2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.remote.rpc.utils;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import org.opendaylight.yangtools.yang.common.QName;
13 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
14 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
15 import org.opendaylight.yangtools.yang.data.api.Node;
16 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
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.data.impl.codec.xml.XmlCodecProvider;
20 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
21 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
27 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
28 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 import javax.annotation.Nonnull;
33 import javax.annotation.Nullable;
34 import javax.xml.stream.XMLStreamException;
35 import javax.xml.stream.XMLStreamWriter;
37 import java.util.Map.Entry;
40 * Utility class for bridging JAXP Stream and YANG Data APIs. Note that the definition of this class
41 * by no means final and subject to change as more functionality is centralized here.
44 public class XmlStreamUtils {
45 private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
46 private final XmlCodecProvider codecProvider;
48 protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
49 this.codecProvider = Preconditions.checkNotNull(codecProvider);
53 * Create a new instance encapsulating a particular codec provider.
55 * @param codecProvider XML codec provider
56 * @return A new instance
58 public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
59 return new XmlStreamUtils(codecProvider);
63 * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
64 * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
66 * @param data Data node
67 * @return True if the data node will result in empty element body.
69 public static boolean isEmptyElement(final Node<?> data) {
74 if (data instanceof CompositeNode) {
75 return ((CompositeNode) data).getValue().isEmpty();
77 if (data instanceof SimpleNode) {
78 return data.getValue() == null;
86 * Write an InstanceIdentifier into the output stream. Calling corresponding {@link javax.xml.stream.XMLStreamWriter#writeStartElement(String)}
87 * and {@link javax.xml.stream.XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
89 * @param writer XML Stream writer
90 * @param id InstanceIdentifier
91 * @throws javax.xml.stream.XMLStreamException
93 public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
94 Preconditions.checkNotNull(writer, "Writer may not be null");
95 Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
96 LOG.debug("Writing Instance identifier with Random prefix");
97 final RandomPrefix prefixes = new RandomPrefix();
98 final String str = XmlUtils.encodeIdentifier(prefixes, id);
100 for (Entry<URI, String> e: prefixes.getPrefixes()) {
101 writer.writeNamespace(e.getValue(), e.getKey().toString());
103 LOG.debug("Instance identifier with Random prefix is now {}", str);
104 writer.writeCharacters(str);
108 * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
110 * @param writer XML Stream writer
111 * @param data data node
112 * @param schema corresponding schema node, may be null
113 * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
115 public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
116 // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
117 // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
119 writer.writeStartDocument();
120 writeElement(writer, data, schema);
121 writer.writeEndDocument();
127 * Write an element into a XML stream writer. This includes the element start/end tags and
128 * the value of the element.
130 * @param writer XML Stream writer
131 * @param data data node
132 * @param schema Schema node
133 * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
135 public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
136 final QName qname = data.getNodeType();
137 final String pfx = qname.getPrefix() != null ? qname.getPrefix() : "";
138 final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
140 if (isEmptyElement(data)) {
141 writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
145 writer.writeStartElement(pfx, qname.getLocalName(), ns);
146 if (data instanceof AttributesContainer && ((AttributesContainer) data).getAttributes() != null) {
147 for (Entry<QName, String> attribute : ((AttributesContainer) data).getAttributes().entrySet()) {
148 writer.writeAttribute(attribute.getKey().getNamespace().toString(), attribute.getKey().getLocalName(), attribute.getValue());
152 if (data instanceof SimpleNode<?>) {
153 LOG.debug("writeElement : node is of type SimpleNode");
155 if (schema instanceof LeafListSchemaNode) {
156 writeValue(writer, ((LeafListSchemaNode) schema).getType(), data.getValue());
157 } else if (schema instanceof LeafSchemaNode) {
158 writeValue(writer, ((LeafSchemaNode) schema).getType(), data.getValue());
160 Object value = data.getValue();
162 writer.writeCharacters(String.valueOf(value));
166 LOG.debug("writeElement : node is of type CompositeNode");
168 for (Node<?> child : ((CompositeNode) data).getValue()) {
169 DataSchemaNode childSchema = null;
170 if (schema instanceof DataNodeContainer) {
171 childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), ((DataNodeContainer) schema).getChildNodes()).orNull();
172 if (childSchema == null) {
173 LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
177 writeElement(writer, child, childSchema);
181 writer.writeEndElement();
185 * Write a value into a XML stream writer. This method assumes the start and end of element is
186 * emitted by the caller.
188 * @param writer XML Stream writer
189 * @param type type definitions
190 * @param value object value
191 * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
193 public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
195 LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
199 final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
200 if (baseType instanceof IdentityrefTypeDefinition) {
201 write(writer, (IdentityrefTypeDefinition) baseType, value);
202 } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
203 write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
205 final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
209 text = codec.serialize(value);
210 } catch (ClassCastException e) {
211 LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
212 text = String.valueOf(value);
215 LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
216 text = String.valueOf(value);
218 writer.writeCharacters(text);
222 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
223 if (value instanceof QName) {
224 final QName qname = (QName) value;
226 if (qname.getPrefix() != null && !qname.getPrefix().isEmpty()) {
227 prefix = qname.getPrefix();
232 writer.writeNamespace(prefix, qname.getNamespace().toString());
233 writer.writeCharacters(prefix + ':' + qname.getLocalName());
235 LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
236 writer.writeCharacters(String.valueOf(value));
240 private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
241 if (value instanceof YangInstanceIdentifier) {
242 LOG.debug("Writing InstanceIdentifier object {}", value);
243 write(writer, (YangInstanceIdentifier)value);
245 LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
246 writer.writeCharacters(String.valueOf(value));