Eliminate XmlUtil.createElement() et al.
[netconf.git] / plugins / netconf-client-mdsal / src / main / java / org / opendaylight / netconf / client / mdsal / impl / NetconfMessageTransformUtil.java
index 887cc196c962b6602f6eb93d92d7c3d8986e89b9..16e915e3aa5d63638fc8be29d1b9739912671016 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.netconf.client.mdsal.impl;
 
+import static java.util.Objects.requireNonNull;
 import static org.opendaylight.netconf.common.mdsal.NormalizedDataUtil.NETCONF_DATA_QNAME;
 import static org.opendaylight.netconf.common.mdsal.NormalizedDataUtil.NETCONF_QNAME;
 
@@ -17,10 +18,8 @@ import java.time.Instant;
 import java.time.format.DateTimeParseException;
 import java.util.ArrayDeque;
 import java.util.Collection;
-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;
@@ -32,8 +31,11 @@ import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
 import org.opendaylight.netconf.api.DocumentedException;
 import org.opendaylight.netconf.api.EffectiveOperation;
-import org.opendaylight.netconf.api.NetconfMessage;
+import org.opendaylight.netconf.api.NamespaceURN;
+import org.opendaylight.netconf.api.messages.NetconfMessage;
 import org.opendaylight.netconf.api.messages.NotificationMessage;
+import org.opendaylight.netconf.api.messages.RpcMessage;
+import org.opendaylight.netconf.api.messages.RpcReplyMessage;
 import org.opendaylight.netconf.api.xml.XmlElement;
 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.netconf.api.xml.XmlUtil;
@@ -42,9 +44,6 @@ 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.XMLNamespace;
 import org.opendaylight.yangtools.yang.common.YangConstants;
@@ -57,16 +56,19 @@ import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedMetadata;
 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.api.schema.stream.NormalizedNodeWriter;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.YangInstanceIdentifierWriter;
 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedMetadata;
 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.NormalizationResultHolder;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
-import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContext.PathMixin;
 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
