8d3890980bfedc11d39b1dbb09efcd663d0c6885
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlStreamUtils.java
1 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
2
3 import com.google.common.annotations.Beta;
4 import com.google.common.annotations.VisibleForTesting;
5 import com.google.common.base.Preconditions;
6 import java.net.URI;
7 import java.util.Map;
8 import java.util.Map.Entry;
9 import javax.annotation.Nonnull;
10 import javax.annotation.Nullable;
11 import javax.xml.stream.XMLStreamException;
12 import javax.xml.stream.XMLStreamWriter;
13 import org.opendaylight.yangtools.yang.common.QName;
14 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
15 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
16 import org.opendaylight.yangtools.yang.data.api.Node;
17 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
20 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
21 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
27 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
28 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
34  * by no means final and subject to change as more functionality is centralized here.
35  */
36 @Beta
37 public class XmlStreamUtils {
38     private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
39     private final XmlCodecProvider codecProvider;
40
41     protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
42         this.codecProvider = Preconditions.checkNotNull(codecProvider);
43     }
44
45     /**
46      * Create a new instance encapsulating a particular codec provider.
47      *
48      * @param codecProvider XML codec provider
49      * @return A new instance
50      */
51     public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
52         return new XmlStreamUtils(codecProvider);
53     }
54
55     /**
56      * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
57      * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
58      *
59      * @param data Data node
60      * @return True if the data node will result in empty element body.
61      */
62     public static boolean isEmptyElement(final Node<?> data) {
63         if (data == null) {
64             return true;
65         }
66
67         if (data instanceof CompositeNode) {
68             return ((CompositeNode) data).getValue().isEmpty();
69         }
70         if (data instanceof SimpleNode) {
71             return data.getValue() == null;
72         }
73
74         // Safe default
75         return false;
76     }
77
78     /**
79      * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
80      * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
81      *
82      * @param writer XML Stream writer
83      * @param id InstanceIdentifier
84      * @throws XMLStreamException
85      */
86     public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
87         Preconditions.checkNotNull(writer, "Writer may not be null");
88         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
89
90         final RandomPrefix prefixes = new RandomPrefix();
91         final String str = XmlUtils.encodeIdentifier(prefixes, id);
92
93         for (Entry<URI, String> e: prefixes.getPrefixes()) {
94             final String ns = e.getKey().toString();
95             final String p = e.getValue();
96
97             writer.writeNamespace(p, ns);
98         }
99         writer.writeCharacters(str);
100     }
101
102     /**
103      * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
104      *
105      * @param writer XML Stream writer
106      * @param data data node
107      * @param schema corresponding schema node, may be null
108      * @throws XMLStreamException if an encoding problem occurs
109      */
110     public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
111         // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
112         // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
113
114         writer.writeStartDocument();
115         writeElement(writer, data, schema);
116         writer.writeEndDocument();
117         writer.flush();
118     }
119
120     /**
121      * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
122      * null SchemaNode.
123      *
124      * @param writer XML Stream writer
125      * @param data data node
126      * @throws XMLStreamException if an encoding problem occurs
127      */
128     public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
129         writeDocument(writer, data, null);
130     }
131
132     /**
133      * Write an element into a XML stream writer. This includes the element start/end tags and
134      * the value of the element.
135      *
136      * @param writer XML Stream writer
137      * @param data data node
138      * @param schema Schema node
139      * @throws XMLStreamException if an encoding problem occurs
140      */
141     public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
142         final QName qname = data.getNodeType();
143         final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
144         final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
145
146         if (isEmptyElement(data)) {
147             if (hasAttributes(data)) {
148                 writer.writeStartElement(pfx, qname.getLocalName(), ns);
149                 final RandomPrefix randomPrefix = new RandomPrefix();
150                 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
151                 writer.writeEndElement();
152             } else {
153                 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
154             }
155             return;
156         }
157
158         writer.writeStartElement(pfx, qname.getLocalName(), ns);
159         writeValue(writer, data, schema);
160         writer.writeEndElement();
161     }
162
163     /**
164      * Write a value into a XML stream writer. This method assumes the start and end of element is
165      * emitted by the caller.
166      *
167      * @param writer XML Stream writer
168      * @param data data node
169      * @param schema Schema node
170      * @throws XMLStreamException if an encoding problem occurs
171      */
172     public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
173         if (hasAttributes(data)) {
174             RandomPrefix randomPrefix = new RandomPrefix();
175             writeAttributes(writer, (AttributesContainer) data, randomPrefix);
176         }
177
178         if (data instanceof SimpleNode<?>) {
179             // Simple node
180             if (schema instanceof LeafListSchemaNode) {
181                 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
182             } else if (schema instanceof LeafSchemaNode) {
183                 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
184             } else {
185                 Object value = data.getValue();
186                 if (value != null) {
187                     writer.writeCharacters(String.valueOf(value));
188                 }
189             }
190         } else {
191             // CompositeNode
192             for (Node<?> child : ((CompositeNode) data).getValue()) {
193                 DataSchemaNode childSchema = null;
194                 if (schema instanceof DataNodeContainer) {
195                     childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
196                 } else if ((childSchema == null) && LOG.isDebugEnabled()) {
197                     LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
198                 }
199                 writeElement(writer, child, childSchema);
200             }
201         }
202     }
203
204     private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
205         for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
206             writeAttribute(writer, attribute, randomPrefix);
207         }
208     }
209
210     private static boolean hasAttributes(final Node<?> data) {
211         if (data instanceof AttributesContainer) {
212             final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
213             return c != null && !c.isEmpty();
214         } else {
215             return false;
216         }
217     }
218
219     @VisibleForTesting
220     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
221             throws XMLStreamException {
222         final QName key = attribute.getKey();
223         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
224         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
225         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
226     }
227
228     /**
229      * Write a value into a XML stream writer. This method assumes the start and end of element is
230      * emitted by the caller.
231      *
232      * @param writer XML Stream writer
233      * @param type data type
234      * @param value data value
235      * @throws XMLStreamException if an encoding problem occurs
236      */
237     public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
238         if (value == null) {
239             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
240             return;
241         }
242
243         final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
244         if (baseType instanceof IdentityrefTypeDefinition) {
245             write(writer, (IdentityrefTypeDefinition) baseType, value);
246         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
247             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
248         } else {
249             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
250             String text;
251             if (codec != null) {
252                 try {
253                     text = codec.serialize(value);
254                 } catch (ClassCastException e) {
255                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
256                     text = String.valueOf(value);
257                 }
258             } else {
259                 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
260                 text = String.valueOf(value);
261             }
262             writer.writeCharacters(text);
263         }
264     }
265
266     @SuppressWarnings("deprecation")
267     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
268         if (value instanceof QName) {
269             final QName qname = (QName) value;
270             final String prefix;
271             if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
272                 prefix = qname.getPrefix();
273             } else {
274                 prefix = "x";
275             }
276
277             final String ns = qname.getNamespace().toString();
278             writer.writeNamespace(prefix, ns);
279             writer.writeCharacters(prefix + ':' + qname.getLocalName());
280         } else {
281             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
282             writer.writeCharacters(String.valueOf(value));
283         }
284     }
285
286     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
287         if (value instanceof YangInstanceIdentifier) {
288             write(writer, (YangInstanceIdentifier)value);
289         } else {
290             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
291             writer.writeCharacters(String.valueOf(value));
292         }
293     }
294 }