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