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