Use switch with patterns in YangInstanceIdentifierWriter
[yangtools.git] / data / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / YangInstanceIdentifier.java
index 0559b41db352fdc9af77f5c8f11afb7172a5486d..2cc4d66aa9327eb1aaf8abbef0c5a57390705cab 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.yang.data.api;
 
-import static com.google.common.base.Preconditions.checkArgument;
 import static java.util.Objects.requireNonNull;
 
 import com.google.common.annotations.Beta;
@@ -17,13 +16,16 @@ import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
-import java.io.Serializable;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.VarHandle;
 import java.lang.reflect.Array;
 import java.util.AbstractMap.SimpleImmutableEntry;
 import java.util.Arrays;
+import java.util.Base64;
 import java.util.Collection;
 import java.util.Deque;
 import java.util.Iterator;
@@ -36,13 +38,12 @@ import java.util.Set;
 import java.util.function.Function;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.yangtools.concepts.HierarchicalIdentifier;
-import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.concepts.AbstractHierarchicalIdentifier;
+import org.opendaylight.yangtools.concepts.Identifier;
 import org.opendaylight.yangtools.concepts.Mutable;
 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
 import org.opendaylight.yangtools.util.SingletonSet;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 
 /**
@@ -68,9 +69,10 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
  *   <li>{@link NodeWithValue} - Identifier of instance {@code leaf} node or {@code leaf-list} node</li>
  * </ul>
  *
- * @see <a href="http://tools.ietf.org/html/rfc6020#section-9.13">RFC6020</a>
+ * @see <a href="http://www.rfc-editor.org/rfc/rfc6020#section-9.13">RFC6020</a>
  */
