BUG-2314 Migrate netconf-connector to NormalizedNode
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / util / NetconfMessageTransformUtil.java
index 371907e0fe386d3a9697141e15fde388079e7ae7..20085bb275cbb9bd5960357d7dba4138cae2b805 100644 (file)
@@ -9,23 +9,18 @@ package org.opendaylight.controller.sal.connect.netconf.util;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import java.net.URI;
-import java.util.ArrayList;
 import java.util.Collections;
-import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import javax.annotation.Nullable;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
@@ -33,20 +28,20 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+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.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
@@ -54,10 +49,13 @@ public class NetconfMessageTransformUtil {
 
     public static final String MESSAGE_ID_ATTR = "message-id";
     public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.cachedReference(QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
+    private static final String SUBTREE = "subtree";
 
     private NetconfMessageTransformUtil() {}
 
     public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring");
+    public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data");
+    public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema");
     public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format");
     public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location");
     public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier");
@@ -67,9 +65,10 @@ public class NetconfMessageTransformUtil {
     public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications");
 
     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
-    public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
+    public static QName NETCONF_QNAME = QName.create(NETCONF_URI.toString(), "2011-06-01", "netconf");
     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
+    public static QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
@@ -106,46 +105,29 @@ public class NetconfMessageTransformUtil {
     public static QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock");
 
     // Discard changes message
-    public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
-            NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
+    public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
+            Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
 
     // Commit changes message
-    public static final CompositeNode COMMIT_RPC_CONTENT =
-            NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
+    public static final ContainerNode COMMIT_RPC_CONTENT =
+            Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
 
     // Get message
-    public static final CompositeNode GET_RPC_CONTENT =
-            NodeFactory.createImmutableCompositeNode(NETCONF_GET_QNAME, null, Collections.<Node<?>>emptyList());
+    public static final ContainerNode GET_RPC_CONTENT =
+            Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_GET_QNAME)).build();
 
     // Create-subscription changes message
-    public static final CompositeNode CREATE_SUBSCRIPTION_RPC_CONTENT =
-            NodeFactory.createImmutableCompositeNode(CREATE_SUBSCRIPTION_RPC_QNAME, null, Collections.<Node<?>>emptyList());
+    public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
+            Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
 
-    public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
-        Node<?> previous = null;
-        if (Iterables.isEmpty(identifier.getPathArguments())) {
-            return null;
-        }
+    public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
+        final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> filterBuilder = Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+        filterBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
 
-        for (final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument component : identifier.getReversePathArguments()) {
-            if (component instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
-                previous = toNode((YangInstanceIdentifier.NodeIdentifierWithPredicates)component, previous);
-            } else {
-                previous = toNode(component, previous);
-            }
+        if (Iterables.isEmpty(identifier.getPathArguments()) == false) {
+            filterBuilder.withChild((DataContainerChild<?, ?>) InstanceIdToNodes.serialize(ctx, identifier));
         }
-        return filter("subtree", previous);
-    }
-
-    static Node<?> toNode(final YangInstanceIdentifier.NodeIdentifierWithPredicates argument, final Node<?> node) {
-        final List<Node<?>> list = new ArrayList<>();
-        for (final Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
-            list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
-        }
-        if (node != null) {
-            list.add(node);
-        }
-        return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
+        return filterBuilder.build();
     }
 
     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
@@ -154,7 +136,7 @@ public class NetconfMessageTransformUtil {
         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
 
         if(inputMsgId.equals(outputMsgId) == false) {
-            Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
+            final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
                     .put( "actual-message-id", outputMsgId )
                     .put( "expected-message-id", inputMsgId )
                     .build();
@@ -168,24 +150,22 @@ public class NetconfMessageTransformUtil {
 
     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
         if(NetconfMessageUtil.isErrorMessage(output)) {
-            throw NetconfDocumentedException.fromXMLDocument( output.getDocument() );
+            throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
         }
     }
 
-    public static RpcError toRpcError( final NetconfDocumentedException ex )
-    {
-        StringBuilder infoBuilder = new StringBuilder();
-        Map<String, String> errorInfo = ex.getErrorInfo();
-        if( errorInfo != null )
-        {
-            for( Entry<String,String> e: errorInfo.entrySet() ) {
+    public static RpcError toRpcError( final NetconfDocumentedException ex ) {
+        final StringBuilder infoBuilder = new StringBuilder();
+        final Map<String, String> errorInfo = ex.getErrorInfo();
+        if(errorInfo != null) {
+            for( final Entry<String,String> e: errorInfo.entrySet() ) {
                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
                 .append( "</" ).append( e.getKey() ).append( '>' );
 
             }
         }
 
-        ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
+        final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
         return severity == ErrorSeverity.ERROR ?
                 RpcResultBuilder.newError(
                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
@@ -204,8 +184,7 @@ public class NetconfMessageTransformUtil {
         }
     }
 
-    private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type )
-    {
+    private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
         switch( type ) {
         case protocol:
             return RpcError.ErrorType.PROTOCOL;
@@ -218,36 +197,12 @@ public class NetconfMessageTransformUtil {
         }
     }
 
-    public static CompositeNode flattenInput(final CompositeNode node) {
-        final QName inputQName = QName.create(node.getNodeType(), "input");
-        final CompositeNode input = node.getFirstCompositeByName(inputQName);
-        if (input == null) {
-            return node;
-        }
-        if (input instanceof CompositeNode) {
-
-            final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
-                    .addAll(input.getValue()) //
-                    .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
-                        @Override
-                        public boolean apply(@Nullable final Node<?> input) {
-                            return !inputQName.equals(input.getNodeType());
-                        }
-                    })) //
-                    .build();
-
-            return ImmutableCompositeNode.create(node.getNodeType(), nodes);
-        }
-
-        return input;
+    public static YangInstanceIdentifier.NodeIdentifier toId(final YangInstanceIdentifier.PathArgument qname) {
+        return toId(qname.getNodeType());
     }
 
-    static Node<?> toNode(final YangInstanceIdentifier.PathArgument argument, final Node<?> node) {
-        if (node != null) {
-            return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
-        } else {
-            return new SimpleNodeTOImpl<Void>(argument.getNodeType(), null, null);
-        }
+    public static YangInstanceIdentifier.NodeIdentifier toId(final QName nodeType) {
+        return new YangInstanceIdentifier.NodeIdentifier(nodeType);
     }
 
     public static Element getDataSubtree(final Document doc) {
@@ -260,14 +215,6 @@ public class NetconfMessageTransformUtil {
                         NETCONF_GET_QNAME.getLocalName()));
     }
 
-    public static boolean isGetOperation(final QName rpc) {
-        return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_QNAME.getLocalName());
-    }
-
-    public static boolean isGetConfigOperation(final QName rpc) {
-        return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName());
-    }
-
     public static boolean isDataEditOperation(final QName rpc) {
         return NETCONF_URI.equals(rpc.getNamespace())
                 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
@@ -298,6 +245,16 @@ public class NetconfMessageTransformUtil {
         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
     }
 
+    public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
+        final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "data");
+        return new NodeContainerProxy(config, schemaContext.getChildNodes());
+    }
+
+
+    public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
+        return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
+    }
+
     /**
      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
      * <pre>
@@ -348,7 +305,6 @@ public class NetconfMessageTransformUtil {
         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
     }
 
-
     public static Optional<RpcDefinition> findSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) {
         Preconditions.checkNotNull(rpcName);
         Preconditions.checkNotNull(schemaContext);
@@ -382,94 +338,29 @@ public class NetconfMessageTransformUtil {
         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
     }
 
-    public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
-        if (node != null) {
-            return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
-        } else {
-            return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
-        }
+    public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
+        return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(Lists.newArrayList(node)).build();
     }
 
-    public static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
-        if (node != null) {
-            return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
+    public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
+                                                                     final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+        // TODO The config element inside the EditContent should be AnyXml not Container, but AnyXml is based on outdated API
+        if(Iterables.isEmpty(dataPath.getPathArguments())) {
+            Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
+            Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
+                    "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
+            return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(
+                    wrap(NETCONF_CONFIG_QNAME, ((DataContainerChild<?, ?>) lastChildOverride.get()))).build();
         } else {
-            return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
+            return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(
+                    wrap(NETCONF_CONFIG_QNAME, (DataContainerChild<?, ?>) InstanceIdToNodes.serialize(ctx, dataPath, lastChildOverride, operation))).build();
         }
     }
 
-    static ImmutableCompositeNode filter(final String type, final Node<?> node) {
-        final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
-        it.setQName(NETCONF_FILTER_QNAME);
-        it.setAttribute(NETCONF_TYPE_QNAME, type);
-        if (node != null) {
-            return it.add(node).toInstance();
-        } else {
-            return it.toInstance();
-        }
-    }
-
-    public static Node<?> findNode(final CompositeNode node, final YangInstanceIdentifier identifier) {
-
-        Node<?> current = node;
-        for (final YangInstanceIdentifier.PathArgument arg : identifier.getPathArguments()) {
-            if (current instanceof SimpleNode<?>) {
-                return null;
-            } else if (current instanceof CompositeNode) {
-                final CompositeNode currentComposite = (CompositeNode) current;
-
-                current = currentComposite.getFirstCompositeByName(arg.getNodeType());
-                if (current == null) {
-                    current = currentComposite.getFirstCompositeByName(arg.getNodeType().withoutRevision());
-                }
-                if (current == null) {
-                    current = currentComposite.getFirstSimpleByName(arg.getNodeType());
-                }
-                if (current == null) {
-                    current = currentComposite.getFirstSimpleByName(arg.getNodeType().withoutRevision());
-                }
-                if (current == null) {
-                    return null;
-                }
-            }
-        }
-        return current;
-    }
-
-    public static String modifyOperationToXmlString(final ModifyAction operation) {
-        return operation.name().toLowerCase();
-    }
-
-
-    public static CompositeNode createEditConfigStructure(final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
-                                                    final Optional<CompositeNode> lastChildOverride) {
-        Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
-
-        List<YangInstanceIdentifier.PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
-
-        // Create deepest edit element with expected edit operation
-        CompositeNode previous = getDeepestEditElement(reversedPath.get(0), operation, lastChildOverride);
-
-        // Remove already processed deepest child
-        reversedPath = Lists.newArrayList(reversedPath);
-        reversedPath.remove(0);
-
-        // Create edit structure in reversed order
-        for (final YangInstanceIdentifier.PathArgument arg : reversedPath) {
-            final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
-            builder.setQName(arg.getNodeType());
-
-            addPredicatesToCompositeNodeBuilder(getPredicates(arg), builder);
-
-            builder.add(previous);
-            previous = builder.toInstance();
-        }
-        return ImmutableCompositeNode.create(NETCONF_CONFIG_QNAME, ImmutableList.<Node<?>>of(previous));
-    }
-
-    public static void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates, final CompositeNodeBuilder<ImmutableCompositeNode> builder) {
+    public static void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates,
+                                                           final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> builder) {
         for (final Map.Entry<QName, Object> entry : predicates.entrySet()) {
-            builder.addLeaf(entry.getKey(), entry.getValue());
+            builder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(entry.getKey())).withValue(entry.getValue()).build());
         }
     }
 
@@ -481,25 +372,11 @@ public class NetconfMessageTransformUtil {
         return predicates;
     }
 
-    public static CompositeNode getDeepestEditElement(final YangInstanceIdentifier.PathArgument arg, final Optional<ModifyAction> operation, final Optional<CompositeNode> lastChildOverride) {
-        final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
-        builder.setQName(arg.getNodeType());
-
-        final Map<QName, Object> predicates = getPredicates(arg);
-        addPredicatesToCompositeNodeBuilder(predicates, builder);
-
-        if (operation.isPresent()) {
-            builder.setAttribute(NETCONF_OPERATION_QNAME, modifyOperationToXmlString(operation.get()));
-        }
-        if (lastChildOverride.isPresent()) {
-            final List<Node<?>> children = lastChildOverride.get().getValue();
-            for(final Node<?> child : children) {
-                if(!predicates.containsKey(child.getKey())) {
-                    builder.add(child);
-                }
-            }
-        }
+    public static SchemaPath toPath(final QName rpc) {
+        return SchemaPath.create(true, rpc);
+    }
 
-        return builder.toInstance();
+    public static String modifyOperationToXmlString(final ModifyAction operation) {
+        return operation.name().toLowerCase();
     }
 }