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.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.NormalizedAnydata;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriterExtension;
31 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Node;
40 * A {@link NormalizedNodeStreamWriter} which translates the events into an {@link XMLStreamWriter}, resulting in an
41 * RFC6020 XML encoding. There are 2 versions of this class, one that takes a SchemaContext and encodes values
42 * appropriately according to the YANG schema. The other is schema-less and merely outputs values using toString. The
43 * latter is intended for debugging where doesn't have a SchemaContext available and isn't meant for production use.
46 * Due to backwards compatibility reasons this writer recognizes RFC7952 metadata include keys QNames with empty URI
47 * (as exposed via {@link XmlParserStream#LEGACY_ATTRIBUTE_NAMESPACE}) as their QNameModule. These indicate an
48 * unqualified XML attribute and their value can be assumed to be a String. Furthermore, this extends to qualified
49 * attributes, which uses the proper namespace, but will not bind to a proper module revision. This caveat will be
50 * removed in a future version.
52 public abstract class XMLStreamNormalizedNodeStreamWriter<T> implements NormalizedNodeStreamWriter,
53 StreamWriterMetadataExtension {
54 private static final Logger LOG = LoggerFactory.getLogger(XMLStreamNormalizedNodeStreamWriter.class);
55 private static final Set<String> BROKEN_ATTRIBUTES = ConcurrentHashMap.newKeySet();
57 private final @NonNull StreamWriterFacade facade;
59 XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
60 facade = new StreamWriterFacade(writer);
64 * Create a new writer with the specified context as its root.
66 * @param writer Output {@link XMLStreamWriter}
67 * @param context Associated {@link SchemaContext}.
68 * @return A new {@link NormalizedNodeStreamWriter}
70 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
71 final SchemaContext context) {
72 return create(writer, context, context);
76 * Create a new writer with the specified context and rooted at the specified node.
78 * @param writer Output {@link XMLStreamWriter}
79 * @param context Associated {@link SchemaContext}.
80 * @param rootNode Root node
81 * @return A new {@link NormalizedNodeStreamWriter}
83 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
84 final DataNodeContainer rootNode) {
85 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(rootNode));
89 * Create a new writer with the specified context and rooted in the specified schema path.
91 * @param writer Output {@link XMLStreamWriter}
92 * @param context Associated {@link SchemaContext}.
94 * @return A new {@link NormalizedNodeStreamWriter}
96 public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer, final SchemaContext context,
97 final SchemaPath path) {
98 return new SchemaAwareXMLStreamNormalizedNodeStreamWriter(writer, context, SchemaTracker.create(context, path));
102 * Create a new schema-less writer. Note that this version is intended for debugging
103 * where doesn't have a SchemaContext available and isn't meant for production use.
105 * @param writer Output {@link XMLStreamWriter}
107 * @return A new {@link NormalizedNodeStreamWriter}
109 public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
110 return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
114 public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
115 return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
118 abstract void startAnydata(NodeIdentifier name);
120 abstract void startList(NodeIdentifier name);
122 abstract void startListItem(PathArgument name) throws IOException;
124 abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
125 throws XMLStreamException;
127 abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
128 throws XMLStreamException;
130 final void writeValue(final @NonNull Object value, final T context) throws IOException {
132 facade.writeCharacters(encodeValue(facade, value, context));
133 } catch (XMLStreamException e) {
134 throw new IOException("Failed to write value", e);
138 final void startElement(final QName qname) throws IOException {
140 facade.writeStartElement(qname);
141 } catch (XMLStreamException e) {
142 throw new IOException("Failed to start element", e);
146 final void endElement() throws IOException {
148 facade.writeEndElement();
149 } catch (XMLStreamException e) {
150 throw new IOException("Failed to end element", e);
154 final void anydataValue(final Object value) throws IOException {
155 if (value instanceof DOMSourceAnydata) {
157 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
158 } catch (XMLStreamException e) {
159 throw new IOException("Unable to transform anydata value: " + value, e);
161 } else if (value instanceof NormalizedAnydata) {
163 facade.emitNormalizedAnydata((NormalizedAnydata) value);
164 } catch (XMLStreamException e) {
165 throw new IOException("Unable to emit anydata value: " + value, e);
168 throw new IllegalStateException("Unexpected anydata value " + value);
172 final void anyxmlValue(final DOMSource domSource) throws IOException {
173 if (domSource != null) {
174 final Node domNode = requireNonNull(domSource.getNode());
176 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
177 } catch (XMLStreamException e) {
178 throw new IOException("Unable to transform anyXml value: " + domNode, e);
184 public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
189 public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
191 startListItem(identifier);
195 public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
200 public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
205 public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
210 public final void close() throws IOException {
213 } catch (XMLStreamException e) {
214 throw new IOException("Failed to close writer", e);
219 public final void flush() throws IOException {
222 } catch (XMLStreamException e) {
223 throw new IOException("Failed to flush writer", e);
228 public final void metadata(final ImmutableMap<QName, Object> attributes) throws IOException {
229 for (final Entry<QName, Object> entry : attributes.entrySet()) {
230 final QName qname = entry.getKey();
231 final String namespace = qname.getNamespace().toString();
232 final String localName = qname.getLocalName();
233 final Object value = entry.getValue();
235 // FIXME: remove this handling once we have complete mapping to metadata
237 if (namespace.isEmpty()) {
238 // Legacy attribute, which is expected to be a String
239 StreamWriterFacade.warnLegacyAttribute(localName);
240 if (!(value instanceof String)) {
241 if (BROKEN_ATTRIBUTES.add(localName)) {
242 LOG.warn("Unbound annotation {} does not have a String value, ignoring it. Please fix the "
243 + "source of this annotation either by formatting it to a String or removing its "
244 + "use", localName, new Throwable("Call stack"));
246 LOG.debug("Ignoring annotation {} value {}", localName, value);
248 facade.writeAttribute(localName, (String) value);
252 final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
253 final String attrValue = encodeAnnotationValue(facade, qname, value);
254 facade.writeAttribute(prefix, namespace, localName, attrValue);
256 } catch (final XMLStreamException e) {
257 throw new IOException("Unable to emit attribute " + qname, e);
263 public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
264 if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
265 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
267 startElement(name.getNodeType());