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.util.concurrent.CheckedFuture;
13 import java.io.IOException;
15 import java.util.Collection;
16 import java.util.Collections;
18 import javax.annotation.Nullable;
19 import javax.xml.stream.XMLOutputFactory;
20 import javax.xml.stream.XMLStreamException;
21 import javax.xml.stream.XMLStreamWriter;
22 import javax.xml.transform.dom.DOMResult;
23 import javax.xml.transform.dom.DOMSource;
24 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
25 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
27 import org.opendaylight.netconf.api.DocumentedException;
28 import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
29 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
30 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
31 import org.opendaylight.netconf.api.NetconfDocumentedException;
32 import org.opendaylight.netconf.api.xml.XmlElement;
33 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
34 import org.opendaylight.netconf.api.xml.XmlUtil;
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.codec.xml.XmlParserStream;
45 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
47 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
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 static final XMLOutputFactory XML_OUTPUT_FACTORY;
67 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
68 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
71 private final CurrentSchemaContext schemaContext;
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 // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
103 return URI.create(namespace);
106 //this returns module with the newest revision if more then 1 module with same namespace is found
107 private Optional<Module> getModule(final URI namespaceURI) {
108 return Optional.fromJavaUtil(schemaContext.getCurrentContext().findModule(namespaceURI));
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", e,
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, XmlNetconfConstants.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(XmlNetconfConstants.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 throw new RuntimeException(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
257 @SuppressWarnings("checkstyle:IllegalCatch")
259 private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input)
260 throws DocumentedException {
261 if (input == null || input.getChildNodes().isEmpty()) {
265 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
266 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
267 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext.getCurrentContext(), input);
270 xmlParser.traverse(new DOMSource(element.getDomElement()));
271 } catch (final Exception ex) {
272 throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex, ErrorType.PROTOCOL,
273 ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
276 return resultHolder.getResult();