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;
12 import java.net.URISyntaxException;
13 import java.util.Collection;
15 import java.util.Optional;
16 import java.util.concurrent.ExecutionException;
17 import javax.xml.stream.XMLOutputFactory;
18 import javax.xml.stream.XMLStreamException;
19 import javax.xml.stream.XMLStreamWriter;
20 import javax.xml.transform.dom.DOMResult;
21 import javax.xml.transform.dom.DOMSource;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
24 import org.opendaylight.mdsal.dom.api.DOMRpcService;
25 import org.opendaylight.netconf.api.DocumentedException;
26 import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
27 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
28 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
29 import org.opendaylight.netconf.api.NetconfDocumentedException;
30 import org.opendaylight.netconf.api.xml.XmlElement;
31 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
32 import org.opendaylight.netconf.api.xml.XmlUtil;
33 import org.opendaylight.netconf.mapping.api.HandlingPriority;
34 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
35 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
36 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
37 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
45 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.w3c.dom.Attr;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55 import org.w3c.dom.NodeList;
56 import org.xml.sax.SAXException;
58 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
60 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
62 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
65 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
66 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
69 private final CurrentSchemaContext schemaContext;
70 private final DOMRpcService rpcService;
72 public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
73 final DOMRpcService rpcService) {
74 super(netconfSessionIdForReporting);
75 this.schemaContext = schemaContext;
76 this.rpcService = rpcService;
80 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
81 final URI namespaceURI = createNsUri(namespace);
82 final Optional<? extends Module> module = getModule(namespaceURI);
84 if (module.isEmpty()) {
85 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
86 return HandlingPriority.CANNOT_HANDLE;
89 getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
90 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
95 protected String getOperationName() {
96 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
99 private static URI createNsUri(final String namespace) {
100 // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
101 return URI.create(namespace);
104 //this returns module with the newest revision if more then 1 module with same namespace is found
105 private Optional<? extends Module> getModule(final URI namespaceURI) {
106 return schemaContext.getCurrentContext().findModules(namespaceURI).stream().findFirst();
109 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
111 for (final RpcDefinition rpcDef : module.getRpcs()) {
112 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
113 && rpcDef.getQName().getLocalName().equals(name)) {
114 return Optional.of(rpcDef);
117 return Optional.empty();
121 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
122 throws DocumentedException {
124 final String netconfOperationName = operationElement.getName();
125 final String netconfOperationNamespace;
127 netconfOperationNamespace = operationElement.getNamespace();
128 } catch (final DocumentedException e) {
129 LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
130 throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
131 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
134 final URI namespaceURI = createNsUri(netconfOperationNamespace);
135 final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
137 if (moduleOptional.isEmpty()) {
138 throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
139 + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
140 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
143 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
144 namespaceURI, netconfOperationName);
146 if (rpcDefinitionOptional.isEmpty()) {
147 throw new DocumentedException(
148 "Unable to find RpcDefinition with namespace and name : "
149 + namespaceURI + " " + netconfOperationName,
150 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
153 final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
154 final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());
156 final DOMRpcResult result;
158 result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
159 } catch (final InterruptedException | ExecutionException e) {
160 throw DocumentedException.wrap(e);
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 transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
170 public Document handle(final Document requestMessage,
171 final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
173 final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
175 final Document document = XmlUtil.newDocument();
177 final XmlElement operationElement = requestElement.getOnlyChildElement();
178 final Map<String, Attr> attributes = requestElement.getAttributes();
180 final Element response = handle(document, operationElement, subsequentOperation);
181 final Element rpcReply = XmlUtil.createElement(document, XmlNetconfConstants.RPC_REPLY_KEY,
182 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
184 if (XmlElement.fromDomElement(response).hasNamespace()) {
185 rpcReply.appendChild(response);
187 final NodeList list = response.getChildNodes();
188 if (list.getLength() == 0) {
189 rpcReply.appendChild(response);
191 while (list.getLength() != 0) {
192 rpcReply.appendChild(list.item(0));
197 for (final Attr attribute : attributes.values()) {
198 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
200 document.appendChild(rpcReply);
204 private Element transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
205 final SchemaPath rpcOutputPath) {
206 final DOMResult result = new DOMResult(document.createElement(XmlNetconfConstants.RPC_REPLY_KEY));
208 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
210 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
211 schemaContext.getCurrentContext(), rpcOutputPath);
213 final SchemaOrderedNormalizedNodeWriter nnWriter =
214 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
216 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
218 nnStreamWriter.close();
220 } catch (IOException | XMLStreamException e) {
221 LOG.warn("Error while closing streams", e);
224 return (Element) result.getNode();
227 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
229 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
230 } catch (final XMLStreamException e) {
231 throw new RuntimeException(e);
235 private static void writeRootElement(final XMLStreamWriter xmlWriter,
236 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
238 final Collection<DataContainerChild<?, ?>> value = data.getValue();
239 nnWriter.write(value);
242 } catch (XMLStreamException | IOException e) {
243 throw new RuntimeException(e);
248 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
250 * @param element rpc xml element
251 * @param input input container schema node, or null if rpc does not take any input
252 * @return parsed rpc into normalized node, or null if input schema is null
254 private @Nullable ContainerNode rpcToNNode(final XmlElement element,
255 final @Nullable InputSchemaNode input) throws DocumentedException {
256 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
257 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
258 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext.getCurrentContext(), input);
261 xmlParser.traverse(new DOMSource(element.getDomElement()));
262 } catch (final XMLStreamException | URISyntaxException | IOException | SAXException ex) {
263 throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex, ErrorType.PROTOCOL,
264 ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
267 return (ContainerNode) resultHolder.getResult();