-public abstract sealed class YangInstanceIdentifier implements HierarchicalIdentifier<YangInstanceIdentifier>
+public abstract sealed class YangInstanceIdentifier
+        extends AbstractHierarchicalIdentifier<YangInstanceIdentifier, YangInstanceIdentifier.PathArgument>
         permits FixedYangInstanceIdentifier, StackedYangInstanceIdentifier {
     @java.io.Serial
     private static final long serialVersionUID = 4L;
@@ -101,11 +103,144 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * namespace.
      *
      * @return An empty YangInstanceIdentifier
+     * @deprecated Use {@link #of()} instead.
      */
-    public static @NonNull YangInstanceIdentifier empty() {
+    @Deprecated(since = "11.0.0", forRemoval = true)
+    public static final @NonNull YangInstanceIdentifier empty() {
+        return of();
+    }
+
+    /**
+     * Return an empty {@link YangInstanceIdentifier}. It corresponds to the path of the conceptual root of the YANG
+     * namespace.
+     *
+     * @return An empty YangInstanceIdentifier
+     */
+    public static final @NonNull YangInstanceIdentifier of() {
         return FixedYangInstanceIdentifier.EMPTY_INSTANCE;
     }
 
+    /**
+     * Returns a new InstanceIdentifier with only one path argument of type {@link PathArgument}.
+     *
+     * @param name QName of first node identifier
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code name} is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final PathArgument name) {
+        return new FixedYangInstanceIdentifier(ImmutableList.of(name));
+    }
+
+    /**
+     * Returns a new InstanceIdentifier composed of supplied {@link PathArgument}s.
+     *
+     * @param path Path arguments
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code path} or any of its components is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final PathArgument... path) {
+        // We are forcing a copy, since we cannot trust the user
+        return of(ImmutableList.copyOf(path));
+    }
+
+    /**
+     * Returns a new InstanceIdentifier composed of supplied {@link PathArgument}s.
+     *
+     * @param path Path arguments
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code path} is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final ImmutableList<PathArgument> path) {
+        return path.isEmpty() ? of() : new FixedYangInstanceIdentifier(path);
+    }
+
+    /**
+     * Returns a new InstanceIdentifier composed of supplied {@link PathArgument}s.
+     *
+     * @param path Path arguments
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code path} or any of its components is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final Collection<? extends PathArgument> path) {
+        return path.isEmpty() ? of() : of(ImmutableList.copyOf(path));
+    }
+
+    /**
+     * Returns a new InstanceIdentifier composed of supplied {@link PathArgument}s.
+     *
+     * @param path Path arguments
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code path} or any of its components is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final Iterable<? extends PathArgument> path) {
+        return of(ImmutableList.copyOf(path));
+    }
+
+    /**
+     * Returns a new {@link YangInstanceIdentifier} with only one path argument of type {@link NodeIdentifier} with
+     * supplied {@link QName}. Note this is a convenience method aimed at test code. Production code should consider
+     * using {@link #of(PathArgument)} instead.
+     *
+     * @param name QName of first {@link NodeIdentifier}
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code name} is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final QName name) {
+        return of(new NodeIdentifier(name));
+    }
+
+    /**
+     * Returns a new {@link YangInstanceIdentifier} with path arguments of type {@link NodeIdentifier} with
+     * supplied {@link QName}s. Note this is a convenience method aimed at test code. Production code should consider
+     * using {@link #of(PathArgument...)} instead.
+     *
+     * @param path QNames of {@link NodeIdentifier}s
+     * @return A YangInstanceIdentifier
+     * @throws NullPointerException if {@code path} or any of its components is {@code null}
+     */
+    public static final @NonNull YangInstanceIdentifier of(final QName... path) {
+        return of(Arrays.stream(path).map(NodeIdentifier::new).collect(ImmutableList.toImmutableList()));
+    }
+
+    /**
+     * Create a YangInstanceIdentifier composed of a single {@link PathArgument}.
+     *
+     * @param pathArgument Path argument
+     * @return A {@link YangInstanceIdentifier}
+     * @throws NullPointerException if {@code pathArgument} is null
+     * @deprecated Use {@link #of(NodeIdentifier)} instead.
+     */
+    @Deprecated(since = "11.0.0", forRemoval = true)
+    public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
+        return of(pathArgument);
+    }
+
+    /**
+     * Create a YangInstanceIdentifier composed of specified {@link PathArgument}s.
+     *
+     * @param path Path arguments
+     * @return A {@link YangInstanceIdentifier}
+     * @throws NullPointerException if {@code path} or any of its components is {@code null}
+     * @deprecated Use {@link #of(PathArgument...)} instead.
+     */
+    @Deprecated(since = "11.0.0", forRemoval = true)
+    public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
+        return of(path);
+    }
+
+    /**
+     * Create a YangInstanceIdentifier composed of specified {@link PathArgument}s.
+     *
+     * @param path Path arguments
+     * @return A {@link YangInstanceIdentifier}
+     * @throws NullPointerException if {@code path} or any of its components is {@code null}
+     * @deprecated Use {@link #of(Iterable)} instead.
+     */
+    @Deprecated(since = "11.0.0", forRemoval = true)
+    public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
+        return of(path);
+    }
+
     abstract @NonNull YangInstanceIdentifier createRelativeIdentifier(int skipFromRoot);
 
     abstract @Nullable List<PathArgument> tryPathArguments();
@@ -113,8 +248,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
     abstract @Nullable List<PathArgument> tryReversePathArguments();
 
     /**
-     * Check if this instance identifier has empty path arguments, e.g. it is
-     * empty and corresponds to {@link #empty()}.
+     * Check if this instance identifier has empty path arguments, e.g. it is empty and corresponds to {@link #of()}.
      *
      * @return True if this instance identifier is empty, false otherwise.
      */
