Rename XmlStreamUtils
[yangtools.git] / yang / yang-data-codec-xml / src / main / java / org / opendaylight / yangtools / yang / data / codec / xml / XMLStreamWriterUtils.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.codec.xml;
10
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import java.util.Map.Entry;
14 import javax.annotation.Nonnull;
15 import javax.xml.stream.XMLStreamException;
16 import javax.xml.stream.XMLStreamWriter;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.common.QNameModule;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
21 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
22 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
24 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
26 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
27 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
33  * by no means final and subject to change as more functionality is centralized here.
34  */
35 abstract class XMLStreamWriterUtils {
36     private static final Logger LOG = LoggerFactory.getLogger(XMLStreamWriterUtils.class);
37
38     static XMLStreamWriterUtils create(final SchemaContext schemaContext) {
39         return schemaContext == null ? SchemalessXMLStreamWriterUtils.INSTANCE
40                 : new SchemaAwareXMLStreamWriterUtils(schemaContext);
41     }
42
43     @VisibleForTesting
44     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute,
45                                final RandomPrefix randomPrefix) throws XMLStreamException {
46         final QName key = attribute.getKey();
47         final String prefix = randomPrefix.encodePrefix(key.getNamespace());
48         writer.writeAttribute("xmlns:" + prefix, key.getNamespace().toString());
49         writer.writeAttribute(prefix, key.getNamespace().toString(), key.getLocalName(), attribute.getValue());
50     }
51
52     /**
53      * Write a value into a XML stream writer. This method assumes the start and end of element is
54      * emitted by the caller.
55      *
56      * @param writer XML Stream writer
57      * @param schemaNode Schema node that describes the value
58      * @param value data value
59      * @param parent module QName owning the leaf definition
60      * @throws XMLStreamException if an encoding problem occurs
61      */
62     void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode,
63             final Object value, final QNameModule parent) throws XMLStreamException {
64         if (value == null) {
65             LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(),
66                     schemaNode.getQName().getLocalName());
67             return;
68         }
69
70         Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode,
71                 "Unable to write value for node %s, only nodes of type: leaf and leaf-list can be written at this point",
72                 schemaNode.getQName());
73
74         TypeDefinition<?> type = ((TypedSchemaNode) schemaNode).getType();
75         if (type instanceof LeafrefTypeDefinition) {
76             type = getBaseTypeForLeafRef(schemaNode, (LeafrefTypeDefinition) type);
77         }
78
79         writeValue(writer, type, value, parent);
80     }
81
82     /**
83      * Write a value into a XML stream writer. This method assumes the start and end of element is
84      * emitted by the caller.
85      *
86      * @param writer XML Stream writer
87      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
88      * @param value data value
89      * @param parent optional parameter of a module QName owning the leaf definition
90      * @throws XMLStreamException if an encoding problem occurs
91      */
92     private void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type,
93             final Object value, final QNameModule parent) throws XMLStreamException {
94         if (value == null) {
95             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(),
96                     type.getQName().getLocalName());
97             return;
98         }
99
100         if (type instanceof IdentityrefTypeDefinition) {
101             write(writer, (IdentityrefTypeDefinition) type, value, parent);
102         } else if (type instanceof InstanceIdentifierTypeDefinition) {
103             write(writer, (InstanceIdentifierTypeDefinition) type, value);
104         } else {
105             final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
106             String text;
107             if (codec != null) {
108                 try {
109                     text = codec.serialize(value);
110                 } catch (ClassCastException e) {
111                     LOG.warn("Provided node value {} did not have type {} required by mapping. Using stream instead.",
112                             value, type, e);
113                     text = String.valueOf(value);
114                 }
115             } else {
116                 LOG.warn("Failed to find codec for {}, falling back to using stream", type);
117                 text = String.valueOf(value);
118             }
119             writer.writeCharacters(text);
120         }
121     }
122
123     @VisibleForTesting
124     static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final IdentityrefTypeDefinition type,
125                       @Nonnull final Object value, final QNameModule parent) throws XMLStreamException {
126         if (value instanceof QName) {
127             final QName qname = (QName) value;
128             final String prefix = "x";
129
130             //in case parent is present and same as element namespace write value without namespace
131             if (qname.getNamespace().equals(parent.getNamespace())){
132                 writer.writeCharacters(qname.getLocalName());
133             } else {
134                 final String ns = qname.getNamespace().toString();
135                 writer.writeNamespace(prefix, ns);
136                 writer.writeCharacters(prefix + ':' + qname.getLocalName());
137             }
138
139         } else {
140             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(),
141                     type.getQName().getLocalName(), value.getClass());
142             writer.writeCharacters(String.valueOf(value));
143         }
144     }
145
146     private void write(@Nonnull final XMLStreamWriter writer, @Nonnull final InstanceIdentifierTypeDefinition type,
147                        @Nonnull final Object value) throws XMLStreamException {
148         if (value instanceof YangInstanceIdentifier) {
149             writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
150         } else {
151             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(),
152                     type.getQName().getLocalName(), value.getClass());
153             writer.writeCharacters(String.valueOf(value));
154         }
155     }
156
157     abstract TypeDefinition<?> getBaseTypeForLeafRef(SchemaNode schemaNode, LeafrefTypeDefinition type);
158
159     abstract void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value)
160             throws XMLStreamException;
161 }