Eliminate XmlUtil.createElement() et al.
[netconf.git] / plugins / netconf-server-mdsal / src / main / java / org / opendaylight / netconf / server / mdsal / operations / 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 package org.opendaylight.netconf.server.mdsal.operations;
9
10 import java.io.IOException;
11 import java.util.Map;
12 import java.util.Optional;
13 import java.util.concurrent.ExecutionException;
14 import javax.xml.stream.XMLOutputFactory;
15 import javax.xml.stream.XMLStreamException;
16 import javax.xml.stream.XMLStreamWriter;
17 import javax.xml.transform.dom.DOMResult;
18 import javax.xml.transform.dom.DOMSource;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
21 import org.opendaylight.mdsal.dom.api.DOMRpcService;
22 import org.opendaylight.netconf.api.DocumentedException;
23 import org.opendaylight.netconf.api.NamespaceURN;
24 import org.opendaylight.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.netconf.api.messages.RpcReplyMessage;
26 import org.opendaylight.netconf.api.xml.XmlElement;
27 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
28 import org.opendaylight.netconf.api.xml.XmlUtil;
29 import org.opendaylight.netconf.server.api.operations.AbstractSingletonNetconfOperation;
30 import org.opendaylight.netconf.server.api.operations.HandlingPriority;
31 import org.opendaylight.netconf.server.api.operations.NetconfOperationChainedExecution;
32 import org.opendaylight.netconf.server.mdsal.CurrentSchemaContext;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.SessionIdType;
34 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
35 import org.opendaylight.yangtools.yang.common.ErrorTag;
36 import org.opendaylight.yangtools.yang.common.ErrorType;
37 import org.opendaylight.yangtools.yang.common.XMLNamespace;
38 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
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.NormalizationResultHolder;
45 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
49 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack;
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
57 public class RuntimeRpc extends AbstractSingletonNetconfOperation {
58     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
59     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
60
61     static {
62         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
63         XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
64     }
65
66     private final CurrentSchemaContext schemaContext;
67     private final DOMRpcService rpcService;
68
69     public RuntimeRpc(final SessionIdType sessionId, final CurrentSchemaContext schemaContext,
70             final DOMRpcService rpcService) {
71         super(sessionId);
72         this.schemaContext = schemaContext;
73         this.rpcService = rpcService;
74     }
75
76     @Override
77     protected HandlingPriority canHandle(final String netconfOperationName, final String namespace) {
78         final XMLNamespace namespaceURI = createNsUri(namespace);
79         final Optional<? extends Module> module = getModule(namespaceURI);
80
81         if (module.isEmpty()) {
82             LOG.debug("Cannot handle rpc: {}, {}", netconfOperationName, namespace);
83             return HandlingPriority.CANNOT_HANDLE;
84         }
85
86         getRpcDefinitionFromModule(module.orElseThrow(), namespaceURI, netconfOperationName);
87         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
88     }
89
90     @Override
91     protected String getOperationName() {
92         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
93     }
94
95     private static XMLNamespace createNsUri(final String namespace) {
96         // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
97         return XMLNamespace.of(namespace);
98     }
99
100     //this returns module with the newest revision if more then 1 module with same namespace is found
101     private Optional<? extends Module> getModule(final XMLNamespace namespace) {
102         return schemaContext.getCurrentContext().findModules(namespace).stream().findFirst();
103     }
104
105     private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final XMLNamespace namespace,
106             final String name) {
107         for (final RpcDefinition rpcDef : module.getRpcs()) {
108             if (rpcDef.getQName().getNamespace().equals(namespace) && rpcDef.getQName().getLocalName().equals(name)) {
109                 return Optional.of(rpcDef);
110             }
111         }
112         return Optional.empty();
113     }
114
115     @Override
116     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
117             throws DocumentedException {
118
119         final String netconfOperationName = operationElement.getName();
120         final String netconfOperationNamespace;
121         try {
122             netconfOperationNamespace = operationElement.getNamespace();
123         } catch (final DocumentedException e) {
124             LOG.debug("Cannot retrieve netconf operation namespace from message due to ", e);
125             throw new DocumentedException("Cannot retrieve netconf operation namespace from message", e,
126                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
127         }
128
129         final XMLNamespace namespaceURI = createNsUri(netconfOperationNamespace);
130         final Optional<? extends Module> moduleOptional = getModule(namespaceURI);
131
132         if (moduleOptional.isEmpty()) {
133             throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
134                         + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
135                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
136         }
137
138         final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.orElseThrow(),
139                 namespaceURI, netconfOperationName);
140
141         if (rpcDefinitionOptional.isEmpty()) {
142             throw new DocumentedException(
143                     "Unable to find RpcDefinition with namespace and name : "
144                         + namespaceURI + " " + netconfOperationName,
145                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
146         }
147
148         final RpcDefinition rpcDefinition = rpcDefinitionOptional.orElseThrow();
149         final ContainerNode inputNode = rpcToNNode(operationElement, rpcDefinition);
150
151         final DOMRpcResult result;
152         try {
153             result = rpcService.invokeRpc(rpcDefinition.getQName(), inputNode).get();
154         } catch (final InterruptedException | ExecutionException e) {
155             throw DocumentedException.wrap(e);
156         }
157         if (result.value() == null) {
158             return document.createElementNS(NamespaceURN.BASE, XmlNetconfConstants.OK);
159         }
160         return transformNormalizedNode(document, result.value(),
161                 Absolute.of(rpcDefinition.getQName(), rpcDefinition.getOutput().getQName()));
162     }
163
164     @Override
165     public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
166             throws DocumentedException {
167         final XmlElement requestElement = getRequestElementWithCheck(requestMessage);
168         final Document document = XmlUtil.newDocument();
169         final XmlElement operationElement = requestElement.getOnlyChildElement();
170         final Map<String, Attr> attributes = requestElement.getAttributes();
171
172         final Element response = handle(document, operationElement, subsequentOperation);
173         final Element rpcReply = document.createElementNS(NamespaceURN.BASE, RpcReplyMessage.ELEMENT_NAME);
174
175         if (XmlElement.fromDomElement(response).hasNamespace()) {
176             rpcReply.appendChild(response);
177         } else {
178             final NodeList list = response.getChildNodes();
179             if (list.getLength() == 0) {
180                 rpcReply.appendChild(response);
181             } else {
182                 while (list.getLength() != 0) {
183                     rpcReply.appendChild(list.item(0));
184                 }
185             }
186         }
187
188         for (final Attr attribute : attributes.values()) {
189             rpcReply.setAttributeNode((Attr) document.importNode(attribute, true));
190         }
191         document.appendChild(rpcReply);
192         return document;
193     }
194
195     private Element transformNormalizedNode(final Document document, final NormalizedNode data,
196                                             final Absolute rpcOutputPath) {
197         final DOMResult result = new DOMResult(document.createElement(RpcReplyMessage.ELEMENT_NAME));
198
199         final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
200
201         final NormalizedNodeStreamWriter nnStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(xmlWriter,
202                 schemaContext.getCurrentContext(), rpcOutputPath);
203
204         final SchemaOrderedNormalizedNodeWriter nnWriter = new SchemaOrderedNormalizedNodeWriter(nnStreamWriter,
205                 schemaContext.getCurrentContext(), rpcOutputPath);
206
207         writeRootElement(xmlWriter, nnWriter, (ContainerNode) data);
208         try {
209             nnStreamWriter.close();
210             xmlWriter.close();
211         } catch (IOException | XMLStreamException e) {
212             // FIXME: throw DocumentedException
213             LOG.warn("Error while closing streams", e);
214         }
215
216         return (Element) result.getNode();
217     }
218
219     private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
220         try {
221             return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
222         } catch (final XMLStreamException e) {
223             throw new IllegalStateException(e);
224         }
225     }
226
227     private static void writeRootElement(final XMLStreamWriter xmlWriter,
228             final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
229         try {
230             nnWriter.write(data.body());
231             nnWriter.flush();
232             xmlWriter.flush();
233         } catch (XMLStreamException | IOException e) {
234             // FIXME: throw DocumentedException
235             throw new IllegalStateException(e);
236         }
237     }
238
239     /**
240      * Parses xml element rpc input into normalized node or null if rpc does not take any input.
241      *
242      * @param element rpc xml element
243      * @param rpcDefinition   input container schema node, or null if rpc does not take any input
244      * @return parsed rpc into normalized node, or null if input schema is null
245      */
246     private @Nullable ContainerNode rpcToNNode(final XmlElement element,
247             final RpcDefinition rpcDefinition) throws DocumentedException {
248         final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
249         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
250         final XmlParserStream xmlParser = XmlParserStream.create(writer, SchemaInferenceStack.of(
251             schemaContext.getCurrentContext(),
252             Absolute.of(rpcDefinition.getQName(), rpcDefinition.getInput().getQName())).toInference());
253
254         try {
255             xmlParser.traverse(new DOMSource(element.getDomElement()));
256         } catch (final XMLStreamException | IOException ex) {
257             throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex,
258                 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
259         }
260
261         return (ContainerNode) resultHolder.getResult().data();
262     }
263 }