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.NormalizedMetadataStreamWriter;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
28 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
30 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Node;
39 * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter}, resulting in an
40 * RFC6020 XML encoding. There are 2 versions of this class, one that takes a SchemaContext and encodes values
41 * appropriately according to the YANG schema. The other is schema-less and merely outputs values using toString. The
42 * latter is intended for debugging where doesn't have a SchemaContext available and isn't meant for production use.
45 * Due to backwards compatibility reasons this writer recognizes RFC7952 metadata include keys QNames with empty URI
46 * (as exposed via {@link XmlParserStream#LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an
47 * unqualified XML attribute and their value can be assumed to be a String. Furthermore, this extends to qualified
48 * attributes, which uses the proper namespace, but will not bind to a proper module revision. This caveat will be
49 * removed in a future version.
51 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamWriter,
52 NormalizedMetadataStreamWriter {
53 private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
54 private static final Set<String> BROKEN_ATTRIBUTES = ConcurrentHashMap.newKeySet();
56 private final @NonNull StreamWriterFacade facade;
58 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
59 facade = new StreamWriterFacade(writer);
63 * Create a new writer with the specified context as its root.
65 * @param writer Output {@link XMLStreamWriter}
66 * @param context Associated {@link SchemaContext}.
67 * @return A new {@link NormalizedNodeStreamWriter}
69 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
70 final SchemaContext context) {
71 return create(writer, context, context);
75 * Create a new writer with the specified context and rooted at the specified node.
77 * @param writer Output {@link XMLStreamWriter}
78 * @param context Associated {@link SchemaContext}.
79 * @param rootNode Root node
80 * @return A new {@link NormalizedNodeStreamWriter}
82 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
83 final DataNodeContainer rootNode) {
84 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(rootNode));
88 * Create a new writer with the specified context and rooted in the specified schema path.
90 * @param writer Output {@link XMLStreamWriter}
91 * @param context Associated {@link SchemaContext}.
93 * @return A new {@link NormalizedNodeStreamWriter}
95 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
96 final SchemaPath path) {
97 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(context, path));
101 * Create a new schema-less writer. Note that this version is intended for debugging
102 * where doesn't have a SchemaContext available and isn't meant for production use.
104 * @param writer Output {@link XMLStreamWriter}
106 * @return A new {@link NormalizedNodeStreamWriter}
108 public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
109 return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
113 public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
114 return ImmutableClassToInstanceMap.of(NormalizedMetadataStreamWriter.class, this);
117 abstract void startList(NodeIdentifier name);
119 abstract void startListItem(PathArgument name) throws IOException;
121 abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
122 throws XMLStreamException;
124 abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
125 throws XMLStreamException;
127 final void writeValue(final @NonNull Object value, final T context) throws IOException {
129 facade.writeCharacters(encodeValue(facade, value, context));
130 } catch (XMLStreamException e) {
131 throw new IOException("Failed to write value", e);
135 final void startElement(final QName qname) throws IOException {
137 facade.writeStartElement(qname);
138 } catch (XMLStreamException e) {
139 throw new IOException("Failed to start element", e);
143 final void endElement() throws IOException {
145 facade.writeEndElement();
146 } catch (XMLStreamException e) {
147 throw new IOException("Failed to end element", e);
151 final void anyxmlValue(final DOMSource domSource) throws IOException {
152 if (domSource != null) {
153 final Node domNode = requireNonNull(domSource.getNode());
155 facade.writeStreamReader(new DOMSourceXMLStreamReader(domSource));
156 } catch (XMLStreamException e) {
157 throw new IOException("Unable to transform anyXml value: " + domNode, e);
163 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
168 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
170 startListItem(identifier);
174 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
179 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
184 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
189 public final void close() throws IOException {
192 } catch (XMLStreamException e) {
193 throw new IOException("Failed to close writer", e);
198 public final void flush() throws IOException {
201 } catch (XMLStreamException e) {
202 throw new IOException("Failed to flush writer", e);
207 public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException {
208 for (final Entry<QName, Object> entry : attributes.entrySet()) {
209 final QName qname = entry.getKey();
210 final String namespace = qname.getNamespace().toString();
211 final String localName = qname.getLocalName();
212 final Object value = entry.getValue();
214 // FIXME: remove this handling once we have complete mapping to metadata
216 if (namespace.isEmpty()) {
217 // Legacy attribute, which is expected to be a String
218 StreamWriterFacade.warnLegacyAttribute(localName);
219 if (!(value instanceof String)) {
220 if (BROKEN_ATTRIBUTES.add(localName)) {
221 LOG.warn("Unbound annotation {} does not have a String value, ignoring it. Please fix the "
222 + "source of this annotation either by formatting it to a String or removing its "
223 + "use", localName, new Throwable("Call stack"));
225 LOG.debug("Ignoring annotation {} value {}", localName, value);
227 facade.writeAttribute(localName, (String) value);
231 final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
232 final String attrValue = encodeAnnotationValue(facade, qname, value);
233 facade.writeAttribute(prefix, namespace, localName, attrValue);
235 } catch (final XMLStreamException e) {
236 throw new IOException("Unable to emit attribute " + qname, e);