BUG-865: Remove deprecated XmlStreamUtils constructor
[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 final 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     private XmlStreamUtils(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
48         this.codecProvider = Preconditions.checkNotNull(codecProvider);
49         this.schemaContext = Optional.fromNullable(schemaContext);
50     }
51
52     /**
53      * Create a new instance encapsulating a particular codec provider.
54      *
55      * @param codecProvider XML codec provider
56      * @return A new instance
57      */
58     public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
59         return new XmlStreamUtils(codecProvider, null);
60     }
61
62     public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
63         return new XmlStreamUtils(codecProvider, schemaContext);
64     }
65
66     @VisibleForTesting
67     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
68             throws XMLStreamException {
69         final QName key = attribute.getKey();
70         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
71         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
72         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
73     }
74
75     /**
76      * Write a value into a XML stream writer. This method assumes the start and end of element is
77      * emitted by the caller.
78      *
79      * @param writer XML Stream writer
80      * @param schemaNode Schema node that describes the value
81      * @param value data value
82      * @param parent optional parameter of a module QName owning the leaf definition
83      * @throws XMLStreamException if an encoding problem occurs
84      */
85     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
86         if (value == null) {
87             LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
88             return;
89         }
90
91         Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode || schemaNode instanceof LeafListSchemaNode,
92                 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point", schemaNode.getQName());
93
94         TypeDefinition<?> type = schemaNode instanceof LeafSchemaNode ?
95                 ((LeafSchemaNode) schemaNode).getType():
96                 ((LeafListSchemaNode) schemaNode).getType();
97
98         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
99
100         if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
101             LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
102             baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
103             Verify.verifyNotNull(baseType, "Unable to find base type for leafref node '%s'.", schemaNode.getPath());
104         }
105
106         writeValue(writer, baseType, value, parent);
107     }
108
109     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value) throws XMLStreamException {
110         writeValue(writer, schemaNode, value, Optional.absent());
111     }
112
113     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final QNameModule parent) throws XMLStreamException {
114         writeValue(writer, schemaNode, value, Optional.of(parent));
115     }
116
117     /**
118      * Write a value into a XML stream writer. This method assumes the start and end of element is
119      * emitted by the caller.
120      *
121      * @param writer XML Stream writer
122      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
123      * @param value data value
124      * @param parent optional parameter of a module QName owning the leaf definition
125      * @throws XMLStreamException if an encoding problem occurs
126      */
127     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final Optional<QNameModule> parent) 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             if (parent.isPresent()) {
136                 write(writer, (IdentityrefTypeDefinition) baseType, value, parent);
137             } else {
138                 write(writer, (IdentityrefTypeDefinition) baseType, value, Optional.absent());
139             }
140         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
141             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
142         } else {
143             final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(type);
144             String text;
145             if (codec != null) {
146                 try {
147                     text = codec.serialize(value);
148                 } catch (ClassCastException e) {
149                     LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, type, e);
150                     text = String.valueOf(value);
151                 }
152             } else {
153                 LOG.error("Failed to find codec for {}, falling back to using stream", type);
154                 text = String.valueOf(value);
155             }
156             writer.writeCharacters(text);
157         }
158     }
159
160     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final QNameModule parent) throws XMLStreamException {
161         writeValue(writer, type, value, Optional.of(parent));
162     }
163
164     public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value) throws XMLStreamException {
165         writeValue(writer, type, value, Optional.absent());
166     }
167
168     @VisibleForTesting
169     static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final IdentityrefTypeDefinition type, @Nonnull final Object value, final Optional<QNameModule>  parent) throws XMLStreamException {
170         if (value instanceof QName) {
171             final QName qname = (QName) value;
172             final String prefix = "x";
173
174             //in case parent is present and same as element namespace write value without namespace
175             if (parent.isPresent() && qname.getNamespace().equals(parent.get().getNamespace())){
176                 writer.writeCharacters(qname.getLocalName());
177             } else {
178                 final String ns = qname.getNamespace().toString();
179                 writer.writeNamespace(prefix, ns);
180                 writer.writeCharacters(prefix + ':' + qname.getLocalName());
181             }
182
183         } else {
184             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
185             writer.writeCharacters(String.valueOf(value));
186         }
187     }
188
189     private void write(@Nonnull final XMLStreamWriter writer, @Nonnull final InstanceIdentifierTypeDefinition type, @Nonnull final Object value) throws XMLStreamException {
190         if (value instanceof YangInstanceIdentifier) {
191             writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
192         } else {
193             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
194             writer.writeCharacters(String.valueOf(value));
195         }
196     }
197
198     public void writeInstanceIdentifier(final XMLStreamWriter writer, final YangInstanceIdentifier value) throws XMLStreamException {
199         if (schemaContext.isPresent()) {
200             RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
201             String serializedValue = iiCodec.serialize(value);
202             writeNamespaceDeclarations(writer,iiCodec.getPrefixes());
203             writer.writeCharacters(serializedValue);
204         } else {
205             LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
206             writeInstanceIdentifier(writer, value);
207         }
208     }
209
210     private static void writeNamespaceDeclarations(final XMLStreamWriter writer, final Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
211         for (Entry<URI, String> e: prefixes) {
212             final String ns = e.getKey().toString();
213             final String p = e.getValue();
214             writer.writeNamespace(p, ns);
215         }
216     }
217 }