Merge changes I6575ddd8,I4b78f51d,I0a0441e6
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / netconf / mdsal / connector / ops / RuntimeRpc.java
index 7c5630a27b6008dd7fd35579ed9c3f53640b0241..18923edb7b4d21f81a82918d2d441889495c3e02 100644 (file)
@@ -12,8 +12,8 @@ import com.google.common.base.Optional;
 import com.google.common.base.Throwables;
 import com.google.common.util.concurrent.CheckedFuture;
 import java.io.IOException;
+import java.io.StringReader;
 import java.net.URI;
-import java.net.URISyntaxException;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Map;
@@ -32,19 +32,22 @@ import org.opendaylight.controller.config.util.xml.XmlUtil;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import org.opendaylight.netconf.api.NetconfDocumentedException;
 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.netconf.mapping.api.HandlingPriority;
 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
+import org.opendaylight.yangtools.util.xml.UntrustedXML;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
@@ -61,17 +64,18 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
 
     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpc.class);
 
-    private final CurrentSchemaContext schemaContext;
     private static final XMLOutputFactory XML_OUTPUT_FACTORY;
 
     static {
         XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
-        XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
+        XML_OUTPUT_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
     }
 
+    private final CurrentSchemaContext schemaContext;
     private final DOMRpcService rpcService;
 
-    public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final DOMRpcService rpcService) {
+    public RuntimeRpc(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+                      final DOMRpcService rpcService) {
         super(netconfSessionIdForReporting);
         this.schemaContext = schemaContext;
         this.rpcService = rpcService;
@@ -97,23 +101,19 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
     }
 
-    private URI createNsUri(final String namespace) {
-        final URI namespaceURI;
-        try {
-            namespaceURI = new URI(namespace);
-        } catch (final URISyntaxException e) {
-            // Cannot occur, namespace in parsed XML cannot be invalid URI
-            throw new IllegalStateException("Unable to parse URI " + namespace, e);
-        }
-        return namespaceURI;
+    private static URI createNsUri(final String namespace) {
+        // May throw IllegalArgumentException, but that should never happen, as the namespace comes from parsed XML
+        return URI.create(namespace);
     }
 
     //this returns module with the newest revision if more then 1 module with same namespace is found
     private Optional<Module> getModule(final URI namespaceURI) {
-        return Optional.fromNullable(schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
+        return Optional.fromNullable(
+                schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(namespaceURI, null));
     }
 
-    private Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI, final String name) {
+    private static Optional<RpcDefinition> getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
+            final String name) {
         for (final RpcDefinition rpcDef : module.getRpcs()) {
             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
                     && rpcDef.getQName().getLocalName().equals(name)) {
@@ -124,7 +124,8 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+            throws DocumentedException {
 
         final String netconfOperationName = operationElement.getName();
         final String netconfOperationNamespace;
@@ -140,15 +141,18 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         final Optional<Module> moduleOptional = getModule(namespaceURI);
 
         if (!moduleOptional.isPresent()) {
-            throw new DocumentedException("Unable to find module in Schema Context with namespace and name : " +
-                    namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
+            throw new DocumentedException("Unable to find module in Schema Context with namespace and name : "
+                        + namespaceURI + " " + netconfOperationName + schemaContext.getCurrentContext(),
                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
         }
 
-        final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(), namespaceURI, netconfOperationName);
+        final Optional<RpcDefinition> rpcDefinitionOptional = getRpcDefinitionFromModule(moduleOptional.get(),
+                namespaceURI, netconfOperationName);
 
         if (!rpcDefinitionOptional.isPresent()) {
-            throw new DocumentedException("Unable to find RpcDefinition with namespace and name : " + namespaceURI + " " + netconfOperationName,
+            throw new DocumentedException(
+                    "Unable to find RpcDefinition with namespace and name : "
+                        + namespaceURI + " " + netconfOperationName,
                     ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, ErrorSeverity.ERROR);
         }
 
@@ -160,7 +164,8 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         try {
             final DOMRpcResult result = rpcFuture.checkedGet();
             if (result.getResult() == null) {
-                return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+                return XmlUtil.createElement(document, XmlNetconfConstants.OK,
+                        Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
             }
             return (Element) transformNormalizedNode(document, result.getResult(), rpcDefinition.getOutput().getPath());
         } catch (final DOMRpcException e) {
@@ -180,9 +185,10 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         final Map<String, Attr> attributes = requestElement.getAttributes();
 
         final Element response = handle(document, operationElement, subsequentOperation);
-        final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+        final Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
+                Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
 
-        if(XmlElement.fromDomElement(response).hasNamespace()) {
+        if (XmlElement.fromDomElement(response).hasNamespace()) {
             rpcReply.appendChild(response);
         } else {
             final NodeList list = response.getChildNodes();
@@ -202,7 +208,8 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         return document;
     }
 
-    private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data, final SchemaPath rpcOutputPath) {
+    private Node transformNormalizedNode(final Document document, final NormalizedNode<?, ?> data,
+                                         final SchemaPath rpcOutputPath) {
         final DOMResult result = new DOMResult(document.createElement(XmlMappingConstants.RPC_REPLY_KEY));
 
         final XMLStreamWriter xmlWriter = getXmlStreamWriter(result);
@@ -224,7 +231,7 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         return result.getNode();
     }
 
-    private XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
+    private static XMLStreamWriter getXmlStreamWriter(final DOMResult result) {
         try {
             return XML_OUTPUT_FACTORY.createXMLStreamWriter(result);
         } catch (final XMLStreamException e) {
@@ -232,9 +239,10 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
         }
     }
 
-    private void writeRootElement(final XMLStreamWriter xmlWriter, final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
+    private static void writeRootElement(final XMLStreamWriter xmlWriter,
+            final SchemaOrderedNormalizedNodeWriter nnWriter, final ContainerNode data) {
         try {
-            final Collection<DataContainerChild<?, ?>> value = (Collection) data.getValue();
+            final Collection<DataContainerChild<?, ?>> value = data.getValue();
             nnWriter.write(value);
             nnWriter.flush();
             xmlWriter.flush();
@@ -244,17 +252,32 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation {
     }
 
     /**
-     * Parses xml element rpc input into normalized node or null if rpc does not take any input
-     * @param oElement rpc xml element
-     * @param input input container schema node, or null if rpc does not take any input
+     * Parses xml element rpc input into normalized node or null if rpc does not take any input.
+     *
+     * @param element rpc xml element
+     * @param input   input container schema node, or null if rpc does not take any input
      * @return parsed rpc into normalized node, or null if input schema is null
      */
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Nullable
-    private NormalizedNode<?, ?> rpcToNNode(final XmlElement oElement, @Nullable final ContainerSchemaNode input) {
-        return input == null ? null : DomToNormalizedNodeParserFactory
-                .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext())
-                .getContainerNodeParser()
-                .parse(Collections.singletonList(oElement.getDomElement()), input);
+    private NormalizedNode<?, ?> rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input)
+            throws DocumentedException {
+        if (input.getChildNodes().isEmpty()) {
+            return null;
+        }
+
+        final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
+        final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
+        final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext.getCurrentContext(), input);
+
+        try {
+            xmlParser.parse(UntrustedXML.createXMLStreamReader(new StringReader(XmlUtil.toString(element))));
+        } catch (final Exception ex) {
+            throw new NetconfDocumentedException("Error parsing input: " + ex.getMessage(), ex, ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR);
+        }
+
+        return resultHolder.getResult();
     }
 
 }