Merge "BUG 2854 : Do not add empty read write transactions to the replicable journal"
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / xml / codec / XmlStreamUtils.java
1 /*
2  * Copyright (c) 2014 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.controller.xml.codec;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import java.net.URI;
13 import java.util.Map.Entry;
14 import javax.annotation.Nonnull;
15 import javax.xml.stream.XMLStreamException;
16 import javax.xml.stream.XMLStreamWriter;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
20 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
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.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 @Beta
32 public class XmlStreamUtils {
33   private static final Logger LOG = LoggerFactory.getLogger(XmlStreamUtils.class);
34   private final XmlCodecProvider codecProvider;
35
36   protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
37     this.codecProvider = Preconditions.checkNotNull(codecProvider);
38   }
39
40   /**
41    * Create a new instance encapsulating a particular codec provider.
42    *
43    * @param codecProvider XML codec provider
44    * @return A new instance
45    */
46   public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
47     return new XmlStreamUtils(codecProvider);
48   }
49
50   /**
51    * Write an InstanceIdentifier into the output stream. Calling corresponding {@link javax.xml.stream.XMLStreamWriter#writeStartElement(String)}
52    * and {@link javax.xml.stream.XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
53    *
54    * @param writer XML Stream writer
55    * @param id InstanceIdentifier
56    * @throws javax.xml.stream.XMLStreamException
57    */
58   public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
59     Preconditions.checkNotNull(writer, "Writer may not be null");
60     Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
61     LOG.debug("Writing Instance identifier with Random prefix");
62     final RandomPrefix prefixes = new RandomPrefix();
63     final String str = XmlUtils.encodeIdentifier(prefixes, id);
64
65     for (final Entry<URI, String> e: prefixes.getPrefixes()) {
66       writer.writeNamespace(e.getValue(), e.getKey().toString());
67     }
68     if(LOG.isDebugEnabled()) {
69         LOG.debug("Instance identifier with Random prefix is now {}", str);
70     }
71     writer.writeCharacters(str);
72   }
73
74   /**
75    * Write a value into a XML stream writer. This method assumes the start and end of element is
76    * emitted by the caller.
77    *
78    * @param writer XML Stream writer
79    * @param type type definitions
80    * @param value object value
81    * @throws javax.xml.stream.XMLStreamException if an encoding problem occurs
82    */
83   public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
84     if (value == null) {
85       if(LOG.isDebugEnabled()){
86         LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
87       }
88       return;
89     }
90
91     final TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
92     if (baseType instanceof IdentityrefTypeDefinition) {
93       write(writer, (IdentityrefTypeDefinition) baseType, value);
94     } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
95       write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
96     } else {
97       final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
98       String text;
99       if (codec != null) {
100         try {
101           text = codec.serialize(value);
102         } catch (final ClassCastException e) {
103           LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
104           text = String.valueOf(value);
105         }
106       } else {
107         LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
108         text = String.valueOf(value);
109       }
110       writer.writeCharacters(text);
111     }
112   }
113
114   private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
115     if (value instanceof QName) {
116       final QName qname = (QName) value;
117
118       writer.writeNamespace("x", qname.getNamespace().toString());
119       writer.writeCharacters("x:" + qname.getLocalName());
120     } else {
121       if(LOG.isDebugEnabled()) {
122         LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
123       }
124       writer.writeCharacters(String.valueOf(value));
125     }
126   }
127
128   private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
129     if (value instanceof YangInstanceIdentifier) {
130       if(LOG.isDebugEnabled()) {
131           LOG.debug("Writing InstanceIdentifier object {}", value);
132       }
133       write(writer, (YangInstanceIdentifier)value);
134     } else {
135       if(LOG.isDebugEnabled()) {
136           LOG.debug("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
137       }
138         writer.writeCharacters(String.valueOf(value));
139     }
140   }
141 }