@@ -83,15 +85,9 @@ public final class NetconfMessageTransformUtil {
 
     public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
             QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
-    private static final String SUBTREE = "subtree";
 
     // Blank document used for creation of new DOM nodes
     private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
-    public static final String EVENT_TIME = "eventTime";
-
-    private NetconfMessageTransformUtil() {
-
-    }
 
     public static final @NonNull QName IETF_NETCONF_MONITORING =
             QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
@@ -115,11 +111,12 @@ public final class NetconfMessageTransformUtil {
 
     public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
 
-    public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
+    public static final @NonNull QName NETCONF_RPC_REPLY_QNAME =
+        QName.create(NETCONF_QNAME, RpcReplyMessage.ELEMENT_NAME).intern();
     public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
         NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
 
-    public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
+    public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, XmlNetconfConstants.OK).intern();
     public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
         QName.create(NETCONF_QNAME, "error-option").intern();
     public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
@@ -157,18 +154,19 @@ public final class NetconfMessageTransformUtil {
     public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
         NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
     public static final @NonNull Absolute NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
-    public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
+    public static final @NonNull QName NETCONF_GET_CONFIG_QNAME =
+        QName.create(NETCONF_QNAME, XmlNetconfConstants.GET_CONFIG).intern();
     public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
         NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
     public static final @NonNull Absolute NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
     public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
     public static final @NonNull Absolute NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
-    public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
-    public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
-    public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
+    public static final @NonNull QName NETCONF_GET_QNAME =
+        QName.create(NETCONF_QNAME, XmlNetconfConstants.GET).intern();
     public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
     public static final @NonNull Absolute NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
-    public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
+    public static final @NonNull QName NETCONF_RPC_QNAME =
+        QName.create(NETCONF_QNAME, RpcMessage.ELEMENT_NAME).intern();
 
     public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
     public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
@@ -197,9 +195,14 @@ public final class NetconfMessageTransformUtil {
 
     public static final @NonNull Absolute CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
 
-    public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
+    public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID =
+        NodeIdentifier.create(QName.create(NETCONF_QNAME, "filter").intern());
+
+    public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(newFilterElement());
 
-    public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(getNetconfFilterElement());
+    private NetconfMessageTransformUtil() {
+        // Hidden on purpose
+    }
 
     /**
      * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
@@ -210,7 +213,7 @@ public final class NetconfMessageTransformUtil {
      */
     public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
                                                        final EffectiveModelContext ctx) {
-        final Element element = getNetconfFilterElement();
+        final Element element = newFilterElement();
         try {
             NormalizedDataUtil.writeFilter(identifier, new DOMResult(element), ctx, null);
         } catch (IOException | XMLStreamException e) {
@@ -230,7 +233,7 @@ public final class NetconfMessageTransformUtil {
     public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
                                                   final EffectiveModelContext ctx) {
         Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
-        final Element element = getNetconfFilterElement();
+        final Element element = newFilterElement();
 
         for (final FieldsFilter filter : fieldsFilters) {
             try {
@@ -244,11 +247,9 @@ public final class NetconfMessageTransformUtil {
         return buildFilterStructure(element);
     }
 
-    private static Element getNetconfFilterElement() {
-        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);
+    private static Element newFilterElement() {
+        final var element = BLANK_DOCUMENT.createElementNS(NamespaceURN.BASE, "filter");
+        element.setAttribute("type", "subtree");
         return element;
     }
 
@@ -306,8 +307,8 @@ public final class NetconfMessageTransformUtil {
                     + "but was: %s", override);
         }
 
-        final var element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
-                Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
+        final var element = BLANK_DOCUMENT.createElementNS(NETCONF_CONFIG_QNAME.getNamespace().toString(),
+            NETCONF_CONFIG_QNAME.getLocalName());
         final var metadata = operation.map(o -> leafMetadata(dataPath, o)).orElse(null);
         try {
             if (lastChildOverride.isPresent()) {
@@ -315,14 +316,15 @@ public final class NetconfMessageTransformUtil {
                 // into xml
 
                 final var parentPath = dataPath.isEmpty() ? dataPath : dataPath.coerceParent();
-                var result = new NormalizedNodeResult();
+                var result = new NormalizationResultHolder();
                 try (var streamWriter = ImmutableNormalizedNodeStreamWriter.from(result)) {
                     try (var iidWriter = YangInstanceIdentifierWriter.open(streamWriter, ctx, parentPath);
                          var nnWriter = NormalizedNodeWriter.forStreamWriter(streamWriter)) {
                         nnWriter.write(lastChildOverride.orElseThrow());
                     }
                 }
-                NormalizedDataUtil.writeNormalizedNode(result.getResult(), metadata, new DOMResult(element), ctx, null);
+                NormalizedDataUtil.writeNormalizedNode(result.getResult().data(), metadata, new DOMResult(element), ctx,
+                    null);
             } else {
                 NormalizedDataUtil.writeNormalizedNode(dataPath, metadata, new DOMResult(element), ctx, null);
             }
@@ -335,23 +337,31 @@ public final class NetconfMessageTransformUtil {
     }
 
     private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final EffectiveOperation oper) {
-        final List<PathArgument> args = path.getPathArguments();
-        final Deque<Builder> builders = new ArrayDeque<>(args.size());
+        record BuilderAndArg(ImmutableNormalizedMetadata.Builder builder, PathArgument arg) {
+            BuilderAndArg {
+                requireNonNull(builder);
+                requireNonNull(arg);
+            }
+        }
+
+        final var args = path.getPathArguments();
+        final var builders = new ArrayDeque<BuilderAndArg>(args.size());
 
         // Step one: open builders
         for (PathArgument arg : args) {
-            builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
+            builders.push(new BuilderAndArg(ImmutableNormalizedMetadata.builder(), arg));
         }
 
         // Step two: set the top builder's metadata
-        builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
+        builders.peek().builder.withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.xmlValue());
 
         // Step three: build the tree
         while (true) {
-            final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
-            final Builder parent = builders.peek();
+            final var current = builders.pop();
+            final var currentMeta = current.builder.build();
+            final var parent = builders.peek();
             if (parent != null) {
-                parent.withChild(currentMeta);
+                parent.builder.withChild(current.arg, currentMeta);
             } else {
                 return currentMeta;
             }
@@ -378,14 +388,15 @@ public final class NetconfMessageTransformUtil {
         final XmlElement eventTimeElement;
         final XmlElement notificationElement;
 
-        if (childElements.get(0).getName().equals(EVENT_TIME)) {
+        if (childElements.get(0).getName().equals(XmlNetconfConstants.EVENT_TIME)) {
             eventTimeElement = childElements.get(0);
             notificationElement = childElements.get(1);
-        } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
+        } else if (childElements.get(1).getName().equals(XmlNetconfConstants.EVENT_TIME)) {
             eventTimeElement = childElements.get(1);
             notificationElement = childElements.get(0);
         } else {
-            throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
+            throw new IllegalArgumentException(
+                "Notification payload does not contain " + XmlNetconfConstants.EVENT_TIME + " " + message);
         }
 
         try {
@@ -393,8 +404,8 @@ public final class NetconfMessageTransformUtil {
                     NotificationMessage.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
                     notificationElement);
         } catch (final DocumentedException e) {
-            throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
-                    e);
+            throw new IllegalArgumentException(
+                "Notification payload does not contain " + XmlNetconfConstants.EVENT_TIME + " " + message, e);
         } catch (final DateTimeParseException e) {
             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
                 NotificationMessage.UNKNOWN_EVENT_TIME, e);
@@ -423,7 +434,7 @@ public final class NetconfMessageTransformUtil {
         rpcNS.setAttribute(XmlNetconfConstants.MESSAGE_ID, counter.getNewMessageId(MESSAGE_ID_PREFIX));
 
         final Element actionNS = document.createElementNS(YangConstants.RFC6020_YANG_NAMESPACE_STRING, "action");
-        final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
+        final DataSchemaContext rootSchemaContextNode = dataSchemaContextTree.getRoot();
         final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
                 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
 
@@ -435,15 +446,16 @@ public final class NetconfMessageTransformUtil {
         return new DOMResult(specificActionElement);
     }
 
-    private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
+    private static Element prepareActionData(final DataSchemaContext currentParentSchemaNode,
             final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
         if (iterator.hasNext()) {
             final PathArgument next = iterator.next();
 
-            final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
+            final DataSchemaContext current = currentParentSchemaNode instanceof DataSchemaContext.Composite composite
+                ? composite.childByArg(next) : null;
             Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
 
-            if (current.isMixin()) {
+            if (current instanceof PathMixin) {
                 return prepareActionData(current, actionNS, iterator, document);
             }