Merge "Bug 1534: Changed blocking calls to async in dist data store"
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / xml / codec / XmlUtils.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.base.Optional;
11 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
12 import org.opendaylight.yangtools.yang.common.QName;
13 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
14 import org.opendaylight.yangtools.yang.data.api.Node;
15 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
21 import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
22 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
23 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
24 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
25 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
27 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import org.w3c.dom.Document;
31 import org.w3c.dom.Element;
32 import org.w3c.dom.NodeList;
33 import org.xml.sax.SAXException;
34
35 import javax.activation.UnsupportedDataTypeException;
36 import javax.annotation.Nonnull;
37 import javax.xml.stream.XMLStreamException;
38 import javax.xml.transform.OutputKeys;
39 import javax.xml.transform.Transformer;
40 import javax.xml.transform.TransformerException;
41 import javax.xml.transform.TransformerFactory;
42 import javax.xml.transform.dom.DOMSource;
43 import javax.xml.transform.stream.StreamResult;
44 import java.io.ByteArrayInputStream;
45 import java.io.IOException;
46 import java.io.StringWriter;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Set;
50
51 /**
52  * Common XML-related utility methods, which are not specific to a particular
53  * JAXP API.
54  */
55 public class XmlUtils {
56
57   public static final XmlCodecProvider DEFAULT_XML_CODEC_PROVIDER = new XmlCodecProvider() {
58     @Override
59     public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
60       return TypeDefinitionAwareCodec.from(baseType);
61     }
62   };
63
64   private XmlUtils() {
65   }
66
67   private static final String BLANK = "";
68   private static final Logger LOG = LoggerFactory.getLogger(XmlUtils.class);
69
70   /**
71    * Converts the composite node to xml using rpc input schema node
72    * @param cNode
73    * @param schemaContext
74    * @return xml String
75    */
76   public static String inputCompositeNodeToXml(CompositeNode cNode, SchemaContext schemaContext){
77     LOG.debug("Converting input composite node to xml {}", cNode);
78     if (cNode == null) return BLANK;
79
80     if(schemaContext == null) return BLANK;
81
82     Document domTree = null;
83     try {
84       Set<RpcDefinition> rpcs =  schemaContext.getOperations();
85       for(RpcDefinition rpc : rpcs) {
86         if(rpc.getQName().equals(cNode.getNodeType())){
87           LOG.debug("Found the rpc definition from schema context matching with input composite node  {}", rpc.getQName());
88
89           CompositeNode inputContainer = cNode.getFirstCompositeByName(QName.create(cNode.getNodeType(), "input"));
90           domTree = XmlDocumentUtils.toDocument(inputContainer, rpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
91
92           LOG.debug("input composite node to document conversion complete, document is   {}", domTree);
93           break;
94         }
95       }
96
97     } catch (UnsupportedDataTypeException e) {
98       LOG.error("Error during translation of CompositeNode to Document", e);
99     }
100     return domTransformer(domTree);
101   }
102
103   /**
104    * Converts the composite node to xml String using rpc output schema node
105    * @param cNode
106    * @param schemaContext
107    * @return xml string
108    */
109   public static String outputCompositeNodeToXml(CompositeNode cNode, SchemaContext schemaContext){
110     LOG.debug("Converting output composite node to xml {}", cNode);
111     if (cNode == null) return BLANK;
112
113     if(schemaContext == null) return BLANK;
114
115     Document domTree = null;
116     try {
117       Set<RpcDefinition> rpcs =  schemaContext.getOperations();
118       for(RpcDefinition rpc : rpcs) {
119         if(rpc.getQName().equals(cNode.getNodeType())){
120           LOG.debug("Found the rpc definition from schema context matching with output composite node  {}", rpc.getQName());
121
122           CompositeNode outputContainer = cNode.getFirstCompositeByName(QName.create(cNode.getNodeType(), "output"));
123           domTree = XmlDocumentUtils.toDocument(outputContainer, rpc.getOutput(), XmlDocumentUtils.defaultValueCodecProvider());
124
125           LOG.debug("output composite node to document conversion complete, document is   {}", domTree);
126           break;
127         }
128       }
129
130     } catch (UnsupportedDataTypeException e) {
131       LOG.error("Error during translation of CompositeNode to Document", e);
132     }
133     return domTransformer(domTree);
134   }
135
136   private static String domTransformer(Document domTree) {
137     StringWriter writer = new StringWriter();
138     try {
139       TransformerFactory tf = TransformerFactory.newInstance();
140       Transformer transformer = tf.newTransformer();
141       transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
142       transformer.transform(new DOMSource(domTree), new StreamResult(writer));
143     } catch (TransformerException e) {
144
145       LOG.error("Error during translation of Document to OutputStream", e);
146     }
147     LOG.debug("Document to string conversion complete, xml string is  {} ",  writer.toString());
148
149     return writer.toString();
150   }
151
152   public static CompositeNode xmlToCompositeNode(String xml){
153     if (xml==null || xml.length()==0) return null;
154
155     Node<?> dataTree;
156     try {
157       dataTree = XmlTreeBuilder.buildDataTree(new ByteArrayInputStream(xml.getBytes()));
158     } catch (XMLStreamException e) {
159       LOG.error("Error during building data tree from XML", e);
160       return null;
161     }
162     if (dataTree == null) {
163       LOG.error("data tree is null");
164       return null;
165     }
166     if (dataTree instanceof SimpleNode) {
167       LOG.error("RPC XML was resolved as SimpleNode");
168       return null;
169     }
170     return (CompositeNode) dataTree;
171   }
172
173   /**
174    * Converts the xml to composite node using rpc input schema node
175    * @param rpc
176    * @param xml
177    * @param schemaContext
178    * @return CompositeNode object based on the input, if any of the input parameter is null, a null object is returned
179    */
180   public static CompositeNode inputXmlToCompositeNode(QName rpc, String xml,  SchemaContext schemaContext){
181     LOG.debug("Converting input xml to composite node {}", xml);
182     if (xml==null || xml.length()==0) return null;
183
184     if(rpc == null) return null;
185
186     if(schemaContext == null) return null;
187
188     CompositeNode compositeNode = null;
189     try {
190
191       Document doc = XmlUtil.readXmlToDocument(xml);
192       Set<RpcDefinition> rpcs =  schemaContext.getOperations();
193       for(RpcDefinition rpcDef : rpcs) {
194         if(rpcDef.getQName().equals(rpc)){
195           LOG.debug("found the rpc definition from schema context matching rpc  {}", rpc);
196
197           if(rpcDef.getInput() == null) {
198             LOG.warn("found rpc definition's input is null");
199             return null;
200           }
201
202           QName input = rpcDef.getInput().getQName();
203           NodeList nodeList = doc.getElementsByTagNameNS(input.getNamespace().toString(), "input");
204           if(nodeList == null || nodeList.getLength() < 1) {
205             LOG.warn("xml does not have input entry. {}", xml);
206             return null;
207           }
208           Element xmlData = (Element)nodeList.item(0);
209
210           List<Node<?>> dataNodes = XmlDocumentUtils.toDomNodes(xmlData,
211               Optional.of(rpcDef.getInput().getChildNodes()), schemaContext);
212
213           LOG.debug("Converted xml input to list of nodes  {}", dataNodes);
214
215           final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder();
216           it.setQName(input);
217           it.add(ImmutableCompositeNode.create(input, dataNodes));
218           compositeNode = it.toInstance();
219           break;
220         }
221       }
222     } catch (SAXException e) {
223       LOG.error("Error during building data tree from XML", e);
224     } catch (IOException e) {
225       LOG.error("Error during building data tree from XML", e);
226     }
227
228     LOG.debug("Xml to composite node conversion complete {} ", compositeNode);
229     return compositeNode;
230   }
231
232   public static TypeDefinition<?> resolveBaseTypeFrom(final @Nonnull TypeDefinition<?> type) {
233     TypeDefinition<?> superType = type;
234     while (superType.getBaseType() != null) {
235       superType = superType.getBaseType();
236     }
237     return superType;
238   }
239
240   /**
241    * This code is picked from yangtools and modified to add type of instance identifier
242    * output of instance identifier something like below for a flow ref composite node of type instance identifier,
243    * which has path arguments with predicates, whose value is of type java.lang.short
244    * <flow-ref xmlns:bgkj="urn:opendaylight:flow:inventory" xmlns:jdlk="urn:opendaylight:inventory">
245    *   /jdlk:nodes/jdlk:node[jdlk:id='openflow:205558455098190@java.lang.String']
246    *   /bgkj:table[bgkj:id='3@java.lang.Short']
247    *   /bgkj:flow[bgkj:id='156@java.lang.String']
248    * </flow-ref>
249    *
250    */
251
252   public static String encodeIdentifier(final RandomPrefix prefixes, final YangInstanceIdentifier id) {
253     StringBuilder textContent = new StringBuilder();
254     for (PathArgument pathArgument : id.getPathArguments()) {
255       textContent.append('/');
256       textContent.append(prefixes.encodeQName(pathArgument.getNodeType()));
257       if (pathArgument instanceof NodeIdentifierWithPredicates) {
258         Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
259
260         for (QName keyValue : predicates.keySet()) {
261           Object value = predicates.get(keyValue);
262           String type = value.getClass().getName();
263           String predicateValue = String.valueOf(value);
264           textContent.append('[');
265           textContent.append(prefixes.encodeQName(keyValue));
266           textContent.append("='");
267           textContent.append(predicateValue);
268           textContent.append("@");
269           textContent.append(type);
270           textContent.append("']");
271         }
272       } else if (pathArgument instanceof NodeWithValue) {
273         textContent.append("[.='");
274         textContent.append(((NodeWithValue) pathArgument).getValue());
275         textContent.append("']");
276       }
277     }
278
279     return textContent.toString();
280   }
281 }