435b3a877833b24964f2e980e8261e4b6d636035
[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.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;
37
38 /**
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.
43  *
44  * <p>
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.
50  */
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();
55
56     private final @NonNull StreamWriterFacade facade;
57
58     XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer) {
59         facade = new StreamWriterFacade(writer);
60     }
61
62     /**
63      * Create a new writer with the specified context as its root.
64      *
65      * @param writer Output {@link XMLStreamWriter}
66      * @param context Associated {@link SchemaContext}.
67      * @return A new {@link NormalizedNodeStreamWriter}
68      */
69     public static @NonNull NormalizedNodeStreamWriter create(final XMLStreamWriter writer,
70             final SchemaContext context) {
71         return create(writer, context, context);
72     }
73
74     /**
75      * Create a new writer with the specified context and rooted at the specified node.
76      *
77      * @param writer Output {@link XMLStreamWriter}
78      * @param context Associated {@link SchemaContext}.
79      * @param rootNode Root node
80      * @return A new {@link NormalizedNodeStreamWriter}
81      */
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));
85     }
86
87     /**
88      * Create a new writer with the specified context and rooted in the specified schema path.
89      *
90      * @param writer Output {@link XMLStreamWriter}
91      * @param context Associated {@link SchemaContext}.
92      * @param path path
93      * @return A new {@link NormalizedNodeStreamWriter}
94      */
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));
98     }
99
100     /**
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.
103      *
104      * @param writer Output {@link XMLStreamWriter}
105      *
106      * @return A new {@link NormalizedNodeStreamWriter}
107      */
108     public static @NonNull NormalizedNodeStreamWriter createSchemaless(final XMLStreamWriter writer) {
109         return new SchemalessXMLStreamNormalizedNodeStreamWriter(writer);
110     }
111
112     @Override
113     public final ClassToInstanceMap<NormalizedNodeStreamWriterExtension> getExtensions() {
114         return ImmutableClassToInstanceMap.of(NormalizedMetadataStreamWriter.class, this);
115     }
116
117     abstract void startList(NodeIdentifier name);
118
119     abstract void startListItem(PathArgument name) throws IOException;
120
121     abstract String encodeAnnotationValue(@NonNull ValueWriter xmlWriter, @NonNull QName qname, @NonNull Object value)
122             throws XMLStreamException;
123
124     abstract String encodeValue(@NonNull ValueWriter xmlWriter, @NonNull Object value, T context)
125             throws XMLStreamException;
126
127     final void writeValue(final @NonNull Object value, final T context) throws IOException {
128         try {
129             facade.writeCharacters(encodeValue(facade, value, context));
130         } catch (XMLStreamException e) {
131             throw new IOException("Failed to write value", e);
132         }
133     }
134
135     final void startElement(final QName qname) throws IOException {
136         try {
137             facade.writeStartElement(qname);
138         } catch (XMLStreamException e) {
139             throw new IOException("Failed to start element", e);
140         }
141     }
142
143     final void endElement() throws IOException {
144         try {
145             facade.writeEndElement();
146         } catch (XMLStreamException e) {
147             throw new IOException("Failed to end element", e);
148         }
149     }
150
151     final void anyxmlValue(final DOMSource domSource) throws IOException {
152         if (domSource != null) {
153             final Node domNode = requireNonNull(domSource.getNode());
154             try {
155                 facade.writeStreamReader(new DOMSourceXMLStreamReader(domSource));
156             } catch (XMLStreamException e) {
157                 throw new IOException("Unable to transform anyXml value: " + domNode, e);
158             }
159         }
160     }
161
162     @Override
163     public final void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint) throws IOException {
164         startListItem(name);
165     }
166
167     @Override
168     public final void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint)
169             throws IOException {
170         startListItem(identifier);
171     }
172
173     @Override
174     public final void startUnkeyedList(final NodeIdentifier name, final int childSizeHint) {
175         startList(name);
176     }
177
178     @Override
179     public final void startMapNode(final NodeIdentifier name, final int childSizeHint) {
180         startList(name);
181     }
182
183     @Override
184     public final void startOrderedMapNode(final NodeIdentifier name, final int childSizeHint) {
185         startList(name);
186     }
187
188     @Override
189     public final void close() throws IOException {
190         try {
191             facade.close();
192         } catch (XMLStreamException e) {
193             throw new IOException("Failed to close writer", e);
194         }
195     }
196
197     @Override
198     public final void flush() throws IOException {
199         try {
200             facade.flush();
201         } catch (XMLStreamException e) {
202             throw new IOException("Failed to flush writer", e);
203         }
204     }
205
206     @Override
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();
213
214             // FIXME: remove this handling once we have complete mapping to metadata
215             try {
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"));
224                         }
225                         LOG.debug("Ignoring annotation {} value {}", localName, value);
226                     } else {
227                         facade.writeAttribute(localName, (String) value);
228                         continue;
229                     }
230                 } else {
231                     final String prefix = facade.getPrefix(qname.getNamespace(), namespace);
232                     final String attrValue = encodeAnnotationValue(facade, qname, value);
233                     facade.writeAttribute(prefix, namespace, localName, attrValue);
234                 }
235             } catch (final XMLStreamException e) {
236                 throw new IOException("Unable to emit attribute " + qname, e);
237             }
238         }
239     }
240 }