Revert "Convert anyxml nodes lazily"
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / util / NetconfMessageTransformUtil.java
index ea7abe2f74291eec22fa1848dc6575c700634407..8283d3f966fb59187a77e69bd2fb71495583607a 100644 (file)
@@ -7,20 +7,23 @@
  */
 package org.opendaylight.netconf.sal.connect.netconf.util;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import java.io.IOException;
 import java.net.URI;
+import java.time.Instant;
 import java.time.format.DateTimeParseException;
-import java.util.AbstractMap;
+import java.util.AbstractMap.SimpleEntry;
+import java.util.ArrayDeque;
 import java.util.Collection;
-import java.util.Date;
+import java.util.Deque;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.Optional;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
 import javax.xml.transform.dom.DOMResult;
@@ -28,6 +31,7 @@ import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
 import org.opendaylight.netconf.api.DocumentedException;
 import org.opendaylight.netconf.api.FailedNetconfMessage;
+import org.opendaylight.netconf.api.ModifyAction;
 import org.opendaylight.netconf.api.NetconfDocumentedException;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.api.xml.XmlElement;
@@ -40,12 +44,14 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.re
 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;
+import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
+import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
+import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
 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.RpcResult;
 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
@@ -60,7 +66,8 @@ import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStr
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@@ -113,6 +120,8 @@ public final class NetconfMessageTransformUtil {
     public static final NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
 
     public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
+    public static final NodeIdentifier NETCONF_RPC_REPLY_NODEID = NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
+
     public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
     public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
     public static final NodeIdentifier NETCONF_ERROR_OPTION_NODEID = NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
@@ -126,24 +135,33 @@ public final class NetconfMessageTransformUtil {
     public static final NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
 
     public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
+    public static final SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
     public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
     public static final NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
+    public static final SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
     public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
     public static final NodeIdentifier NETCONF_COPY_CONFIG_NODEID = NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
+    public static final SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
 
     public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
+    private static final QName NETCONF_OPERATION_QNAME_LEGACY = NETCONF_OPERATION_QNAME.withoutRevision().intern();
     public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
             QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
     public static final NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
             NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
     public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
     public static final NodeIdentifier NETCONF_EDIT_CONFIG_NODEID = NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
+    public static final SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
     public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
+    public static final NodeIdentifier NETCONF_GET_CONFIG_NODEID = NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
+    public static final SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
     public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
+    public static final SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
     public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
     public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
     public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
     public static final NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
+    public static final SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
     public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
     public static final QName YANG_QNAME = null;
     public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
@@ -164,8 +182,10 @@ public final class NetconfMessageTransformUtil {
 
     public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
     public static final NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
+    public static final SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
     public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
     public static final NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
+    public static final SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
 
     public static final NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
 
@@ -179,51 +199,41 @@ public final class NetconfMessageTransformUtil {
 
     // Get message
     public static final ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
-            .withNodeIdentifier(NodeIdentifier.create(NETCONF_GET_QNAME)).build();
+            .withNodeIdentifier(NETCONF_GET_NODEID).build();
 
     // Create-subscription changes message
     public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
             .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
 
-    private static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
-    private static final Map<QName, String> SUBTREE_FILTER_ATTRIBUTES = ImmutableMap.of(NETCONF_TYPE_QNAME, SUBTREE);
+    public static final NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
 
     public static final DataContainerChild<?, ?> EMPTY_FILTER;
 
     static {
-        final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
-                Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
-                .withAttributes(SUBTREE_FILTER_ATTRIBUTES);
-
         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
-                NETCONF_TYPE_QNAME.getLocalName(), "subtree");
-
-        anyXmlBuilder.withValue(new DOMSource(element));
+                NETCONF_TYPE_QNAME.getLocalName(), SUBTREE);
 
-        EMPTY_FILTER = anyXmlBuilder.build();
+        EMPTY_FILTER = Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID)
+                .withValue(new DOMSource(element)).build();
     }
 
     public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
                                                              final SchemaContext ctx) {
-        final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder()
-                .withNodeIdentifier(NETCONF_FILTER_NODEID).withAttributes(SUBTREE_FILTER_ATTRIBUTES);
-        final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
-
         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
-                "subtree");
+                SUBTREE);
 
         try {
-            NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
+            NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
         } catch (IOException | XMLStreamException e) {
             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
         }
-        anyXmlBuilder.withValue(new DOMSource(element));
 
-        return anyXmlBuilder.build();
+        return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_FILTER_NODEID).withValue(new DOMSource(element))
+                .build();
     }
 
     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
@@ -318,15 +328,21 @@ public final class NetconfMessageTransformUtil {
         return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
     }
 
+    @Deprecated
     public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
