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.util.Collection;
17 import java.util.Collections;
19 import javax.annotation.Nullable;
20 import javax.xml.stream.XMLOutputFactory;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.stream.XMLStreamWriter;
23 import javax.xml.transform.dom.DOMResult;
24 import org.opendaylight.controller.config.util.xml.DocumentedException;
25 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
26 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
27 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
28 import org.opendaylight.controller.config.util.xml.XmlElement;
29 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
30 import org.opendaylight.controller.config.util.xml.XmlUtil;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
34 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
35 import org.opendaylight.netconf.mapping.api.HandlingPriority;
36 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
37 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
38 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
39 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
46 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.Module;
49 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Attr;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
56 import org.w3c.dom.Node;
57 import org.w3c.dom.NodeList;
59 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
61 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
63 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
66 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
67 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
70 private final CurrentSchemaContext schemaContext;
71 private final DOMRpcService rpcService;
73 public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
74 final DOMRpcService rpcService) {
75 super(netconfSessionIdForReporting);
76 this.schemaContext = schemaContext;
77 this.rpcService = rpcService;
81 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
82 final URI namespaceURI = createNsUri(namespace);
83 final Optional<Module> module = getModule(namespaceURI);
85 if (!module.isPresent()) {
86 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
87 return HandlingPriority.CANNOT_HANDLE;
90 getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
91 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
96 protected String getOperationName() {
97 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
100 private static URI createNsUri(final String namespace) {
101 // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
102 return URI.create(namespace);
105 //this returns module with the newest revision if more then 1 module with same namespace is found
106 private Optional<Module> getModule(final URI namespaceURI) {
107 return Optional.fromNullable(
108 schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
111 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
113 for (final RpcDefinition rpcDef : module.getRpcs()) {
114 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
115 && rpcDef.getQName().getLocalName().equals(name)) {
116 return Optional.of(rpcDef);
119 return Optional.absent();
123 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
124 throws DocumentedException {
126 final String netconfOperationName = operationElement.getName();
127 final String netconfOperationNamespace;
129 netconfOperationNamespace = operationElement.getNamespace();
130 } catch (final DocumentedException e) {
131 LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
132 throw new DocumentedException("Cannot retrieve netconf operation namespace from message",
133 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
136 final URI namespaceURI = createNsUri(netconfOperationNamespace);
137 final Optional<Module> moduleOptional = getModule(namespaceURI);
139 if (!moduleOptional.isPresent()) {
140 throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
141 + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
142 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
145 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
146 namespaceURI, netconfOperationName);
148 if (!rpcDefinitionOptional.isPresent()) {
149 throw new DocumentedException(
150 "Unable to find RpcDefinition with namespace and name : "
151 + namespaceURI + " " + netconfOperationName,
152 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
155 final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
156 final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
157 final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());
159 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
161 final DOMRpcResult result = rpcFuture.checkedGet();
162 if (result.getResult() == null) {
163 return XmlUtil.createElement(document, XmlNetconfConstants.OK,
164 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
166 return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
167 } catch (final DOMRpcException e) {
168 throw DocumentedException.wrap(e);
173 public Document handle(final Document requestMessage,
174 final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
176 final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
178 final Document document = XmlUtil.newDocument();
180 final XmlElement operationElement = requestElement.getOnlyChildElement();
181 final Map<String, Attr> attributes = requestElement.getAttributes();
183 final Element response = handle(document, operationElement, subsequentOperation);
184 final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
185 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
187 if (XmlElement.fromDomElement(response).hasNamespace()) {
188 rpcReply.appendChild(response);
190 final NodeList list = response.getChildNodes();
191 if (list.getLength() == 0) {
192 rpcReply.appendChild(response);
194 while (list.getLength() != 0) {
195 rpcReply.appendChild(list.item(0));
200 for (final Attr attribute : attributes.values()) {
201 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
203 document.appendChild(rpcReply);
207 private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
208 final SchemaPath rpcOutputPath) {
209 final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
211 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
213 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
214 schemaContext.getCurrentContext(), rpcOutputPath);
216 final SchemaOrderedNormalizedNodeWriter nnWriter =
217 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
219 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
221 nnStreamWriter.close();
223 } catch (IOException | XMLStreamException e) {
224 LOG.warn("Error while closing streams", e);
227 return result.getNode();
230 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
232 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
233 } catch (final XMLStreamException e) {
234 throw new RuntimeException(e);
238 private static void writeRootElement(final XMLStreamWriter xmlWriter,
239 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
241 final Collection<DataContainerChild<?, ?>> value = data.getValue();
242 nnWriter.write(value);
245 } catch (XMLStreamException | IOException e) {
246 Throwables.propagate(e);
251 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
253 * @param element rpc xml element
254 * @param input input container schema node, or null if rpc does not take any input
255 * @return parsed rpc into normalized node, or null if input schema is null
258 private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input) {
259 return input.getChildNodes().isEmpty() ? null : DomToNormalizedNodeParserFactory
260 .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext())
261 .getContainerNodeParser()
262 .parse(Collections.singletonList(element.getDomElement()), input);