Merge "very basic tests for yang-binding-util"
[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 #writeDataDocument(XMLStreamWriter, CompositeNode, SchemaNode, XmlCodecProvider)} with
122      * null SchemaNode.
123      *
124      * @param writer XML Stream writer
125      * @param data data node
126      * @param schema corresponding schema node, may be null
127      * @throws XMLStreamException if an encoding problem occurs
128      */
129     public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
130         writeDocument(writer, data, null);
131     }
132
133     /**
134      * Write an element into a XML stream writer. This includes the element start/end tags and
135      * the value of the element.
136      *
137      * @param writer XML Stream writer
138      * @param data data node
139      * @param schema Schema node
140      * @throws XMLStreamException if an encoding problem occurs
141      */
142     public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
143         final QName qname = data.getNodeType();
144         final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
145         final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
146
147         if (isEmptyElement(data)) {
148             if (hasAttributes(data)) {
149                 writer.writeStartElement(pfx, qname.getLocalName(), ns);
150                 final RandomPrefix randomPrefix = new RandomPrefix();
151                 writeAttributes(writer, (AttributesContainer) data, randomPrefix);
152                 writer.writeEndElement();
153             } else {
154                 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
155             }
156             return;
157         }
158
159         writer.writeStartElement(pfx, qname.getLocalName(), ns);
160         writeValue(writer, data, schema);
161         writer.writeEndElement();
162     }
163
164     /**
165      * Write a value into a XML stream writer. This method assumes the start and end of element is
166      * emitted by the caller.
167      *
168      * @param writer XML Stream writer
169      * @param data data node
170      * @param schema Schema node
171      * @throws XMLStreamException if an encoding problem occurs
172      */
173     public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
174         if (hasAttributes(data)) {
175             RandomPrefix randomPrefix = new RandomPrefix();
176             writeAttributes(writer, (AttributesContainer) data, randomPrefix);
177         }
178
179         if (data instanceof SimpleNode<?>) {
180             // Simple node
181             if (schema instanceof LeafListSchemaNode) {
182                 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
183             } else if (schema instanceof LeafSchemaNode) {
184                 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
185             } else {
186                 Object value = data.getValue();
187                 if (value != null) {
188                     writer.writeCharacters(String.valueOf(value));
189                 }
190             }
191         } else {
192             // CompositeNode
193             for (Node<?> child : ((CompositeNode) data).getValue()) {
194                 DataSchemaNode childSchema = null;
195                 if (schema instanceof DataNodeContainer) {
196                     childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
197                     if (LOG.isDebugEnabled()) {
198                         if (childSchema == null) {
199                             LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
200                         }
201                     }
202                 }
203
204                 writeElement(writer, child, childSchema);
205             }
206         }
207     }
208
209     private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
210         for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
211             writeAttribute(writer, attribute, randomPrefix);
212         }
213     }
214
215     private static boolean hasAttributes(final Node<?> data) {
216         if (data instanceof AttributesContainer) {
217             final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
218             return c != null && !c.isEmpty();
219         } else {
220             return false;
221         }
222     }
223
224     @VisibleForTesting
225     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
226             throws XMLStreamException {
227         final QName key = attribute.getKey();
228         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
229         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
230         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
231     }
232
233     /**
234      * Write a value into a XML stream writer. This method assumes the start and end of element is
235      * emitted by the caller.
236      *
237      * @param writer XML Stream writer
238      * @param type data type
239      * @param value data value
240      * @throws XMLStreamException if an encoding problem occurs
241      */
242     public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
243         if (value == null) {
244             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
245             return;
246         }
247
248         final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
249         if (baseType instanceof IdentityrefTypeDefinition) {
250             write(writer, (IdentityrefTypeDefinition) baseType, value);
251         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
252             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
253         } else {
254             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
255             String text;
256             if (codec != null) {
257                 try {
258                     text = codec.serialize(value);
259                 } catch (ClassCastException e) {
260                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
261                     text = String.valueOf(value);
262                 }
263             } else {
264                 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
265                 text = String.valueOf(value);
266             }
267             writer.writeCharacters(text);
268         }
269     }
270
271     @SuppressWarnings("deprecation")
272     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
273         if (value instanceof QName) {
274             final QName qname = (QName) value;
275             final String prefix;
276             if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
277                 prefix = qname.getPrefix();
278             } else {
279                 prefix = "x";
280             }
281
282             final String ns = qname.getNamespace().toString();
283             writer.writeNamespace(prefix, ns);
284             writer.writeCharacters(prefix + ':' + qname.getLocalName());
285         } else {
286             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
287             writer.writeCharacters(String.valueOf(value));
288         }
289     }
290
291     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
292         if (value instanceof YangInstanceIdentifier) {
293             write(writer, (YangInstanceIdentifier)value);
294         } else {
295             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
296             writer.writeCharacters(String.valueOf(value));
297         }
298     }
299 }