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