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