Merge "Parent schema node input parameter in JsonParserStream"
[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(XmlCodecProvider codecProvider, 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     public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
100         Preconditions.checkNotNull(writer, "Writer may not be null");
101         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
102
103         final RandomPrefix prefixes = new RandomPrefix();
104         final String str = XmlUtils.encodeIdentifier(prefixes, id);
105
106         for (Entry<URI, String> e: prefixes.getPrefixes()) {
107             final String ns = e.getKey().toString();
108             final String p = e.getValue();
109
110             writer.writeNamespace(p, ns);
111         }
112         writer.writeCharacters(str);
113     }
114
115     /**
116      * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
117      *
118      * @param writer XML Stream writer
119      * @param data data node
120      * @param schema corresponding schema node, may be null
121      * @throws XMLStreamException if an encoding problem occurs
122      */
123     public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
124         // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
125         // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
126
127         writer.writeStartDocument();
128         writeElement(writer, data, schema);
129         writer.writeEndDocument();
130         writer.flush();
131     }
132
133     /**
134      * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
135      * null SchemaNode.
136      *
137      * @param writer XML Stream writer
138      * @param data data node
139      * @throws XMLStreamException if an encoding problem occurs
140      */
141     public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
142         writeDocument(writer, data, null);
143     }
144
145     /**
146      * Write an element into a XML stream writer. This includes the element start/end tags and
147      * the value of the element.
148      *
149      * @param writer XML Stream writer
150      * @param data data node
151      * @param schema Schema node
152      * @throws XMLStreamException if an encoding problem occurs
153      */
154     public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
155         final QName qname = data.getNodeType();
156         final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
157         final String pfx = "";
158
159         if (isEmptyElement(data)) {
160             if (hasAttributes(data)) {
161                 writer.writeStartElement(pfx, qname.getLocalName(), ns);
162                 final RandomPrefix randomPrefix = new RandomPrefix();
163                 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
164                 writer.writeEndElement();
165             } else {
166                 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
167             }
168             return;
169         }
170
171         writer.writeStartElement(pfx, qname.getLocalName(), ns);
172         writeValue(writer, data, schema);
173         writer.writeEndElement();
174     }
175
176     /**
177      * Write a value into a XML stream writer. This method assumes the start and end of element is
178      * emitted by the caller.
179      *
180      * @param writer XML Stream writer
181      * @param data data node
182      * @param schema Schema node
183      * @throws XMLStreamException if an encoding problem occurs
184      */
185     public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
186         if (hasAttributes(data)) {
187             RandomPrefix randomPrefix = new RandomPrefix();
188             writeAttributes(writer, (AttributesContainer) data, randomPrefix);
189         }
190
191         if (data instanceof SimpleNode<?>) {
192             // Simple node
193             if (schema instanceof LeafListSchemaNode || schema instanceof LeafSchemaNode) {
194                 writeValue(writer, schema, data.getValue());
195             } else {
196                 Object value = data.getValue();
197                 if (value != null) {
198                     writer.writeCharacters(String.valueOf(value));
199                 }
200             }
201         } else {
202             // CompositeNode
203             final CompositeNode castedData = ((CompositeNode) data);
204             final DataNodeContainer castedSchema;
205             if (schema instanceof DataNodeContainer) {
206                 castedSchema = (DataNodeContainer) schema;
207             } else {
208                 castedSchema = null;
209             }
210             final Collection<QName> keyLeaves;
211             if (schema instanceof ListSchemaNode) {
212                 keyLeaves = ((ListSchemaNode) schema).getKeyDefinition();
213
214             } else {
215                 keyLeaves = Collections.emptyList();
216
217             }
218             for (QName key : keyLeaves) {
219                 SimpleNode<?> keyLeaf = castedData.getFirstSimpleByName(key);
220                 if(keyLeaf != null) {
221                     writeChildElement(writer,keyLeaf,castedSchema);
222                 }
223             }
224
225             for (Node<?> child : castedData.getValue()) {
226                 if(keyLeaves.contains(child.getNodeType())) {
227                     // Skip key leaf which was written by previous for loop.
228                     continue;
229                 }
230                 writeChildElement(writer,child,castedSchema);
231             }
232         }
233     }
234
235     private void writeChildElement(XMLStreamWriter writer, Node<?> child, DataNodeContainer parentSchema) throws XMLStreamException {
236         DataSchemaNode childSchema = null;
237         if (parentSchema != null) {
238             childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), parentSchema.getChildNodes()).orNull();
239             if ((childSchema == null) && LOG.isDebugEnabled()) {
240                 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
241             }
242         }
243         writeElement(writer, child, childSchema);
244     }
245
246     private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
247         for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
248             writeAttribute(writer, attribute, randomPrefix);
249         }
250     }
251
252     private static boolean hasAttributes(final Node<?> data) {
253         if (data instanceof AttributesContainer) {
254             final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
255             return c != null && !c.isEmpty();
256         } else {
257             return false;
258         }
259     }
260
261     @VisibleForTesting
262     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
263             throws XMLStreamException {
264         final QName key = attribute.getKey();
265         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
266         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
267         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
268     }
269
270     /**
271      * Write a value into a XML stream writer. This method assumes the start and end of element is
272      * emitted by the caller.
273      *
274      * @param writer XML Stream writer
275      * @param schemaNode Schema node that describes the value
276      * @param value data value
277      * @throws XMLStreamException if an encoding problem occurs
278      */
279     public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull SchemaNode schemaNode, final Object value) throws XMLStreamException {
280         if (value == null) {
281             LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
282             return;
283         }
284
285         Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
286                 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
287
288         TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
289                 ((LeafSchemaNode) schemaNode).getType():
290                 ((LeafListSchemaNode) schemaNode).getType();
291
292         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
293
294         if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
295             LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
296             baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
297         }
298
299         writeValue(writer, baseType, value);
300     }
301
302     /**
303      * Write a value into a XML stream writer. This method assumes the start and end of element is
304      * emitted by the caller.
305      *
306      * @param writer XML Stream writer
307      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
308      * @param value data value
309      * @throws XMLStreamException if an encoding problem occurs
310      */
311     public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
312         if (value == null) {
313             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
314             return;
315         }
316         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
317
318         if (baseType instanceof IdentityrefTypeDefinition) {
319             write(writer, (IdentityrefTypeDefinition) baseType, value);
320         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
321             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
322         } else {
323             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
324             String text;
325             if (codec != null) {
326                 try {
327                     text = codec.serialize(value);
328                 } catch (ClassCastException e) {
329                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
330                     text = String.valueOf(value);
331                 }
332             } else {
333                 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
334                 text = String.valueOf(value);
335             }
336             writer.writeCharacters(text);
337         }
338     }
339
340     @SuppressWarnings("deprecation")
341     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
342         if (value instanceof QName) {
343             final QName qname = (QName) value;
344             final String prefix = "x";
345
346             final String ns = qname.getNamespace().toString();
347             writer.writeNamespace(prefix, ns);
348             writer.writeCharacters(prefix + ':' + qname.getLocalName());
349         } else {
350             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
351             writer.writeCharacters(String.valueOf(value));
352         }
353     }
354
355     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
356         if (value instanceof YangInstanceIdentifier) {
357             write(writer, (YangInstanceIdentifier)value);
358         } else {
359             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
360             writer.writeCharacters(String.valueOf(value));
361         }
362     }
363
364     public static XmlStreamUtils create(XmlCodecProvider codecProvider, SchemaContext schemaContext) {
365         return new XmlStreamUtils(codecProvider, schemaContext);
366     }
367 }