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