e74a84a17e6ec6e3b5c13e346ab8d3f4cd4657ed
[controller.git] / opendaylight / md-sal / sal-remoterpc-connector / src / main / java / org / opendaylight / controller / remote / rpc / utils / XmlStreamUtils.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.remote.rpc.utils;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import org.opendaylight.yangtools.yang.common.QName;
13 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
14 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
15 import org.opendaylight.yangtools.yang.data.api.Node;
16 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
19 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
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 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import javax.xml.stream.XMLStreamException;
35 import javax.xml.stream.XMLStreamWriter;
36 import java.net.URI;
37 import java.util.Map.Entry;
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
48     protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
49         this.codecProvider = Preconditions.checkNotNull(codecProvider);
50     }
51
52     /**
53      * Create a new instance encapsulating a particular codec provider.
54      *
55      * @param codecProvider XML codec provider
56      * @return A new instance
57      */
58     public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
59         return new XmlStreamUtils(codecProvider);
60     }
61
62     /**
63      * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
64      * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
65      *
66      * @param data Data node
67      * @return True if the data node will result in empty element body.
68      */
69     public static boolean isEmptyElement(final Node<?> data) {
70         if (data == null) {
71             return true;
72         }
73
74         if (data instanceof CompositeNode) {
75             return ((CompositeNode) data).getValue().isEmpty();
76         }
77         if (data instanceof SimpleNode) {
78             return data.getValue() == null;
79         }
80
81         // Safe default
82         return false;
83     }
84
85     /**
86      * Write an InstanceIdentifier into the output stream. Calling corresponding {@link javax.xml.stream.XMLStreamWriter#writeStartElement(String)}
87      * and {@link javax.xml.stream.XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
88      *
89      * @param writer XML Stream writer
90      * @param id InstanceIdentifier
91      * @throws javax.xml.stream.XMLStreamException
92      */
93     public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
94         Preconditions.checkNotNull(writer, "Writer may not be null");
95         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
96
97         final RandomPrefix prefixes = new RandomPrefix();
98         final String str = XmlUtils.encodeIdentifier(prefixes, id);
99
100         for (Entry<URI, String> e: prefixes.getPrefixes()) {
101             writer.writeNamespace(e.getValue(), e.getKey().toString());
102         }
103         writer.writeCharacters(str);
104     }
105
106     /**
107      * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
108      *
109      * @param writer XML Stream writer
110      * @param data data node
111      * @param schema corresponding schema node, may be null
112      * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
113      */
114     public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
115         // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
116         // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
117
118         writer.writeStartDocument();
119         writeElement(writer, data, schema);
120         writer.writeEndDocument();
121         writer.flush();
122     }
123
124
125     /**
126      * Write an element into a XML stream writer. This includes the element start/end tags and
127      * the value of the element.
128      *
129      * @param writer XML Stream writer
130      * @param data data node
131      * @param schema Schema node
132      * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
133      */
134     public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
135         final QName qname = data.getNodeType();
136         final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
137         final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
138
139         if (isEmptyElement(data)) {
140             writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
141             return;
142         }
143
144         writer.writeStartElement(pfx, qname.getLocalName(), ns);
145         if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
146             for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
147                 writer.writeAttribute(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(), attribute.getValue());
148             }
149         }
150
151         if (data instanceof SimpleNode<?>) {
152             // Simple node
153             if (schema instanceof LeafListSchemaNode) {
154                 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
155             } else if (schema instanceof LeafSchemaNode) {
156                 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
157             } else {
158                 Object value = data.getValue();
159                 if (value != null) {
160                     writer.writeCharacters(String.valueOf(value));
161                 }
162             }
163         } else {
164             // CompositeNode
165             for (Node<?> child : ((CompositeNode) data).getValue()) {
166                 DataSchemaNode childSchema = null;
167                 if (schema instanceof DataNodeContainer) {
168                     childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
169                     if (LOG.isDebugEnabled()) {
170                         if (childSchema == null) {
171                             LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
172                         }
173                     }
174                 }
175
176                 writeElement(writer, child, childSchema);
177             }
178         }
179
180         writer.writeEndElement();
181     }
182
183     /**
184      * Write a value into a XML stream writer. This method assumes the start and end of element is
185      * emitted by the caller.
186      *
187      * @param writer XML Stream writer
188      * @param type type definitions
189      * @param value object value
190      * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
191      */
192     public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
193         if (value == null) {
194             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
195             return;
196         }
197
198         final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
199         if (baseType instanceof IdentityrefTypeDefinition) {
200             write(writer, (IdentityrefTypeDefinition) baseType, value);
201         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
202             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
203         } else {
204             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
205             String text;
206             if (codec != null) {
207                 try {
208                     text = codec.serialize(value);
209                 } catch (ClassCastException e) {
210                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
211                     text = String.valueOf(value);
212                 }
213             } else {
214                 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
215                 text = String.valueOf(value);
216             }
217             writer.writeCharacters(text);
218         }
219     }
220
221     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
222         if (value instanceof QName) {
223             final QName qname = (QName) value;
224             final String prefix;
225             if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
226                 prefix = qname.getPrefix();
227             } else {
228                 prefix = "x";
229             }
230
231             writer.writeNamespace(prefix, qname.getNamespace().toString());
232             writer.writeCharacters(prefix + ':' + qname.getLocalName());
233         } else {
234             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
235             writer.writeCharacters(String.valueOf(value));
236         }
237     }
238
239     private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
240         if (value instanceof YangInstanceIdentifier) {
241             write(writer, (YangInstanceIdentifier)value);
242         } else {
243             LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
244             writer.writeCharacters(String.valueOf(value));
245         }
246     }
247 }