e26c144fbf17abcf769a04e6b94e2ce05a081f17
[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.Optional;
6 import com.google.common.base.Preconditions;
7 import java.net.URI;
8 import java.util.Map.Entry;
9 import javax.annotation.Nonnull;
10 import javax.xml.stream.XMLStreamException;
11 import javax.xml.stream.XMLStreamWriter;
12 import org.opendaylight.yangtools.yang.common.QName;
13 import org.opendaylight.yangtools.yang.common.QNameModule;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
16 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
17 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
18 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
19 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
21 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
22 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
23 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
24 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
30  * by no means final and subject to change as more functionality is centralized here.
31  */
32 @Beta
33 public class XmlStreamUtils {
34     private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
35     private final XmlCodecProvider codecProvider;
36     private final Optional<SchemaContext> schemaContext;
37
38     protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
39         this(codecProvider, null);
40     }
41
42     private XmlStreamUtils(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
43         this.codecProvider = Preconditions.checkNotNull(codecProvider);
44         this.schemaContext = Optional.fromNullable(schemaContext);
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      * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
59      * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
60      *
61      * @param writer XML Stream writer
62      * @param id InstanceIdentifier
63      * @throws XMLStreamException
64      *
65      * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
66      */
67     @Deprecated
68     public static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final YangInstanceIdentifier id) throws XMLStreamException {
69         Preconditions.checkNotNull(writer, "Writer may not be null");
70         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
71
72         final RandomPrefix prefixes = new RandomPrefix();
73         final String str = XmlUtils.encodeIdentifier(prefixes, id);
74         writeNamespaceDeclarations(writer, prefixes.getPrefixes());
75         writer.writeCharacters(str);
76     }
77
78     @VisibleForTesting
79     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
80             throws XMLStreamException {
81         final QName key = attribute.getKey();
82         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
83         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
84         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
85     }
86
87     /**
88      * Write a value into a XML stream writer. This method assumes the start and end of element is
89      * emitted by the caller.
90      *
91      * @param writer XML Stream writer
92      * @param schemaNode Schema node that describes the value
93      * @param value data value
94      * @param parent optional parameter of a module QName owning the leaf definition
95      * @throws XMLStreamException if an encoding problem occurs
96      */
97     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
98         if (value == null) {
99             LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
100             return;
101         }
102
103         Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
104                 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
105
106         TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
107                 ((LeafSchemaNode) schemaNode).getType():
108                 ((LeafListSchemaNode) schemaNode).getType();
109
110         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
111
112         if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
113             LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
114             baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
115         }
116
117         writeValue(writer, baseType, value, parent);
118     }
119
120     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value) throws XMLStreamException {
121         writeValue(writer, schemaNode, value, Optional.<QNameModule>absent());
122     }
123
124     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final QNameModule parent) throws XMLStreamException {
125         writeValue(writer, schemaNode, value, Optional.of(parent));
126     }
127
128     /**
129      * Write a value into a XML stream writer. This method assumes the start and end of element is
130      * emitted by the caller.
131      *
132      * @param writer XML Stream writer
133      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
134      * @param value data value
135      * @param parent optional parameter of a module QName owning the leaf definition
136      * @throws XMLStreamException if an encoding problem occurs
137      */
138     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
139         if (value == null) {
140             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
141             return;
142         }
143         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
144
145         if (baseType instanceof IdentityrefTypeDefinition) {
146             if (parent.isPresent()) {
147                 write(writer, (IdentityrefTypeDefinition) baseType, value, parent);
148             } else {
149                 write(writer, (IdentityrefTypeDefinition) baseType, value, Optional.<QNameModule>absent());
150             }
151         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
152             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
153         } else {
154             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(type);
155             String text;
156             if (codec != null) {
157                 try {
158                     text = codec.serialize(value);
159                 } catch (ClassCastException e) {
160                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, type, e);
161                     text = String.valueOf(value);
162                 }
163             } else {
164                 LOG.error("Failed to find codec for {}, falling back to using stream", type);
165                 text = String.valueOf(value);
166             }
167             writer.writeCharacters(text);
168         }
169     }
170
171     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final QNameModule parent) throws XMLStreamException {
172         writeValue(writer, type, value, Optional.of(parent));
173     }
174
175     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value) throws XMLStreamException {
176         writeValue(writer, type, value, Optional.<QNameModule>absent());
177     }
178
179     @VisibleForTesting
180     static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final IdentityrefTypeDefinition type, @Nonnull final Object value, final Optional<QNameModule>  parent) throws XMLStreamException {
181         if (value instanceof QName) {
182             final QName qname = (QName) value;
183             final String prefix = "x";
184
185             //in case parent is present and same as element namespace write value without namespace
186             if (parent.isPresent() && qname.getNamespace().equals(parent.get().getNamespace())){
187                 writer.writeCharacters(qname.getLocalName());
188             } else {
189                 final String ns = qname.getNamespace().toString();
190                 writer.writeNamespace(prefix, ns);
191                 writer.writeCharacters(prefix + ':' + qname.getLocalName());
192             }
193
194         } else {
195             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
196             writer.writeCharacters(String.valueOf(value));
197         }
198     }
199
200     private void write(@Nonnull final XMLStreamWriter writer, @Nonnull final InstanceIdentifierTypeDefinition type, @Nonnull final Object value) throws XMLStreamException {
201         if (value instanceof YangInstanceIdentifier) {
202             writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
203         } else {
204             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
205             writer.writeCharacters(String.valueOf(value));
206         }
207     }
208
209     public void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value) throws XMLStreamException {
210         if(schemaContext.isPresent()) {
211             RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
212             String serializedValue = iiCodec.serialize(value);
213             writeNamespaceDeclarations(writer,iiCodec.getPrefixes());
214             writer.writeCharacters(serializedValue);
215         } else {
216             LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
217             write(writer,value);
218         }
219     }
220
221     private static void writeNamespaceDeclarations(XMLStreamWriter writer, Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
222         for (Entry<URI, String> e: prefixes) {
223             final String ns = e.getKey().toString();
224             final String p = e.getValue();
225             writer.writeNamespace(p, ns);
226         }
227     }
228
229     public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
230         return new XmlStreamUtils(codecProvider, schemaContext);
231     }
232 }