Drop unneeded generic type specifiers
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / retest / 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.retest;
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.data.impl.codec.xml.XmlCodecProvider;
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 by no means final
39  * and subject to change as more functionality is centralized here.
40  *
41  * @deprecated Used for interim testing, to be removed in near future.
42  */
43 @Deprecated
44 @Beta
45 public class XmlStreamUtils {
46     private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
47     private final XmlCodecProvider codecProvider;
48     private final Optional<SchemaContext> schemaContext;
49
50     protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
51         this(codecProvider, null);
52     }
53
54     private XmlStreamUtils(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
55         this.codecProvider = Preconditions.checkNotNull(codecProvider);
56         this.schemaContext = Optional.fromNullable(schemaContext);
57     }
58
59     /**
60      * Create a new instance encapsulating a particular codec provider.
61      *
62      * @param codecProvider
63      *            XML codec provider
64      * @return A new instance
65      */
66     public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
67         return new XmlStreamUtils(codecProvider);
68     }
69
70     /**
71      * Write an InstanceIdentifier into the output stream. Calling corresponding
72      * {@link XMLStreamWriter#writeStartElement(String)} and {@link XMLStreamWriter#writeEndElement()} is the
73      * responsibility of the caller.
74      *
75      * @param writer
76      *            XML Stream writer
77      * @param id
78      *            InstanceIdentifier
79      * @throws XMLStreamException XMLStreamException object
80      *
81      * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
82      */
83     @Deprecated
84     public static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final YangInstanceIdentifier id)
85             throws XMLStreamException {
86         Preconditions.checkNotNull(writer, "Writer may not be null");
87         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
88
89         final RandomPrefix prefixes = new RandomPrefix();
90         final String str = XmlUtils.encodeIdentifier(prefixes, id);
91         writeNamespaceDeclarations(writer, prefixes.getPrefixes());
92         writer.writeCharacters(str);
93     }
94
95     @VisibleForTesting
96     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute,
97             final RandomPrefix randomPrefix) throws XMLStreamException {
98         final QName key = attribute.getKey();
99         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
100         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
101         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
102     }
103
104     /**
105      * Write a value into a XML stream writer. This method assumes the start and end of element is emitted by the
106      * caller.
107      *
108      * @param writer
109      *            XML Stream writer
110      * @param schemaNode
111      *            Schema node that describes the value
112      * @param value
113      *            data value
114      * @param parent
115      *            optional parameter of a module QName owning the leaf definition
116      * @throws XMLStreamException
117      *             if an encoding problem occurs
118      */
119     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode,
120             final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
121         if (value == null) {
122             LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode
123                     .getQName().getLocalName());
124             return;
125         }
126
127         Preconditions
128                 .checkArgument(
129                         schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
130                         "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point",
131                         schemaNode.getQName());
132
133         TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ? ((LeafSchemaNode) schemaNode).getType()
134                 : ((LeafListSchemaNode) schemaNode).getType();
135
136         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
137
138         if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
139             LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
140             baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
141         }
142
143         writeValue(writer, baseType, value, parent);
144     }
145
146     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode,
147             final Object value) throws XMLStreamException {
148         writeValue(writer, schemaNode, value, Optional.absent());
149     }
150
151     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode,
152             final Object value, final QNameModule parent) throws XMLStreamException {
153         writeValue(writer, schemaNode, value, Optional.of(parent));
154     }
155
156     /**
157      * Write a value into a XML stream writer. This method assumes the start and end of element is emitted by the
158      * caller.
159      *
160      * @param writer
161      *            XML Stream writer
162      * @param type
163      *            data type. In case of leaf ref this should be the type of leaf being referenced
164      * @param value
165      *            data value
166      * @param parent
167      *            optional parameter of a module QName owning the leaf definition
168      * @throws XMLStreamException
169      *             if an encoding problem occurs
170      */
171     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type,
172             final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
173         if (value == null) {
174             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName()
175                     .getLocalName());
176             return;
177         }
178         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
179
180         if (baseType instanceof IdentityrefTypeDefinition) {
181             if (parent.isPresent()) {
182                 write(writer, (IdentityrefTypeDefinition) baseType, value, parent);
183             } else {
184                 write(writer, (IdentityrefTypeDefinition) baseType, value, Optional.absent());
185             }
186         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
187             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
188         } else {
189             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(type);
190             String text;
191             if (codec != null) {
192                 try {
193                     text = codec.serialize(value);
194                 } catch (ClassCastException e) {
195                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.",
196                             value, type, e);
197                     text = String.valueOf(value);
198                 }
199             } else {
200                 LOG.error("Failed to find codec for {}, falling back to using stream", type);
201                 text = String.valueOf(value);
202             }
203             writer.writeCharacters(text);
204         }
205     }
206
207     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type,
208             final Object value, final QNameModule parent) throws XMLStreamException {
209         writeValue(writer, type, value, Optional.of(parent));
210     }
211
212     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type,
213             final Object value) throws XMLStreamException {
214         writeValue(writer, type, value, Optional.absent());
215     }
216
217     @VisibleForTesting
218     static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final IdentityrefTypeDefinition type,
219             @Nonnull final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
220         if (value instanceof QName) {
221             final QName qname = (QName) value;
222             final String prefix = "x";
223
224             // in case parent is present and same as element namespace write value without namespace
225             if (parent.isPresent() && qname.getNamespace().equals(parent.get().getNamespace())) {
226                 writer.writeCharacters(qname.getLocalName());
227             } else {
228                 final String ns = qname.getNamespace().toString();
229                 writer.writeNamespace(prefix, ns);
230                 writer.writeCharacters(prefix + ':' + qname.getLocalName());
231             }
232
233         } else {
234             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName()
235                     .getLocalName(), value.getClass());
236             writer.writeCharacters(String.valueOf(value));
237         }
238     }
239
240     private void write(@Nonnull final XMLStreamWriter writer, @Nonnull final InstanceIdentifierTypeDefinition type,
241             @Nonnull final Object value) throws XMLStreamException {
242         if (value instanceof YangInstanceIdentifier) {
243             writeInstanceIdentifier(writer, (YangInstanceIdentifier) value);
244         } else {
245             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type
246                     .getQName().getLocalName(), value.getClass());
247             writer.writeCharacters(String.valueOf(value));
248         }
249     }
250
251     public void writeInstanceIdentifier(final XMLStreamWriter writer, final YangInstanceIdentifier value) throws XMLStreamException {
252         if (schemaContext.isPresent()) {
253             RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(
254                     schemaContext.get());
255             String serializedValue = iiCodec.serialize(value);
256             writeNamespaceDeclarations(writer, iiCodec.getPrefixes());
257             writer.writeCharacters(serializedValue);
258         } else {
259             LOG.warn("Schema context not present in {}, serializing {} without schema.", this, value);
260             write(writer, value);
261         }
262     }
263
264     private static void writeNamespaceDeclarations(final XMLStreamWriter writer, final Iterable<Entry<URI, String>> prefixes)
265             throws XMLStreamException {
266         for (Entry<URI, String> e : prefixes) {
267             final String ns = e.getKey().toString();
268             final String p = e.getValue();
269             writer.writeNamespace(p, ns);
270         }
271     }
272
273     public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
274         return new XmlStreamUtils(codecProvider, schemaContext);
275     }
276 }