Check unions for instance-identifier types
[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 com.google.common.annotations.VisibleForTesting;
11 import java.util.Set;
12 import java.util.concurrent.ConcurrentHashMap;
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.TypeDefinition;
21 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
22 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
23 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
24 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
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      * Warn-once set of identityref nodes which were found to be normalized to a different object than a QName.
36      */
37     private static final Set<QName> IDENTITYREF_WARNED = ConcurrentHashMap.newKeySet();
38
39     /**
40      * Encode a value into a String in the context of a XML stream writer. This method assumes the start and end of
41      * element is emitted by the caller.
42      *
43      * @param writer XML Stream writer
44      * @param schemaNode Schema node that describes the value
45      * @param type Schema type definition
46      * @param value data value
47      * @param parent module QName owning the leaf definition
48      * @return String characters to be written
49      * @throws XMLStreamException if an encoding problem occurs
50      */
51     String encodeValue(final @NonNull ValueWriter writer,final @NonNull SchemaNode schemaNode,
52             final TypeDefinition<?> type, final @NonNull Object value, final QNameModule parent)
53                     throws XMLStreamException {
54         return type instanceof LeafrefTypeDefinition
55                 ? encodeValue(writer, getBaseTypeForLeafRef(schemaNode, (LeafrefTypeDefinition) type), value, parent)
56                         : encodeValue(writer, type, value, parent);
57     }
58
59     /**
60      * Write a value into a XML stream writer. This method assumes the start and end of element is
61      * emitted by the caller.
62      *
63      * @param writer XML Stream writer
64      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
65      * @param value data value
66      * @param parent optional parameter of a module QName owning the leaf definition
67      * @return String characters to be written
68      * @throws XMLStreamException if an encoding problem occurs
69      */
70     private String encodeValue(final @NonNull ValueWriter writer, final @NonNull TypeDefinition<?> type,
71             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
72         if (type instanceof IdentityrefTypeDefinition) {
73             return encode(writer, (IdentityrefTypeDefinition) type, value, parent);
74         } else if (type instanceof InstanceIdentifierTypeDefinition) {
75             return encode(writer, (InstanceIdentifierTypeDefinition) type, value);
76         } else if (value instanceof QName && isIdentityrefUnion(type)) {
77             // Ugly special-case form unions with identityrefs
78             return encode(writer, (QName) value, parent);
79         } else if (value instanceof YangInstanceIdentifier && isInstanceIdentifierUnion(type)) {
80             return encodeInstanceIdentifier(writer, (YangInstanceIdentifier) value);
81         } else {
82             return serialize(type, value);
83         }
84     }
85
86     private static boolean isIdentityrefUnion(final TypeDefinition<?> type) {
87         if (type instanceof UnionTypeDefinition) {
88             for (TypeDefinition<?> subtype : ((UnionTypeDefinition) type).getTypes()) {
89                 if (subtype instanceof IdentityrefTypeDefinition || isIdentityrefUnion(subtype)) {
90                     return true;
91                 }
92             }
93         }
94         return false;
95     }
96
97     private boolean isInstanceIdentifierUnion(final TypeDefinition<?> type) {
98         if (type instanceof UnionTypeDefinition) {
99             for (TypeDefinition<?> subtype : ((UnionTypeDefinition) type).getTypes()) {
100                 if (subtype instanceof InstanceIdentifierTypeDefinition || isInstanceIdentifierUnion(subtype)) {
101                     return true;
102                 }
103             }
104         }
105         return false;
106     }
107
108     private static String serialize(final @NonNull TypeDefinition<?> type, final @NonNull Object value) {
109         final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
110         if (codec == null) {
111             LOG.warn("Failed to find codec for {}, falling back to using stream", type);
112             return value.toString();
113         }
114
115         try {
116             return codec.serialize(value);
117         } catch (ClassCastException e) {
118             LOG.warn("Provided node value {} did not have type {} required by mapping. Using stream instead.",
119                 value, type, e);
120             return value.toString();
121         }
122     }
123
124     @VisibleForTesting
125     static String encode(final @NonNull ValueWriter writer, final @NonNull QName qname, final QNameModule parent)
126             throws XMLStreamException {
127         //in case parent is present and same as element namespace write value without namespace
128         if (qname.getNamespace().equals(parent.getNamespace())) {
129             return qname.getLocalName();
130         }
131
132         final String ns = qname.getNamespace().toString();
133         final String prefix = "x";
134         writer.writeNamespace(prefix, ns);
135         return prefix + ':' + qname.getLocalName();
136     }
137
138     private static String encode(final @NonNull ValueWriter writer, final @NonNull IdentityrefTypeDefinition type,
139             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
140         if (value instanceof QName) {
141             return encode(writer, (QName) value, parent);
142         }
143
144         final QName qname = type.getQName();
145         if (IDENTITYREF_WARNED.add(qname)) {
146             LOG.warn("Value of {}:{} is not a QName but {}. Please the source of this data", qname.getNamespace(),
147                 qname.getLocalName(), value.getClass(), new Throwable());
148         }
149         return value.toString();
150     }
151
152     private String encode(final @NonNull ValueWriter writer, final @NonNull InstanceIdentifierTypeDefinition type,
153             final @NonNull Object value) throws XMLStreamException {
154         if (value instanceof YangInstanceIdentifier) {
155             return encodeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
156         }
157
158         final QName qname = type.getQName();
159         LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", qname.getNamespace(), qname.getLocalName(),
160             value.getClass());
161         return value.toString();
162     }
163
164     abstract @NonNull TypeDefinition<?> getBaseTypeForLeafRef(SchemaNode schemaNode,
165             @NonNull LeafrefTypeDefinition type);
166
167     abstract String encodeInstanceIdentifier(@NonNull ValueWriter writer, YangInstanceIdentifier value)
168             throws XMLStreamException;
169 }