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.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.NetconfDocumentedException;
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.codec.xml.XMLStreamNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
46 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
47 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
48 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
49 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Attr;
56 import org.w3c.dom.Document;
57 import org.w3c.dom.Element;
58 import org.w3c.dom.Node;
59 import org.w3c.dom.NodeList;
61 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
63 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
65 private static final XMLOutputFactory XML_OUTPUT_FACTORY;
68 XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
69 XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
72 private final CurrentSchemaContext schemaContext;
73 private final DOMRpcService rpcService;
75 public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
76 final DOMRpcService rpcService) {
77 super(netconfSessionIdForReporting);
78 this.schemaContext = schemaContext;
79 this.rpcService = rpcService;
83 protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
84 final URI namespaceURI = createNsUri(namespace);
85 final Optional<Module> module = getModule(namespaceURI);
87 if (!module.isPresent()) {
88 LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
89 return HandlingPriority.CANNOT_HANDLE;
92 getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
93 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
98 protected String getOperationName() {
99 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
102 private static URI createNsUri(final String namespace) {
103 // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
104 return URI.create(namespace);
107 //this returns module with the newest revision if more then 1 module with same namespace is found
108 private Optional<Module> getModule(final URI namespaceURI) {
109 return Optional.fromJavaUtil(schemaContext.getCurrentContext().findModule(namespaceURI));
112 private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
114 for (final RpcDefinition rpcDef : module.getRpcs()) {
115 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
116 && rpcDef.getQName().getLocalName().equals(name)) {
117 return Optional.of(rpcDef);
120 return Optional.absent();
124 protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
125 throws DocumentedException {
127 final String netconfOperationName = operationElement.getName();
128 final String netconfOperationNamespace;
130 netconfOperationNamespace = operationElement.getNamespace();
131 } catch (final DocumentedException e) {
132 LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
133 throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
134 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
137 final URI namespaceURI = createNsUri(netconfOperationNamespace);
138 final Optional<Module> moduleOptional = getModule(namespaceURI);
140 if (!moduleOptional.isPresent()) {
141 throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
142 + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
143 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
146 final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
147 namespaceURI, netconfOperationName);
149 if (!rpcDefinitionOptional.isPresent()) {
150 throw new DocumentedException(
151 "Unable to find RpcDefinition with namespace and name : "
152 + namespaceURI + " " + netconfOperationName,
153 ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
156 final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
157 final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
158 final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());
160 final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
162 final DOMRpcResult result = rpcFuture.checkedGet();
163 if (result.getResult() == null) {
164 return XmlUtil.createElement(document, XmlNetconfConstants.OK,
165 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
167 return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
168 } catch (final DOMRpcException e) {
169 throw DocumentedException.wrap(e);
174 public Document handle(final Document requestMessage,
175 final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
177 final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
179 final Document document = XmlUtil.newDocument();
181 final XmlElement operationElement = requestElement.getOnlyChildElement();
182 final Map<String, Attr> attributes = requestElement.getAttributes();
184 final Element response = handle(document, operationElement, subsequentOperation);
185 final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
186 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
188 if (XmlElement.fromDomElement(response).hasNamespace()) {
189 rpcReply.appendChild(response);
191 final NodeList list = response.getChildNodes();
192 if (list.getLength() == 0) {
193 rpcReply.appendChild(response);
195 while (list.getLength() != 0) {
196 rpcReply.appendChild(list.item(0));
201 for (final Attr attribute : attributes.values()) {
202 rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
204 document.appendChild(rpcReply);
208 private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
209 final SchemaPath rpcOutputPath) {
210 final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
212 final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
214 final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
215 schemaContext.getCurrentContext(), rpcOutputPath);
217 final SchemaOrderedNormalizedNodeWriter nnWriter =
218 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
220 writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
222 nnStreamWriter.close();
224 } catch (IOException | XMLStreamException e) {
225 LOG.warn("Error while closing streams", e);
228 return result.getNode();
231 private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
233 return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
234 } catch (final XMLStreamException e) {
235 throw new RuntimeException(e);
239 private static void writeRootElement(final XMLStreamWriter xmlWriter,
240 final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
242 final Collection<DataContainerChild<?, ?>> value = data.getValue();
243 nnWriter.write(value);
246 } catch (XMLStreamException | IOException e) {
247 throw new RuntimeException(e);
252 * Parses xml element rpc input into normalized node or null if rpc does not take any input.
254 * @param element rpc xml element
255 * @param input input container schema node, or null if rpc does not take any input
256 * @return parsed rpc into normalized node, or null if input schema is null
258 @SuppressWarnings("checkstyle:IllegalCatch")
260 private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input)
261 throws DocumentedException {
262 if (input.getChildNodes().isEmpty()) {
266 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
267 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
268 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext.getCurrentContext(), input);
271 xmlParser.traverse(new DOMSource(element.getDomElement()));
272 } catch (final Exception ex) {
273 throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex, ErrorType.PROTOCOL,
274 ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
277 return resultHolder.getResult();