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