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