2 * Copyright (c) 2015 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
9 package org.opendaylight.netconf.mdsal.connector.ops;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Throwables;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import java.io.IOException;
16 import java.net.URISyntaxException;
17 import java.util.Collection;
18 import java.util.Collections;
20 import javax.annotation.Nullable;
21 import javax.xml.stream.XMLOutputFactory;
22 import javax.xml.stream.XMLStreamException;
23 import javax.xml.stream.XMLStreamWriter;
24 import javax.xml.transform.dom.DOMResult;
25 import org.opendaylight.controller.config.util.xml.DocumentedException;
26 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
27 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
28 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
31 import org.opendaylight.controller.config.util.xml.XmlUtil;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
34 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
35 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
36 import org.opendaylight.netconf.mapping.api.HandlingPriority;
37 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
38 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
39 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
47 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
48 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.Module;
50 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
51 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Attr;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57 import org.w3c.dom.Node;
58 import org.w3c.dom.NodeList;
60 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
62 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
64 private final CurrentSchemaContext schemaContext;
65 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
68 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
69 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
72 private final DOMRpcService rpcService;
74 public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
75 final DOMRpcService rpcService) {
76 super(netconfSessionIdForReporting);
77 this.schemaContext = schemaContext;
78 this.rpcService = rpcService;
82 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
83 final URI namespaceURI = createNsUri(namespace);
84 final Optional<Module> module = getModule(namespaceURI);
86 if (!module.isPresent()) {
87 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
88 return HandlingPriority.CANNOT_HANDLE;
91 getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
92 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
97 protected String getOperationName() {
98 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
101 private static URI createNsUri(final String namespace) {
102 final URI namespaceURI;
104 namespaceURI = new URI(namespace);
105 } catch (final URISyntaxException e) {
106 // Cannot occur, namespace in parsed XML cannot be invalid URI
107 throw new IllegalStateException("Unable to parse URI " + namespace, e);
112 //this returns module with the newest revision if more then 1 module with same namespace is found
113 private Optional<Module> getModule(final URI namespaceURI) {
114 return Optional.fromNullable(
115 schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
118 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
120 for (final RpcDefinition rpcDef : module.getRpcs()) {
121 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
122 && rpcDef.getQName().getLocalName().equals(name)) {
123 return Optional.of(rpcDef);
126 return Optional.absent();
130 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
131 throws DocumentedException {
133 final String netconfOperationName = operationElement.getName();
134 final String netconfOperationNamespace;
136 netconfOperationNamespace = operationElement.getNamespace();
137 } catch (final DocumentedException e) {
138 LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
139 throw new DocumentedException("Cannot retrieve netconf operation namespace from message",
140 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
143 final URI namespaceURI = createNsUri(netconfOperationNamespace);
144 final Optional<Module> moduleOptional = getModule(namespaceURI);
146 if (!moduleOptional.isPresent()) {
147 throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
148 + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
149 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
152 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
153 namespaceURI, netconfOperationName);
155 if (!rpcDefinitionOptional.isPresent()) {
156 throw new DocumentedException(
157 "Unable to find RpcDefinition with namespace and name : "
158 + namespaceURI + " " + netconfOperationName,
159 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
162 final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
163 final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
164 final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());
166 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
168 final DOMRpcResult result = rpcFuture.checkedGet();
169 if (result.getResult() == null) {
170 return XmlUtil.createElement(document, XmlNetconfConstants.OK,
171 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
173 return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
174 } catch (final DOMRpcException e) {
175 throw DocumentedException.wrap(e);
180 public Document handle(final Document requestMessage,
181 final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
183 final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
185 final Document document = XmlUtil.newDocument();
187 final XmlElement operationElement = requestElement.getOnlyChildElement();
188 final Map<String, Attr> attributes = requestElement.getAttributes();
190 final Element response = handle(document, operationElement, subsequentOperation);
191 final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
192 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
194 if (XmlElement.fromDomElement(response).hasNamespace()) {
195 rpcReply.appendChild(response);
197 final NodeList list = response.getChildNodes();
198 if (list.getLength() == 0) {
199 rpcReply.appendChild(response);
201 while (list.getLength() != 0) {
202 rpcReply.appendChild(list.item(0));
207 for (final Attr attribute : attributes.values()) {
208 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
210 document.appendChild(rpcReply);
214 private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
215 final SchemaPath rpcOutputPath) {
216 final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
218 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
220 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
221 schemaContext.getCurrentContext(), rpcOutputPath);
223 final SchemaOrderedNormalizedNodeWriter nnWriter =
224 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
226 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
228 nnStreamWriter.close();
230 } catch (IOException | XMLStreamException e) {
231 LOG.warn("Error while closing streams", e);
234 return result.getNode();
237 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
239 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
240 } catch (final XMLStreamException e) {
241 throw new RuntimeException(e);
245 private static void writeRootElement(final XMLStreamWriter xmlWriter,
246 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
248 final Collection<DataContainerChild<?, ?>> value = data.getValue();
249 nnWriter.write(value);
252 } catch (XMLStreamException | IOException e) {
253 Throwables.propagate(e);
258 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
260 * @param element rpc xml element
261 * @param input input container schema node, or null if rpc does not take any input
262 * @return parsed rpc into normalized node, or null if input schema is null
265 private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input) {
266 return input.getChildNodes().isEmpty() ? null : DomToNormalizedNodeParserFactory
267 .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext())
268 .getContainerNodeParser()
269 .parse(Collections.singletonList(element.getDomElement()), input);