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