Move yang-common(-netty)
[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.TypeDefinition;
20 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
21 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
22 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
28  * by no means final and subject to change as more functionality is centralized here.
29  */
30 abstract class XMLStreamWriterUtils {
31     private static final Logger LOG = LoggerFactory.getLogger(XMLStreamWriterUtils.class);
32     /**
33      * Warn-once set of identityref nodes which were found to be normalized to a different object than a QName.
34      */
35     private static final Set<QName> IDENTITYREF_WARNED = ConcurrentHashMap.newKeySet();
36
37     /**
38      * Write a value into a XML stream writer. This method assumes the start and end of element is
39      * emitted by the caller.
40      *
41      * @param writer XML Stream writer
42      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
43      * @param value data value
44      * @param parent optional parameter of a module QName owning the leaf definition
45      * @return String characters to be written
46      * @throws XMLStreamException if an encoding problem occurs
47      */
48     String encodeValue(final @NonNull ValueWriter writer, final @NonNull TypeDefinition<?> type,
49             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
50         if (type instanceof IdentityrefTypeDefinition) {
51             return encode(writer, (IdentityrefTypeDefinition) type, value, parent);
52         } else if (type instanceof InstanceIdentifierTypeDefinition) {
53             return encode(writer, (InstanceIdentifierTypeDefinition) type, value);
54         } else if (value instanceof QName && isIdentityrefUnion(type)) {
55             // Ugly special-case form unions with identityrefs
56             return encode(writer, (QName) value, parent);
57         } else if (value instanceof YangInstanceIdentifier && isInstanceIdentifierUnion(type)) {
58             return encodeInstanceIdentifier(writer, (YangInstanceIdentifier) value);
59         } else {
60             return serialize(type, value);
61         }
62     }
63
64     private static boolean isIdentityrefUnion(final TypeDefinition<?> type) {
65         if (type instanceof UnionTypeDefinition) {
66             for (TypeDefinition<?> subtype : ((UnionTypeDefinition) type).getTypes()) {
67                 if (subtype instanceof IdentityrefTypeDefinition || isIdentityrefUnion(subtype)) {
68                     return true;
69                 }
70             }
71         }
72         return false;
73     }
74
75     private boolean isInstanceIdentifierUnion(final TypeDefinition<?> type) {
76         if (type instanceof UnionTypeDefinition) {
77             for (TypeDefinition<?> subtype : ((UnionTypeDefinition) type).getTypes()) {
78                 if (subtype instanceof InstanceIdentifierTypeDefinition || isInstanceIdentifierUnion(subtype)) {
79                     return true;
80                 }
81             }
82         }
83         return false;
84     }
85
86     private static String serialize(final @NonNull TypeDefinition<?> type, final @NonNull Object value) {
87         final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
88         if (codec == null) {
89             LOG.warn("Failed to find codec for {}, falling back to using stream", type);
90             return value.toString();
91         }
92
93         try {
94             return codec.serialize(value);
95         } catch (ClassCastException e) {
96             LOG.warn("Provided node value {} did not have type {} required by mapping. Using stream instead.",
97                 value, type, e);
98             return value.toString();
99         }
100     }
101
102     @VisibleForTesting
103     static String encode(final @NonNull ValueWriter writer, final @NonNull QName qname, final QNameModule parent)
104             throws XMLStreamException {
105         //in case parent is present and same as element namespace write value without namespace
106         if (qname.getNamespace().equals(parent.getNamespace())) {
107             return qname.getLocalName();
108         }
109
110         final String ns = qname.getNamespace().toString();
111         final String prefix = "x";
112         writer.writeNamespace(prefix, ns);
113         return prefix + ':' + qname.getLocalName();
114     }
115
116     private static String encode(final @NonNull ValueWriter writer, final @NonNull IdentityrefTypeDefinition type,
117             final @NonNull Object value, final QNameModule parent) throws XMLStreamException {
118         if (value instanceof QName) {
119             return encode(writer, (QName) value, parent);
120         }
121
122         final QName qname = type.getQName();
123         if (IDENTITYREF_WARNED.add(qname)) {
124             LOG.warn("Value of {}:{} is not a QName but {}. Please the source of this data", qname.getNamespace(),
125                 qname.getLocalName(), value.getClass(), new Throwable());
126         }
127         return value.toString();
128     }
129
130     private String encode(final @NonNull ValueWriter writer, final @NonNull InstanceIdentifierTypeDefinition type,
131             final @NonNull Object value) throws XMLStreamException {
132         if (value instanceof YangInstanceIdentifier) {
133             return encodeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
134         }
135
136         final QName qname = type.getQName();
137         LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", qname.getNamespace(), qname.getLocalName(),
138             value.getClass());
139         return value.toString();
140     }
141
142     abstract String encodeInstanceIdentifier(@NonNull ValueWriter writer, YangInstanceIdentifier value)
143             throws XMLStreamException;
144 }