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.xml.codec;
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;
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;
52 * Common XML-related utility methods, which are not specific to a particular
55 public class XmlUtils {
57 public static final XmlCodecProvider DEFAULT_XML_CODEC_PROVIDER = new XmlCodecProvider() {
59 public TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codecFor(final TypeDefinition<?> baseType) {
60 return TypeDefinitionAwareCodec.from(baseType);
67 private static final String BLANK = "";
68 private static final Logger LOG = LoggerFactory.getLogger(XmlUtils.class);
71 * Converts the composite node to xml using rpc input schema node
73 * @param schemaContext
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;
80 if(schemaContext == null) return BLANK;
82 Document domTree = null;
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());
89 CompositeNode inputContainer = cNode.getFirstCompositeByName(QName.create(cNode.getNodeType(), "input"));
90 domTree = XmlDocumentUtils.toDocument(inputContainer, rpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
92 LOG.debug("input composite node to document conversion complete, document is {}", domTree);
97 } catch (UnsupportedDataTypeException e) {
98 LOG.error("Error during translation of CompositeNode to Document", e);
100 return domTransformer(domTree);
104 * Converts the composite node to xml String using rpc output schema node
106 * @param schemaContext
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;
113 if(schemaContext == null) return BLANK;
115 Document domTree = null;
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());
122 CompositeNode outputContainer = cNode.getFirstCompositeByName(QName.create(cNode.getNodeType(), "output"));
123 domTree = XmlDocumentUtils.toDocument(outputContainer, rpc.getOutput(), XmlDocumentUtils.defaultValueCodecProvider());
125 LOG.debug("output composite node to document conversion complete, document is {}", domTree);
130 } catch (UnsupportedDataTypeException e) {
131 LOG.error("Error during translation of CompositeNode to Document", e);
133 return domTransformer(domTree);
136 private static String domTransformer(Document domTree) {
137 StringWriter writer = new StringWriter();
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) {
145 LOG.error("Error during translation of Document to OutputStream", e);
147 LOG.debug("Document to string conversion complete, xml string is {} ", writer.toString());
149 return writer.toString();
152 public static CompositeNode xmlToCompositeNode(String xml){
153 if (xml==null || xml.length()==0) return null;
157 dataTree = XmlTreeBuilder.buildDataTree(new ByteArrayInputStream(xml.getBytes()));
158 } catch (XMLStreamException e) {
159 LOG.error("Error during building data tree from XML", e);
162 if (dataTree == null) {
163 LOG.error("data tree is null");
166 if (dataTree instanceof SimpleNode) {
167 LOG.error("RPC XML was resolved as SimpleNode");
170 return (CompositeNode) dataTree;
174 * Converts the xml to composite node using rpc input schema node
177 * @param schemaContext
178 * @return CompositeNode object based on the input, if any of the input parameter is null, a null object is returned
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;
184 if(rpc == null) return null;
186 if(schemaContext == null) return null;
188 CompositeNode compositeNode = null;
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);
197 if(rpcDef.getInput() == null) {
198 LOG.warn("found rpc definition's input is null");
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);
208 Element xmlData = (Element)nodeList.item(0);
210 List<Node<?>> dataNodes = XmlDocumentUtils.toDomNodes(xmlData,
211 Optional.of(rpcDef.getInput().getChildNodes()), schemaContext);
213 LOG.debug("Converted xml input to list of nodes {}", dataNodes);
215 final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder();
217 it.add(ImmutableCompositeNode.create(input, dataNodes));
218 compositeNode = it.toInstance();
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);
228 LOG.debug("Xml to composite node conversion complete {} ", compositeNode);
229 return compositeNode;
232 public static TypeDefinition<?> resolveBaseTypeFrom(final @Nonnull TypeDefinition<?> type) {
233 TypeDefinition<?> superType = type;
234 while (superType.getBaseType() != null) {
235 superType = superType.getBaseType();
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']
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();
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("']");
272 } else if (pathArgument instanceof NodeWithValue) {
273 textContent.append("[.='");
274 textContent.append(((NodeWithValue) pathArgument).getValue());
275 textContent.append("']");
279 return textContent.toString();