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