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