Add SchemaPath->SchemaNodeIdentifier conversions
[yangtools.git] / yang / yang-model-api / src / main / java / org / opendaylight / yangtools / yang / model / api / SchemaPath.java
index 1669e0816f82b79b102df64348bbefc31a791b92..267e9786e4cd515d221074e051293b3b01955908 100644 (file)
  */
 package org.opendaylight.yangtools.yang.model.api;
 
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.opendaylight.yangtools.yang.common.QName;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
 
-import com.google.common.base.Preconditions;
+import com.google.common.base.MoreObjects;
+import com.google.common.base.MoreObjects.ToStringHelper;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
+import com.google.common.collect.UnmodifiableIterator;
+import java.util.Arrays;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
+import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
 
 /**
- *
  * Represents unique path to the every node inside the module.
- *
  */
-public class SchemaPath {
+public abstract class SchemaPath implements Immutable {
+
+    /**
+     * An absolute SchemaPath.
+     */
+    private static final class AbsoluteSchemaPath extends SchemaPath {
+        private AbsoluteSchemaPath(final SchemaPath parent, final QName qname) {
+            super(parent, qname);
+        }
+
+        @Override
+        public boolean isAbsolute() {
+            return true;
+        }
+
+        @Override
+        public AbsoluteSchemaPath createChild(final QName element) {
+            return new AbsoluteSchemaPath(this, requireNonNull(element));
+        }
+    }
+
+    /**
+     * A relative SchemaPath.
+     */
+    private static final class RelativeSchemaPath extends SchemaPath {
+        private RelativeSchemaPath(final SchemaPath parent, final QName qname) {
+            super(parent, qname);
+        }
+
+        @Override
+        public boolean isAbsolute() {
+            return false;
+        }
+
+        @Override
+        public RelativeSchemaPath createChild(final QName element) {
+            return new RelativeSchemaPath(this, requireNonNull(element));
+        }
+    }
+
     /**
      * Shared instance of the conceptual root schema node.
      */
-    public static final SchemaPath ROOT = SchemaPath.create(Collections.<QName>emptyList(), true);
+    public static final @NonNull SchemaPath ROOT = new AbsoluteSchemaPath(null, null);
 
     /**
      * Shared instance of the "same" relative schema node.
      */
-    public static final SchemaPath SAME = SchemaPath.create(Collections.<QName>emptyList(), false);
+    public static final @NonNull SchemaPath SAME = new RelativeSchemaPath(null, null);
 
     /**
-     * List of QName instances which represents complete path to the node.
+     * Parent path.
      */
-    private final ImmutableList<QName> path;
+    private final SchemaPath parent;
 
     /**
-     * Boolean value which represents type of schema path (relative or
-     * absolute).
+     * This component.
      */
-    private final Boolean absolute;
+    private final QName qname;
+
+    /**
+     * Cached hash code. We can use this since we are immutable.
+     */
+    private final int hash;
+
+    SchemaPath(final SchemaPath parent, final QName qname) {
+        this.parent = parent;
+        this.qname = qname;
+
+        int tmp = Objects.hashCode(parent);
+        if (qname != null) {
+            tmp = tmp * 31 + qname.hashCode();
+        }
+
+        hash = tmp;
+    }
 
     /**
      * Constructs new instance of this class with the concrete path.
@@ -54,49 +117,26 @@ public class SchemaPath {
      *            boolean value which specifies if the path is absolute or
      *            relative
      *
-     * @deprecated Use {@link #create(Iterable, boolean)} instead.
-     */
-    @Deprecated
-    public SchemaPath(final List<QName> path, final boolean absolute) {
-        this(ImmutableList.copyOf(path), absolute, null);
-    }
-
-    /**
-     * Returns the complete path to schema node.
-     *
-     * @return list of <code>QName</code> instances which represents complete
-     *         path to schema node
-     *
-     * @deprecated Use {@link #getPathFromRoot()} instead.
+     * @return A SchemaPath instance.
      */
-    @Deprecated
-    public List<QName> getPath() {
-        return path;
-    }
-
-    private SchemaPath(final ImmutableList<QName> path, final boolean absolute, final Void dummy) {
-        this.path = Preconditions.checkNotNull(path);
-        this.absolute = absolute;
+    public static @NonNull SchemaPath create(final Iterable<QName> path, final boolean absolute) {
+        return (absolute ? ROOT : SAME).createChild(path);
     }
 
     /**
      * Constructs new instance of this class with the concrete path.
      *
-     * @param path
-     *            list of QName instances which specifies exact path to the
-     *            module node
      * @param absolute
      *            boolean value which specifies if the path is absolute or
      *            relative
+     * @param element
+     *            a single QName which specifies exact path to the
+     *            module node
      *
      * @return A SchemaPath instance.
      */
-    public static SchemaPath create(final Iterable<QName> path, final boolean absolute) {
-        if (Iterables.isEmpty(path)) {
-            return absolute ? ROOT : SAME;
-        } else {
-            return new SchemaPath(ImmutableList.copyOf(path), absolute, null);
-        }
+    public static @NonNull SchemaPath create(final boolean absolute, final QName element) {
+        return (absolute ? ROOT : SAME).createChild(element);
     }
 
     /**
@@ -111,8 +151,8 @@ public class SchemaPath {
      *
      * @return A SchemaPath instance.
      */
-    public static SchemaPath create(final boolean absolute, final QName... path) {
-       return create(Arrays.asList(path), absolute);
+    public static @NonNull SchemaPath create(final boolean absolute, final QName... path) {
+        return create(Arrays.asList(path), absolute);
     }
 
     /**
@@ -121,11 +161,17 @@ public class SchemaPath {
      * @param relative Relative path
      * @return A new child path
      */
-    public SchemaPath createChild(final Iterable<QName> relative) {
+    public @NonNull SchemaPath createChild(final Iterable<QName> relative) {
         if (Iterables.isEmpty(relative)) {
             return this;
         }
-        return create(Iterables.concat(path, relative), absolute);
+
+        SchemaPath parentPath = this;
+        for (QName item : relative) {
+            parentPath = parentPath.createChild(item);
+        }
+
+        return parentPath;
     }
 
     /**
@@ -134,11 +180,19 @@ public class SchemaPath {
      * @param relative Relative SchemaPath
      * @return A new child path
      */
-    public SchemaPath createChild(final SchemaPath relative) {
-        Preconditions.checkArgument(!relative.isAbsolute(), "Child creation requires relative path");
-        return createChild(relative.path);
+    public @NonNull SchemaPath createChild(final SchemaPath relative) {
+        checkArgument(!relative.isAbsolute(), "Child creation requires relative path");
+        return createChild(relative.getPathFromRoot());
     }
 
+    /**
+     * Create a child path based on concatenation of this path and an additional path element.
+     *
+     * @param element Relative SchemaPath elements
+     * @return A new child path
+     */
+    public abstract @NonNull SchemaPath createChild(QName element);
+
     /**
      * Create a child path based on concatenation of this path and additional
      * path elements.
@@ -146,7 +200,7 @@ public class SchemaPath {
      * @param elements Relative SchemaPath elements
      * @return A new child path
      */
-    public SchemaPath createChild(final QName... elements) {
+    public @NonNull SchemaPath createChild(final QName... elements) {
         return createChild(Arrays.asList(elements));
     }
 
@@ -158,8 +212,11 @@ public class SchemaPath {
      * @return list of <code>qname</code> instances which represents
      *         path from the root to the schema node.
      */
-    public Iterable<QName> getPathFromRoot() {
-        return path;
+    public List<QName> getPathFromRoot() {
+        if (qname == null) {
+            return ImmutableList.of();
+        }
+        return parent == null ? ImmutableList.of(qname) : new PathFromRoot(this);
     }
 
     /**
@@ -170,7 +227,43 @@ public class SchemaPath {
      *         path from the schema node towards the root.
      */
     public Iterable<QName> getPathTowardsRoot() {
-        return path.reverse();
+        return () -> new UnmodifiableIterator<>() {
+            private SchemaPath current = SchemaPath.this;
+
+            @Override
+            public boolean hasNext() {
+                return current.parent != null;
+            }
+
+            @Override
+            public QName next() {
+                if (current.parent != null) {
+                    final QName ret = current.qname;
+                    current = current.parent;
+                    return ret;
+                }
+
+                throw new NoSuchElementException("No more elements available");
+            }
+        };
+    }
+
+    /**
+     * Returns the immediate parent SchemaPath.
+     *
+     * @return Parent path, null if this SchemaPath is already toplevel.
+     */
+    public SchemaPath getParent() {
+        return parent;
+    }
+
+    /**
+     * Get the last component of this path.
+     *
+     * @return The last component of this path.
+     */
+    public final QName getLastComponent() {
+        return qname;
     }
 
     /**
@@ -179,19 +272,51 @@ public class SchemaPath {
      * @return boolean value which is <code>true</code> if schema path is
      *         absolute.
      */
-    public boolean isAbsolute() {
-        return absolute;
+    public abstract boolean isAbsolute();
+
+    /**
+     * Return this path as a {@link SchemaNodeIdentifier}.
+     *
+     * @return A SchemaNodeIdentifier.
+     * @throws IllegalStateException if this path is empty
+     */
+    public final SchemaNodeIdentifier asSchemaNodeIdentifier() {
+        checkState(qname != null, "Cannot convert empty %s", this);
+        final List<QName> path = getPathFromRoot();
+        return isAbsolute() ? Absolute.of(path) : Descendant.of(path);
     }
 
-    @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + absolute.hashCode();
-        for (Object o : path) {
-            result = prime * result + o.hashCode();
+    /**
+     * Return this path as an {@link Absolute} SchemaNodeIdentifier.
+     *
+     * @return An SchemaNodeIdentifier.
+     * @throws IllegalStateException if this path is empty or is not absolute.
+     */
+    public final Absolute asAbsolute() {
+        final SchemaNodeIdentifier ret = asSchemaNodeIdentifier();
+        if (ret instanceof Absolute) {
+            return (Absolute) ret;
+        }
+        throw new IllegalStateException("Path " + this + " is relative");
+    }
+
+    /**
+     * Return this path as an {@link Descendant} SchemaNodeIdentifier.
+     *
+     * @return An SchemaNodeIdentifier.
+     * @throws IllegalStateException if this path is empty or is not relative.
+     */
+    public final Descendant asDescendant() {
+        final SchemaNodeIdentifier ret = asSchemaNodeIdentifier();
+        if (ret instanceof Descendant) {
+            return (Descendant) ret;
         }
-        return result;
+        throw new IllegalStateException("Path " + this + " is absolute");
+    }
+
+    @Override
+    public final int hashCode() {
+        return hash;
     }
 
     @Override
@@ -205,22 +330,16 @@ public class SchemaPath {
         if (getClass() != obj.getClass()) {
             return false;
         }
-        SchemaPath other = (SchemaPath) obj;
-        if (absolute != other.absolute) {
-            return false;
-        }
-
-        return Iterables.elementsEqual(path, other.path);
+        final SchemaPath other = (SchemaPath) obj;
+        return Objects.equals(qname, other.qname) && Objects.equals(parent, other.parent);
     }
 
     @Override
-    public String toString() {
-        StringBuilder builder = new StringBuilder();
-        builder.append("SchemaPath [path=");
-        builder.append(path);
-        builder.append(", absolute=");
-        builder.append(absolute);
-        builder.append("]");
-        return builder.toString();
+    public final String toString() {
+        return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
+    }
+
+    protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+        return toStringHelper.add("path", getPathFromRoot());
     }
 }