Add UniqueValidation
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / AbstractNodeContainerModificationStrategy.java
index d8a651b03ff863d9999749189eb8e2dc0175e802..50ef3b0b7edc93b2c13ea1285c82d5bee6f7def5 100644 (file)
@@ -10,12 +10,12 @@ package org.opendaylight.yangtools.yang.data.impl.schema.tree;
 import static com.google.common.base.Preconditions.checkArgument;
 import static java.util.Objects.requireNonNull;
 
-import com.google.common.base.MoreObjects;
 import com.google.common.base.MoreObjects.ToStringHelper;
 import com.google.common.base.Verify;
 import java.util.Collection;
 import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
@@ -111,16 +111,14 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
     final void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
         if (verifyChildrenStructure) {
             final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
-            for (final Object child : container.getValue()) {
-                checkArgument(child instanceof NormalizedNode);
-                final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
-                final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
+            for (final NormalizedNode<?, ?> child : container.getValue()) {
+                final Optional<ModificationApplyOperation> childOp = getChild(child.getIdentifier());
                 if (childOp.isPresent()) {
-                    childOp.get().fullVerifyStructure(castedChild);
+                    childOp.get().fullVerifyStructure(child);
                 } else {
                     throw new SchemaValidationFailedException(String.format(
                             "Node %s is not a valid child of %s according to the schema.",
-                            castedChild.getIdentifier(), container.getIdentifier()));
+                            child.getIdentifier(), container.getIdentifier()));
                 }
             }
 
@@ -152,23 +150,21 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
     @Override
     protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
         final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
-        for (final Object child : container.getValue()) {
-            checkArgument(child instanceof NormalizedNode);
-            final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
-            final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
+        for (final NormalizedNode<?, ?> child : container.getValue()) {
+            final Optional<ModificationApplyOperation> childOp = getChild(child.getIdentifier());
             if (!childOp.isPresent()) {
                 throw new SchemaValidationFailedException(
                     String.format("Node %s is not a valid child of %s according to the schema.",
-                        castedChild.getIdentifier(), container.getIdentifier()));
+                        child.getIdentifier(), container.getIdentifier()));
             }
 
-            childOp.get().recursivelyVerifyStructure(castedChild);
+            childOp.get().recursivelyVerifyStructure(child);
         }
     }
 
     @Override
     protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