@@ -132,7 +266,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * Return the conceptual parent {@link YangInstanceIdentifier}, which has
      * one item less in {@link #getPathArguments()}.
      *
-     * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #empty()}.
+     * @return Parent {@link YangInstanceIdentifier}, or null if this object is {@link #of()}.
      */
     public abstract @Nullable YangInstanceIdentifier getParent();
 
@@ -141,7 +275,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * {@link #getPathArguments()}.
      *
      * @return Parent {@link YangInstanceIdentifier}
-     * @throws VerifyException if this object is {@link #empty()}.
+     * @throws VerifyException if this object is {@link #of()}.
      */
     public abstract @NonNull YangInstanceIdentifier coerceParent();
 
@@ -177,19 +311,6 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      */
     public abstract PathArgument getLastPathArgument();
 
-    public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
-        return Iterables.isEmpty(path) ? empty() : new FixedYangInstanceIdentifier(ImmutableList.copyOf(path));
-    }
-
-    public static @NonNull YangInstanceIdentifier create(final PathArgument pathArgument) {
-        return new FixedYangInstanceIdentifier(ImmutableList.of(pathArgument));
-    }
-
-    public static @NonNull YangInstanceIdentifier create(final PathArgument... path) {
-        // We are forcing a copy, since we cannot trust the user
-        return create(Arrays.asList(path));
-    }
-
     /**
      * Create a {@link YangInstanceIdentifier} by taking a snapshot of provided path and iterating it backwards.
      *
@@ -201,7 +322,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
         final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
             pathTowardsRoot.size());
         pathTowardsRoot.descendingIterator().forEachRemaining(builder::add);
-        return YangInstanceIdentifier.create(builder.build());
+        return YangInstanceIdentifier.of(builder.build());
     }
 
     /**
@@ -214,13 +335,12 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      */
     public static <T> @NonNull YangInstanceIdentifier createReverse(final Deque<? extends T> stackTowardsRoot,
             final Function<T, PathArgument> function) {
-        final ImmutableList.Builder<PathArgument> builder = ImmutableList.builderWithExpectedSize(
-            stackTowardsRoot.size());
-        final Iterator<? extends T> it = stackTowardsRoot.descendingIterator();
+        final var builder = ImmutableList.<PathArgument>builderWithExpectedSize(stackTowardsRoot.size());
+        final var it = stackTowardsRoot.descendingIterator();
         while (it.hasNext()) {
             builder.add(function.apply(it.next()));
         }
-        return YangInstanceIdentifier.create(builder.build());
+        return YangInstanceIdentifier.of(builder.build());
     }
 
     boolean pathArgumentsEqual(final YangInstanceIdentifier other) {
@@ -263,19 +383,18 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      */
     public Optional<YangInstanceIdentifier> relativeTo(final YangInstanceIdentifier ancestor) {
         if (this == ancestor) {
-            return Optional.of(empty());
+            return Optional.of(of());
         }
         if (ancestor.isEmpty()) {
             return Optional.of(this);
         }
 
-        final Iterator<PathArgument> lit = getPathArguments().iterator();
-        final Iterator<PathArgument> oit = ancestor.getPathArguments().iterator();
+        final var lit = getPathArguments().iterator();
         int common = 0;
 
-        while (oit.hasNext()) {
+        for (var element : ancestor.getPathArguments()) {
             // Ancestor is not really an ancestor
-            if (!lit.hasNext() || !lit.next().equals(oit.next())) {
+            if (!lit.hasNext() || !lit.next().equals(element)) {
                 return Optional.empty();
             }
 
@@ -286,33 +405,35 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
             return Optional.of(this);
         }
         if (!lit.hasNext()) {
-            return Optional.of(empty());
+            return Optional.of(of());
         }
 
         return Optional.of(createRelativeIdentifier(common));
     }
 
     @Override
-    public final boolean contains(final YangInstanceIdentifier other) {
-        if (this == other) {
-            return true;
-        }
+    protected final Iterator<PathArgument> itemIterator() {
+        return getPathArguments().iterator();
+    }
 
-        checkArgument(other != null, "other should not be null");
-        final Iterator<PathArgument> lit = getPathArguments().iterator();
-        final Iterator<PathArgument> oit = other.getPathArguments().iterator();
+    @Override
+    protected final Object writeReplace() {
+        return new YIDv1(this);
+    }
 
-        while (lit.hasNext()) {
-            if (!oit.hasNext()) {
-                return false;
-            }
+    @java.io.Serial
+    private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+        throwNSE();
+    }
 
-            if (!lit.next().equals(oit.next())) {
-                return false;
-            }
-        }
+    @java.io.Serial
+    private void readObjectNoData() throws ObjectStreamException {
+        throwNSE();
+    }
 
-        return true;
+    @java.io.Serial
+    private void writeObject(final ObjectOutputStream stream) throws IOException {
+        throwNSE();
     }
 
     @Override
@@ -326,7 +447,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
          * The cache is thread-safe - if multiple computations occurs at the
          * same time, cache will be overwritten with same result.
          */
-        final String ret = (String) TO_STRING_CACHE.getAcquire(this);
+        final var ret = (String) TO_STRING_CACHE.getAcquire(this);
         return ret != null ? ret : loadToString();
     }
 
@@ -364,8 +485,8 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
             return 0;
         }
 
-        if (byte[].class.equals(value.getClass())) {
-            return Arrays.hashCode((byte[]) value);
+        if (value instanceof byte[] bytes) {
+            return Arrays.hashCode(bytes);
         }
 
         if (value.getClass().isArray()) {
@@ -378,7 +499,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
             return hash;
         }
 
-        return Objects.hashCode(value);
+        return value.hashCode();
     }
 
     private int loadHashCode() {
@@ -389,24 +510,6 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
 
     abstract int computeHashCode();
 
-    @java.io.Serial
-    final Object writeReplace() {
-        return new YIDv1(this);
-    }
-
-    // Static factories & helpers
-
-    /**
-     * Returns a new InstanceIdentifier with only one path argument of type {@link NodeIdentifier} with supplied
-     * QName.
-     *
-     * @param name QName of first node identifier
-     * @return Instance Identifier with only one path argument of type {@link NodeIdentifier}
-     */
-    public static @NonNull YangInstanceIdentifier of(final QName name) {
-        return create(new NodeIdentifier(name));
-    }
-
     /**
      * Returns new builder for InstanceIdentifier with empty path arguments.
      *
@@ -447,15 +550,25 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * <li>{@link NodeWithValue} - Identifier of leaf-list entry
      * </ul>
      */
-    public sealed interface PathArgument extends Comparable<PathArgument>, Immutable, Serializable
-            permits AbstractPathArgument {
+    public abstract static sealed class PathArgument implements Identifier, Comparable<PathArgument> {
+        @java.io.Serial
+        private static final long serialVersionUID = -4546547994250849340L;
+
+        private final @NonNull QName nodeType;
+        private transient volatile int hashValue;
+
+        protected PathArgument(final QName nodeType) {
+            this.nodeType = requireNonNull(nodeType);
+        }
+
         /**
          * Returns unique QName of data node as defined in YANG Schema, if available.
          *
          * @return Node type
-         * @throws UnsupportedOperationException if node type is not applicable, for example in case of an augmentation.
          */
-        @NonNull QName getNodeType();
+        public final @NonNull QName getNodeType() {
+            return nodeType;
+        }
 
         /**
          * Return the string representation of this object for use in context
@@ -466,27 +579,17 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
          * @param previous Previous path argument
          * @return String representation
          */
-        @NonNull String toRelativeString(PathArgument previous);
-    }
-
-    private abstract static sealed class AbstractPathArgument implements PathArgument {
-        private static final long serialVersionUID = -4546547994250849340L;
-        private final @NonNull QName nodeType;
-        private transient volatile int hashValue;
-
-        protected AbstractPathArgument(final QName nodeType) {
-            this.nodeType = requireNonNull(nodeType);
-        }
-
-        @Override
-        public final QName getNodeType() {
-            return nodeType;
+        public @NonNull String toRelativeString(final PathArgument previous) {
+            if (previous != null && nodeType.getModule().equals(previous.nodeType.getModule())) {
+                return nodeType.getLocalName();
+            }
+            return nodeType.toString();
         }
 
         @Override
         @SuppressWarnings("checkstyle:parameterName")
         public int compareTo(final PathArgument o) {
-            return nodeType.compareTo(o.getNodeType());
+            return nodeType.compareTo(o.nodeType);
         }
 
         protected int hashCodeImpl() {
@@ -508,26 +611,15 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
                 return false;
             }
 
-            return getNodeType().equals(((AbstractPathArgument)obj).getNodeType());
+            return nodeType.equals(((PathArgument) obj).nodeType);
         }
 
         @Override
         public String toString() {
-            return getNodeType().toString();
-        }
-
-        @Override
-        public String toRelativeString(final PathArgument previous) {
-            if (previous instanceof AbstractPathArgument) {
-                final QNameModule mod = previous.getNodeType().getModule();
-                if (getNodeType().getModule().equals(mod)) {
-                    return getNodeType().getLocalName();
-                }
-            }
-
-            return getNodeType().toString();
+            return nodeType.toString();
         }
 
+        @java.io.Serial
         abstract Object writeReplace();
     }
 
@@ -535,7 +627,8 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * Simple path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.ContainerNode} or
      * {@link org.opendaylight.yangtools.yang.data.api.schema.LeafNode} leaf in particular subtree.
      */
-    public static final class NodeIdentifier extends AbstractPathArgument {
+    public static final class NodeIdentifier extends PathArgument {
+        @java.io.Serial
         private static final long serialVersionUID = -2255888212390871347L;
         private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
                 .build(new CacheLoader<QName, NodeIdentifier>() {
@@ -570,9 +663,10 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * Composite path argument identifying a {@link org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode} leaf
      * overall data tree.
      */
-    public abstract static sealed class NodeIdentifierWithPredicates extends AbstractPathArgument {
+    public abstract static sealed class NodeIdentifierWithPredicates extends PathArgument {
         @Beta
         public static final class Singleton extends NodeIdentifierWithPredicates {
+            @java.io.Serial
             private static final long serialVersionUID = 1L;
 
             private final @NonNull QName key;
@@ -637,6 +731,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
         }
 
         private static final class Regular extends NodeIdentifierWithPredicates {
+            @java.io.Serial
             private static final long serialVersionUID = 1L;
 
             private final @NonNull Map<QName, Object> keyValues;
@@ -703,6 +798,7 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
             }
         }
 
+        @java.io.Serial
         private static final long serialVersionUID = -4787195606494761540L;
 
         NodeIdentifierWithPredicates(final QName node) {
@@ -830,7 +926,8 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
      * Simple path argument identifying a {@link LeafSetEntryNode} leaf
      * overall data tree.
      */
-    public static final class NodeWithValue<T> extends AbstractPathArgument {
+    public static final class NodeWithValue<T> extends PathArgument {
+        @java.io.Serial
         private static final long serialVersionUID = -3637456085341738431L;
 
         private final @NonNull T value;
@@ -852,16 +949,14 @@ public abstract sealed class YangInstanceIdentifier implements HierarchicalIdent
         @Override
         @SuppressWarnings("checkstyle:equalsHashCode")
         public boolean equals(final Object obj) {
-            if (!super.equals(obj)) {
-                return false;
-            }
-            final NodeWithValue<?> other = (NodeWithValue<?>) obj;
-            return Objects.deepEquals(value, other.value);
+            return super.equals(obj) && Objects.deepEquals(value, ((NodeWithValue<?>) obj).value);
         }
 
         @Override
         public String toString() {
-            return super.toString() + '[' + value + ']';
+            final var str = super.toString();
+            return value instanceof byte[] bytes ? str + "[b64:" + Base64.getEncoder().encodeToString(bytes) + ']'
+                : str + '[' + value + ']';
         }
 
         @Override