-        return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
+        return wrap(toId(name), node);
+    }
+
+    public static ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
+        return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
     }
 
     public static AnyXmlNode createEditConfigAnyxml(
-            final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+            final SchemaContext ctx, final YangInstanceIdentifier dataPath,
+            final Optional<ModifyAction> operation,
             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
         final NormalizedNode<?, ?> configContent;
-
+        final NormalizedMetadata metadata;
         if (dataPath.isEmpty()) {
             Preconditions.checkArgument(lastChildOverride.isPresent(),
                     "Data has to be present when creating structure for top level element");
@@ -334,17 +350,17 @@ public final class NetconfMessageTransformUtil {
                     "Data has to be either container or a list node when creating structure for top level element, "
                             + "but was: %s", lastChildOverride.get());
             configContent = lastChildOverride.get();
+            metadata = null;
         } else {
-            final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
-                    ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
-            configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride.toJavaUtil(),
-                java.util.Optional.ofNullable(modifyOperation));
+            configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
+            metadata = operation.map(oper -> leafMetadata(dataPath, oper)).orElse(null);
         }
 
         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
                 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
+
         try {
-            NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
+            NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
         } catch (IOException | XMLStreamException e) {
             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
         }
@@ -353,18 +369,42 @@ public final class NetconfMessageTransformUtil {
                 .build();
     }
 
-    public static DataContainerChild<?, ?> createEditConfigStructure(
-            final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+    private static NormalizedMetadata leafMetadata(YangInstanceIdentifier path, final ModifyAction oper) {
+        final List<PathArgument> args = path.getPathArguments();
+        final Deque<Builder> builders = new ArrayDeque<>(args.size());
+
+        // Step one: open builders
+        for (PathArgument arg : args) {
+            builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
+        }
+
+        // Step two: set the top builder's metadata
+        builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
+
+        // Step three: build the tree
+        while (true) {
+            final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
+            final Builder parent = builders.peek();
+            if (parent != null) {
+                parent.withChild(currentMeta);
+            } else {
+                return currentMeta;
+            }
+        }
+    }
+
+    public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx,
+            final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
         return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
                 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
     }
 
     public static SchemaPath toPath(final QName rpc) {
-        return SchemaPath.create(true, rpc);
+        return SchemaPath.ROOT.createChild(rpc);
     }
 
-    public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
+    public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
         final List<XmlElement> childElements = xmlElement.getChildElements();
         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
@@ -384,8 +424,8 @@ public final class NetconfMessageTransformUtil {
         }
 
         try {
-            return new AbstractMap.SimpleEntry<>(
-                    NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
+            return new SimpleEntry<>(
+                    NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
                     notificationElement);
         } catch (final DocumentedException e) {
             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
@@ -393,7 +433,8 @@ public final class NetconfMessageTransformUtil {
         } catch (final DateTimeParseException e) {
             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
                     NetconfNotification.UNKNOWN_EVENT_TIME, e);
-            return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
+            return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
+                    notificationElement);
         }
     }
 
@@ -409,8 +450,9 @@ public final class NetconfMessageTransformUtil {
         return new DOMResult(elementNS);
     }
 
-    public static DOMResult prepareDomResultForActionRequest(DOMDataTreeIdentifier domDataTreeIdentifier,
-            final SchemaPath actionSchemaPath, final MessageCounter counter, String action) {
+    public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
+            final DOMDataTreeIdentifier domDataTreeIdentifier, final SchemaPath actionSchemaPath,
+            final MessageCounter counter, final String action) {
         final Document document = XmlUtil.newDocument();
         final Element rpcNS =
                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
@@ -418,8 +460,8 @@ public final class NetconfMessageTransformUtil {
         rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
 
         final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
-
-        final Element actionData = prepareActionData(actionNS,
+        final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
+        final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
                 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
 
         Element specificActionElement = document.createElement(action);
@@ -429,11 +471,19 @@ public final class NetconfMessageTransformUtil {
         return new DOMResult(specificActionElement);
     }
 
-    private static Element prepareActionData(Element actionNS, Iterator<PathArgument> iterator, Document document) {
+    private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
+            final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
         if (iterator.hasNext()) {
-            PathArgument next = iterator.next();
-            final QName actualNS = next.getNodeType();
+            final PathArgument next = iterator.next();
+
+            DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
+            Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
 
+            if (current.isMixin()) {
+                return prepareActionData(current, actionNS, iterator, document);
+            }
+
+            final QName actualNS = next.getNodeType();
             final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
                     actualNS.getLocalName());
             if (next instanceof NodeWithValue) {
@@ -448,7 +498,7 @@ public final class NetconfMessageTransformUtil {
                 }
             }
             actionNS.appendChild(actualElement);
-            return prepareActionData(actualElement, iterator, document);
+            return prepareActionData(current, actualElement, iterator, document);
         } else {
             return actionNS;
         }