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