-            final Optional<TreeNode> currentMeta, final Version version) {
+            final Optional<? extends TreeNode> currentMeta, final Version version) {
         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
 
         if (modification.getChildren().isEmpty()) {
@@ -176,20 +172,18 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
         }
 
         /*
-         * This is where things get interesting. The user has performed a write and
-         * then she applied some more modifications to it. So we need to make sense
-         * of that an apply the operations on top of the written value. We could have
-         * done it during the write, but this operation is potentially expensive, so
-         * we have left it out of the fast path.
+         * This is where things get interesting. The user has performed a write and then she applied some more
+         * modifications to it. So we need to make sense of that and apply the operations on top of the written value.
          *
-         * As it turns out, once we materialize the written data, we can share the
-         * code path with the subtree change. So let's create an unsealed TreeNode
-         * and run the common parts on it -- which end with the node being sealed.
+         * We could have done it during the write, but this operation is potentially expensive, so we have left it out
+         * of the fast path.
          *
-         * FIXME: this code needs to be moved out from the prepare() path and into
-         *        the read() and seal() paths. Merging of writes needs to be charged
-         *        to the code which originated this, not to the code which is
-         *        attempting to make it visible.
+         * As it turns out, once we materialize the written data, we can share the code path with the subtree change. So
+         * let's create an unsealed TreeNode and run the common parts on it -- which end with the node being sealed.
+         *
+         * FIXME: this code needs to be moved out from the prepare() path and into the read() and seal() paths. Merging
+         *        of writes needs to be charged to the code which originated this, not to the code which is attempting
+         *        to make it visible.
          */
         final MutableTreeNode mutable = newValueMeta.mutable();
         mutable.setSubtreeVersion(version);
@@ -220,9 +214,9 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
 
         for (final ModifiedNode mod : modifications) {
             final PathArgument id = mod.getIdentifier();
-            final Optional<TreeNode> cm = meta.getChild(id);
+            final Optional<? extends TreeNode> cm = meta.getChild(id);
 
-            final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
+            final Optional<? extends TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
             if (result.isPresent()) {
                 final TreeNode tn = result.get();
                 meta.addChild(tn);
@@ -247,9 +241,7 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
         final NormalizedNode<?, ?> value = modification.getWrittenValue();
 
         Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
-        @SuppressWarnings({"unchecked", "rawtypes"})
-        final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
-        for (final NormalizedNode<?, ?> c : children) {
+        for (final NormalizedNode<?, ?> c : ((NormalizedNodeContainer<?, ?, ?>) value).getValue()) {
             final PathArgument id = c.getIdentifier();
             modification.modifyChild(id, resolveChildOperation(id), version);
         }
@@ -257,7 +249,7 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
     }
 
     private void mergeChildrenIntoModification(final ModifiedNode modification,
-            final Collection<NormalizedNode<?, ?>> children, final Version version) {
+            final Collection<? extends NormalizedNode<?, ?>> children, final Version version) {
         for (final NormalizedNode<?, ?> c : children) {
             final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
             final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
@@ -268,8 +260,8 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
     @Override
     final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
             final Version version) {
-        @SuppressWarnings({ "unchecked", "rawtypes" })
-        final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
+        final Collection<? extends NormalizedNode<?, ?>> children =
+                ((NormalizedNodeContainer<?, ?, ?>)value).getValue();
 
         switch (modification.getOperation()) {
             case NONE:
@@ -280,12 +272,10 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
             case TOUCH:
 
                 mergeChildrenIntoModification(modification, children, version);
-                // We record empty merge value, since real children merges
-                // are already expanded. This is needed to satisfy non-null for merge
-                // original merge value can not be used since it mean different
-                // order of operation - parent changes are always resolved before
-                // children ones, and having node in TOUCH means children was modified
-                // before.
+                // We record empty merge value, since real children merges are already expanded. This is needed to
+                // satisfy non-null for merge original merge value can not be used since it mean different order of
+                // operation - parent changes are always resolved before children ones, and having node in TOUCH means
+                // children was modified before.
                 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
                 return;
             case MERGE:
@@ -301,7 +291,7 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
                 // and then append any child entries.
                 if (!modification.getChildren().isEmpty()) {
                     // Version does not matter here as we'll throw it out
-                    final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
+                    final Optional<? extends TreeNode> current = apply(modification, modification.getOriginal(),
                         Version.initial());
                     if (current.isPresent()) {
                         modification.updateValue(LogicalOperation.WRITE, current.get().getData());
@@ -326,9 +316,11 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
     @Override
     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
         /*
-         * The user may have issued an empty merge operation. In this case we do not perform
-         * a data tree mutation, do not pass GO, and do not collect useless garbage. It
-         * also means the ModificationType is UNMODIFIED.
+         * The user may have issued an empty merge operation. In this case we:
+         * - do not perform a data tree mutation
+         * - do not pass GO, and
+         * - do not collect useless garbage.
+         * It also means the ModificationType is UNMODIFIED.
          */
         final Collection<ModifiedNode> children = modification.getChildren();
         if (!children.isEmpty()) {
@@ -339,12 +331,12 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
 
             /*
-             * It is possible that the only modifications under this node were empty merges,
-             * which were turned into UNMODIFIED. If that is the case, we can turn this operation
-             * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
-             * of speeding up any users, who can skip processing child nodes.
+             * It is possible that the only modifications under this node were empty merges, which were turned into
+             * UNMODIFIED. If that is the case, we can turn this operation into UNMODIFIED, too, potentially cascading
+             * it up to root. This has the benefit of speeding up any users, who can skip processing child nodes.
              *
              * In order to do that, though, we have to check all child operations are UNMODIFIED.
+             *
              * Let's do precisely that, stopping as soon we find a different result.
              */
             for (final ModifiedNode child : children) {
@@ -362,38 +354,46 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
     }
 
     @Override
-    protected void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
-            final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
-        if (!modification.getOriginal().isPresent() && !current.isPresent()) {
-            final YangInstanceIdentifier id = path.toInstanceIdentifier();
-            throw new ModifiedNodeDoesNotExistException(id,
-                String.format("Node %s does not exist. Cannot apply modification to its children.", id));
+    protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
+            final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
+        final TreeNode currentNode;
+        if (!current.isPresent()) {
+            currentNode = defaultTreeNode();
+            if (currentNode == null) {
+                if (!modification.getOriginal().isPresent()) {
+                    final YangInstanceIdentifier id = path.toInstanceIdentifier();
+                    throw new ModifiedNodeDoesNotExistException(id,
+                        String.format("Node %s does not exist. Cannot apply modification to its children.", id));
+                }
+
+                throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
+                    "Node was deleted by other transaction.");
+            }
+        } else {
+            currentNode = current.get();
         }
 
-        checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
-        checkChildPreconditions(path, modification, current.get(), version);
+        checkChildPreconditions(path, modification, currentNode, version);
     }
 
     /**
-     * Checks is supplied {@link NodeModification} is applicable for Subtree Modification. This variant is used by
-     * subclasses which support automatic lifecycle.
+     * Return the default tree node. Default implementation does nothing, but can be overridden to call
+     * {@link #defaultTreeNode(NormalizedNode)}.
      *
-     * @param path Path to current node
-     * @param modification Node modification which should be applied.
-     * @param current Current state of data tree
-     * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
-     * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
-     *         modification is not applicable (e.g. leaf node).
+     * @return Default empty tree node, or null if no default is available
      */
-    final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
-            final Optional<TreeNode> current, final Version version, final NormalizedNode<?, ?> emptyNode)
-                    throws DataValidationFailedException {
-        checkChildPreconditions(path, modification, touchMeta(current, emptyNode), version);
+    @Nullable TreeNode defaultTreeNode() {
+        // Defaults to no recovery
+        return null;
+    }
+
+    static final TreeNode defaultTreeNode(final NormalizedNode<?, ?> emptyNode) {
+        return TreeNodeFactory.createTreeNode(emptyNode, FAKE_VERSION);
     }
 
     @Override
     protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
-            final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
+            final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
         if (current.isPresent()) {
             checkChildPreconditions(path, modification, current.get(), version);
         }
@@ -410,7 +410,7 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
             final TreeNode current, final Version version) throws DataValidationFailedException {
         for (final NodeModification childMod : modification.getChildren()) {
             final PathArgument childId = childMod.getIdentifier();
-            final Optional<TreeNode> childMeta = current.getChild(childId);
+            final Optional<? extends TreeNode> childMeta = current.getChild(childId);
 
             path.push(childId);
             try {
@@ -421,15 +421,7 @@ abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
         }
     }
 
-    private static TreeNode touchMeta(final Optional<TreeNode> current, final NormalizedNode<?, ?> emptyNode) {
-        return current.isPresent() ? current.get() : TreeNodeFactory.createTreeNode(emptyNode, FAKE_VERSION);
-    }
-
     @Override
-    public final String toString() {
-        return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
-    }
-
     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
         return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);
     }