Fix various warnings
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / RuntimeRpc.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.mdsal.connector.ops;
10
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;
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.Map;
20 import javax.annotation.Nullable;
21 import javax.xml.stream.XMLOutputFactory;
22 import javax.xml.stream.XMLStreamException;
23 import javax.xml.stream.XMLStreamWriter;
24 import javax.xml.transform.dom.DOMResult;
25 import org.opendaylight.controller.config.util.xml.DocumentedException;
26 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
27 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
28 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.config.util.xml.XmlMappingConstants;
31 import org.opendaylight.controller.config.util.xml.XmlUtil;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
34 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
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.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
47 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
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;
59
60 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
61
62     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
63
64     private final CurrentSchemaContext schemaContext;
65     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
66
67     static {
68         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
69         XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
70     }
71
72     private final DOMRpcService rpcService;
73
74     public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
75                       final DOMRpcService rpcService) {
76         super(netconfSessionIdForReporting);
77         this.schemaContext = schemaContext;
78         this.rpcService = rpcService;
79     }
80
81     @Override
82     protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
83         final URI namespaceURI = createNsUri(namespace);
84         final Optional<Module> module = getModule(namespaceURI);
85
86         if (!module.isPresent()) {
87             LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
88             return HandlingPriority.CANNOT_HANDLE;
89         }
90
91         getRpcDefinitionFromModule(module.get(), namespaceURI, netconfOperationName);
92         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
93
94     }
95
96     @Override
97     protected String getOperationName() {
98         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
99     }
100
101     private static URI createNsUri(final String namespace) {
102         final URI namespaceURI;
103         try {
104             namespaceURI = new URI(namespace);
105         } catch (final URISyntaxException e) {
106             // Cannot occur, namespace in parsed XML cannot be invalid URI
107             throw new IllegalStateException("Unable to parse URI " + namespace, e);
108         }
109         return namespaceURI;
110     }
111
112     //this returns module with the newest revision if more then 1 module with same namespace is found
113     private Optional<Module> getModule(final URI namespaceURI) {
114         return Optional.fromNullable(
115                 schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
116     }
117
118     private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
119             final String name) {
120         for (final RpcDefinition rpcDef : module.getRpcs()) {
121             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
122                     && rpcDef.getQName().getLocalName().equals(name)) {
123                 return Optional.of(rpcDef);
124             }
125         }
126         return Optional.absent();
127     }
128
129     @Override
130     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
131             throws DocumentedException {
132
133         final String netconfOperationName = operationElement.getName();
134         final String netconfOperationNamespace;
135         try {
136             netconfOperationNamespace = operationElement.getNamespace();
137         } catch (final DocumentedException e) {
138             LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
139             throw new DocumentedException("Cannot retrieve netconf operation namespace from message",
140                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
141         }
142
143         final URI namespaceURI = createNsUri(netconfOperationNamespace);
144         final Optional<Module> moduleOptional = getModule(namespaceURI);
145
146         if (!moduleOptional.isPresent()) {
147             throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
148                         + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
149                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
150         }
151
152         final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
153                 namespaceURI, netconfOperationName);
154
155         if (!rpcDefinitionOptional.isPresent()) {
156             throw new DocumentedException(
157                     "Unable to find RpcDefinition with namespace and name : "
158                         + namespaceURI + " " + netconfOperationName,
159                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
160         }
161
162         final RpcDefinition rpcDefinition = rpcDefinitionOptional.get();
163         final SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(rpcDefinition.getQName()), true);
164         final NormalizedNode<?, ?> inputNode = rpcToNNode(operationElement, rpcDefinition.getInput());
165
166         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcFuture = rpcService.invokeRpc(schemaPath, inputNode);
167         try {
168             final DOMRpcResult result = rpcFuture.checkedGet();
169             if (result.getResult() == null) {
170                 return XmlUtil.createElement(document, XmlNetconfConstants.OK,
171                         Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
172             }
173             return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
174         } catch (final DOMRpcException e) {
175             throw DocumentedException.wrap(e);
176         }
177     }
178
179     @Override
180     public Document handle(final Document requestMessage,
181                            final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
182
183         final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
184
185         final Document document = XmlUtil.newDocument();
186
187         final XmlElement operationElement = requestElement.getOnlyChildElement();
188         final Map<String, Attr> attributes = requestElement.getAttributes();
189
190         final Element response = handle(document, operationElement, subsequentOperation);
191         final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
192                 Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
193
194         if (XmlElement.fromDomElement(response).hasNamespace()) {
195             rpcReply.appendChild(response);
196         } else {
197             final NodeList list = response.getChildNodes();
198             if (list.getLength() == 0) {
199                 rpcReply.appendChild(response);
200             } else {
201                 while (list.getLength() != 0) {
202                     rpcReply.appendChild(list.item(0));
203                 }
204             }
205         }
206
207         for (final Attr attribute : attributes.values()) {
208             rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
209         }
210         document.appendChild(rpcReply);
211         return document;
212     }
213
214     private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
215                                          final SchemaPath rpcOutputPath) {
216         final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
217
218         final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
219
220         final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
221                 schemaContext.getCurrentContext(), rpcOutputPath);
222
223         final SchemaOrderedNormalizedNodeWriter nnWriter =
224                 new SchemaOrderedNormalizedNodeWriter(nnStreamWriter, schemaContext.getCurrentContext(), rpcOutputPath);
225
226         writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
227         try {
228             nnStreamWriter.close();
229             xmlWriter.close();
230         } catch (IOException | XMLStreamException e) {
231             LOG.warn("Error while closing streams", e);
232         }
233
234         return result.getNode();
235     }
236
237     private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
238         try {
239             return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
240         } catch (final XMLStreamException e) {
241             throw new RuntimeException(e);
242         }
243     }
244
245     private static void writeRootElement(final XMLStreamWriter xmlWriter,
246             final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
247         try {
248             final Collection<DataContainerChild<?, ?>> value = data.getValue();
249             nnWriter.write(value);
250             nnWriter.flush();
251             xmlWriter.flush();
252         } catch (XMLStreamException | IOException e) {
253             Throwables.propagate(e);
254         }
255     }
256
257     /**
258      * Parses xml element rpc input into normalized node or null if rpc does not take any input.
259      *
260      * @param element rpc xml element
261      * @param input   input container schema node, or null if rpc does not take any input
262      * @return parsed rpc into normalized node, or null if input schema is null
263      */
264     @Nullable
265     private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input) {
266         return input.getChildNodes().isEmpty() ? null : DomToNormalizedNodeParserFactory
267                 .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext())
268                 .getContainerNodeParser()
269                 .parse(Collections.singletonList(element.getDomElement()), input);
270     }
271
272 }