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
8 package org.opendaylight.netconf.mdsal.connector.ops;
10 import java.io.IOException;
11 import java.net.URISyntaxException;
13 import java.util.Optional;
14 import java.util.concurrent.ExecutionException;
15 import javax.xml.stream.XMLOutputFactory;
16 import javax.xml.stream.XMLStreamException;
17 import javax.xml.stream.XMLStreamWriter;
18 import javax.xml.transform.dom.DOMResult;
19 import javax.xml.transform.dom.DOMSource;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
22 import org.opendaylight.mdsal.dom.api.DOMRpcService;
23 import org.opendaylight.netconf.api.DocumentedException;
24 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
25 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
26 import org.opendaylight.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.netconf.api.xml.XmlElement;
28 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
29 import org.opendaylight.netconf.api.xml.XmlUtil;
30 import org.opendaylight.netconf.mapping.api.HandlingPriority;
31 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
32 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
33 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
34 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
35 import org.opendaylight.yangtools.yang.common.XMLNamespace;
36 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
41 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
43 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
48 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.w3c.dom.Attr;
52 import org.w3c.dom.Document;
53 import org.w3c.dom.Element;
54 import org.w3c.dom.NodeList;
55 import org.xml.sax.SAXException;
57 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
59 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
61 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
64 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
65 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
68 private final CurrentSchemaContext schemaContext;
69 private final DOMRpcService rpcService;
71 public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
72 final DOMRpcService rpcService) {
73 super(netconfSessionIdForReporting);
74 this.schemaContext = schemaContext;
75 this.rpcService = rpcService;
79 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
80 final XMLNamespace namespaceURI = createNsUri(namespace);
81 final Optional<? extends Module> module = getModule(namespaceURI);
83 if (module.isEmpty()) {
84 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
85 return HandlingPriority.CANNOT_HANDLE;
88 getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
89 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
94 protected String getOperationName() {
95 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
98 private static XMLNamespace createNsUri(final String namespace) {
99 // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
100 return XMLNamespace.of(namespace);
103 //this returns module with the newest revision if more then 1 module with same namespace is found
104 private Optional<? extends Module> getModule(final XMLNamespace namespace) {
105 return schemaContext.getCurrentContext().findModules(namespace).stream().findFirst();
108 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final XMLNamespace namespace,
110 for (final RpcDefinition rpcDef : module.getRpcs()) {
111 if (rpcDef.getQName().getNamespace().equals(namespace) && rpcDef.getQName().getLocalName().equals(name)) {
112 return Optional.of(rpcDef);
115 return Optional.empty();
119 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
120 throws DocumentedException {
122 final String netconfOperationName = operationElement.getName();
123 final String netconfOperationNamespace;
125 netconfOperationNamespace = operationElement.getNamespace();
126 } catch (final DocumentedException e) {
127 LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
128 throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
129 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
132 final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
133 final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
135 if (moduleOptional.isEmpty()) {
136 throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
137 + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
138 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
141 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
142 namespaceURI, netconfOperationName);
144 if (rpcDefinitionOptional.isEmpty()) {
145 throw new DocumentedException(
146 "Unable to find RpcDefinition with namespace and name : "
147 + namespaceURI + " " + netconfOperationName,
148 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
151 final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
152 final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
154 final DOMRpcResult result;
156 result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
157 } catch (final InterruptedException | ExecutionException e) {
158 throw DocumentedException.wrap(e);
160 if (result.getResult() == null) {
161 return XmlUtil.createElement(document, XmlNetconfConstants.OK,
162 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
164 return transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
168 public Document handle(final Document requestMessage,
169 final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
171 final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
173 final Document document = XmlUtil.newDocument();
175 final XmlElement operationElement = requestElement.getOnlyChildElement();
176 final Map<String, Attr> attributes = requestElement.getAttributes();
178 final Element response = handle(document, operationElement, subsequentOperation);
179 final Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY,
180 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
182 if (XmlElement.fromDomElement(response).hasNamespace()) {
183 rpcReply.appendChild(response);
185 final NodeList list = response.getChildNodes();
186 if (list.getLength() == 0) {
187 rpcReply.appendChild(response);
189 while (list.getLength() != 0) {
190 rpcReply.appendChild(list.item(0));
195 for (final Attr attribute : attributes.values()) {
196 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
198 document.appendChild(rpcReply);
202 private Element transformNormalizedNode(final Document document, final NormalizedNode data,
203 final SchemaPath rpcOutputPath) {
204 final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.RPC_REPLY_KEY));
206 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
208 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
209 schemaContext.getCurrentContext(), rpcOutputPath);
211 final SchemaOrderedNormalizedNodeWriter nnWriter =
212 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
214 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
216 nnStreamWriter.close();
218 } catch (IOException | XMLStreamException e) {
219 LOG.warn("Error while closing streams", e);
222 return (Element) result.getNode();
225 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
227 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
228 } catch (final XMLStreamException e) {
229 throw new RuntimeException(e);
233 private static void writeRootElement(final XMLStreamWriter xmlWriter,
234 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
236 nnWriter.write(data.body());
239 } catch (XMLStreamException | IOException e) {
240 throw new RuntimeException(e);
245 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
247 * @param element rpc xml element
248 * @param rpcDefinition input container schema node, or null if rpc does not take any input
249 * @return parsed rpc into normalized node, or null if input schema is null
251 private @Nullable ContainerNode rpcToNNode(final XmlElement element,
252 final RpcDefinition rpcDefinition) throws DocumentedException {
253 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
254 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
255 final XmlParserStream xmlParser = XmlParserStream.create(writer, SchemaInferenceStack.of(
256 schemaContext.getCurrentContext(),
257 Absolute.of(rpcDefinition.getQName(), rpcDefinition.getInput().getQName())).toInference());
260 xmlParser.traverse(new DOMSource(element.getDomElement()));
261 } catch (final XMLStreamException | URISyntaxException | IOException | SAXException ex) {
262 throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex, ErrorType.PROTOCOL,
263 ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
266 return (ContainerNode) resultHolder.getResult();