Merge branch 'master' of ../controller
[yangtools.git] / yang / 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.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;
17 import java.util.Set;
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;
38
39 /**
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.
44  *
45  * <p>
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.
51  */
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();
56
57     private final @NonNull StreamWriterFacade facade;
58
59     XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
60         facade = new StreamWriterFacade(writer);
61     }
62
63     /**
64      * Create a new writer with the specified context as its root.
65      *
66      * @param writer Output {@link XMLStreamWriter}
67      * @param context Associated {@link SchemaContext}.
68      * @return A new {@link NormalizedNodeStreamWriter}
69      */
70     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
71             final SchemaContext context) {
72         return create(writer, context, context);
73     }
74
75     /**
76      * Create a new writer with the specified context and rooted at the specified node.
77      *
78      * @param writer Output {@link XMLStreamWriter}
79      * @param context Associated {@link SchemaContext}.
80      * @param rootNode Root node
81      * @return A new {@link NormalizedNodeStreamWriter}
82      */
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));
86     }
87
88     /**
89      * Create a new writer with the specified context and rooted in the specified schema path.
90      *
91      * @param writer Output {@link XMLStreamWriter}
92      * @param context Associated {@link SchemaContext}.
93      * @param path path
94      * @return A new {@link NormalizedNodeStreamWriter}
95      */
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));
99     }
100
101     /**
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.
104      *
105      * @param writer Output {@link XMLStreamWriter}
106      *
107      * @return A new {@link NormalizedNodeStreamWriter}
108      */
109     public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
110         return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
111     }
112
113     @Override
114     public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
115         return ImmutableClassToInstanceMap.of(StreamWriterMetadataExtension.class, this);
116     }
117
118     abstract void startAnydata(NodeIdentifier name);
119
120     abstract void startList(NodeIdentifier name);
121
122     abstract void startListItem(PathArgument name) throws IOException;
123
124     abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
125             throws XMLStreamException;
126
127     abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
128             throws XMLStreamException;
129
130     final void writeValue(final @NonNull Object value, final T context) throws IOException {
131         try {
132             facade.writeCharacters(encodeValue(facade, value, context));
133         } catch (XMLStreamException e) {
134             throw new IOException("Failed to write value", e);
135         }
136     }
137
138     final void startElement(final QName qname) throws IOException {
139         try {
140             facade.writeStartElement(qname);
141         } catch (XMLStreamException e) {
142             throw new IOException("Failed to start element", e);
143         }
144     }
145
146     final void endElement() throws IOException {
147         try {
148             facade.writeEndElement();
149         } catch (XMLStreamException e) {
150             throw new IOException("Failed to end element", e);
151         }
152     }
153
154     final void anydataValue(final Object value) throws IOException {
155         if (value instanceof DOMSourceAnydata) {
156             try {
157                 facade.anydataWriteStreamReader(((DOMSourceAnydata) value).toStreamReader());
158             } catch (XMLStreamException e) {
159                 throw new IOException("Unable to transform anydata value: " + value, e);
160             }
161         } else if (value instanceof NormalizedAnydata) {
162             try {
163                 facade.emitNormalizedAnydata((NormalizedAnydata) value);
164             } catch (XMLStreamException e) {
165                 throw new IOException("Unable to emit anydata value: " + value, e);
166             }
167         } else {
168             throw new IllegalStateException("Unexpected anydata value " + value);
169         }
170     }
171
172     final void anyxmlValue(final DOMSource domSource) throws IOException {
173         if (domSource != null) {
174             final Node domNode = requireNonNull(domSource.getNode());
175             try {
176                 facade.anyxmlWriteStreamReader(new DOMSourceXMLStreamReader(domSource));
177             } catch (XMLStreamException e) {
178                 throw new IOException("Unable to transform anyXml value: " + domNode, e);
179             }
180         }
181     }
182
183     @Override
184     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
185         startListItem(name);
186     }
187
188     @Override
189     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
190             throws IOException {
191         startListItem(identifier);
192     }
193
194     @Override
195     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
196         startList(name);
197     }
198
199     @Override
200     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
201         startList(name);
202     }
203
204     @Override
205     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
206         startList(name);
207     }
208
209     @Override
210     public final void close() throws IOException {
211         try {
212             facade.close();
213         } catch (XMLStreamException e) {
214             throw new IOException("Failed to close writer", e);
215         }
216     }
217
218     @Override
219     public final void flush() throws IOException {
220         try {
221             facade.flush();
222         } catch (XMLStreamException e) {
223             throw new IOException("Failed to flush writer", e);
224         }
225     }
226
227     @Override
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();
234
235             // FIXME: remove this handling once we have complete mapping to metadata
236             try {
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"));
245                         }
246                         LOG.debug("Ignoring annotation {} value {}", localName, value);
247                     } else {
248                         facade.writeAttribute(localName, (String) value);
249                         continue;
250                     }
251                 } else {
252                     final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
253                     final String attrValue = encodeAnnotationValue(facade, qname, value);
254                     facade.writeAttribute(prefix, namespace, localName, attrValue);
255                 }
256             } catch (final XMLStreamException e) {
257                 throw new IOException("Unable to emit attribute " + qname, e);
258             }
259         }
260     }
261
262     @Override
263     public final boolean startAnydataNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
264         if (DOMSourceAnydata.class.isAssignableFrom(objectModel)
265                 || NormalizedAnydata.class.isAssignableFrom(objectModel)) {
266             startAnydata(name);
267             startElement(name.getNodeType());
268             return true;
269         }
270         return false;
271     }
272 }