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