Add utility wrappers for instantiating builders/nodes
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / AbstractNodeContainerModificationStrategy.java
index f908483b409a22cb54f0a0476c4b90873322316b..079b3b36e0265a0e8e754e5198728a775a82b470 100644 (file)
@@ -8,20 +8,21 @@
 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.Optional;
-import com.google.common.base.Preconditions;
+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.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
@@ -30,23 +31,27 @@ import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
 
 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
-
-    private final Class<? extends NormalizedNode<?, ?>> nodeClass;
+    private final NormalizedNodeContainerSupport<?, ?> support;
     private final boolean verifyChildrenStructure;
 
-    protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass,
+    AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
             final DataTreeConfiguration treeConfig) {
-        this.nodeClass = Preconditions.checkNotNull(nodeClass , "nodeClass");
-        this.verifyChildrenStructure = (treeConfig.getTreeType() == TreeType.CONFIGURATION);
+        this.support = requireNonNull(support);
+        this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
+    }
+
+    @Override
+    protected final ChildTrackingPolicy getChildPolicy() {
+        return support.childPolicy;
     }
 
-    @SuppressWarnings("rawtypes")
     @Override
     void verifyStructure(final NormalizedNode<?, ?> writtenValue, final boolean verifyChildren) {
+        final Class<?> nodeClass = support.requiredClass;
         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
         checkArgument(writtenValue instanceof NormalizedNodeContainer);
         if (verifyChildrenStructure && verifyChildren) {
-            final NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
+            final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
             for (final Object child : container.getValue()) {
                 checkArgument(child instanceof NormalizedNode);
                 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
@@ -64,7 +69,7 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
 
     @Override
     protected void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
-        final NormalizedNodeContainer container = (NormalizedNodeContainer) value;
+        final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
         for (final Object child : container.getValue()) {
             checkArgument(child instanceof NormalizedNode);
             final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
@@ -73,16 +78,15 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
                 childOp.get().recursivelyVerifyStructure(castedChild);
             } else {
                 throw new SchemaValidationFailedException(
-                        String.format("Node %s is not a valid child of %s according to the schema.",
-                                castedChild.getIdentifier(), container.getIdentifier()));
+                    String.format("Node %s is not a valid child of %s according to the schema.",
+                        castedChild.getIdentifier(), container.getIdentifier()));
             }
         }
     }
 
     @Override
-    protected TreeNode applyWrite(final ModifiedNode modification,
+    protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
             final Optional<TreeNode> currentMeta, final Version version) {
-        final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
 
         if (modification.getChildren().isEmpty()) {
@@ -109,7 +113,7 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
         mutable.setSubtreeVersion(version);
 
         @SuppressWarnings("rawtypes")
-        final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
+        final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
         final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
 
         // We are good to go except one detail: this is a single logical write, but
@@ -133,7 +137,7 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
 
         for (final ModifiedNode mod : modifications) {
-            final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
+            final PathArgument id = mod.getIdentifier();
             final Optional<TreeNode> cm = meta.getChild(id);
 
             final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
@@ -186,12 +190,12 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
 
         switch (modification.getOperation()) {
-        case NONE:
-            // Fresh node, just record a MERGE with a value
+            case NONE:
+                // Fresh node, just record a MERGE with a value
                 recursivelyVerifyStructure(value);
-            modification.updateValue(LogicalOperation.MERGE, value);
-            return;
-        case TOUCH:
+                modification.updateValue(LogicalOperation.MERGE, value);
+                return;
+            case TOUCH:
 
                 mergeChildrenIntoModification(modification, children, version);
                 // We record empty merge value, since real children merges
@@ -200,40 +204,41 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
                 // 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, createEmptyValue(value));
+                modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
                 return;
-        case MERGE:
-            // Merging into an existing node. Merge data children modifications (maybe recursively) and mark as MERGE,
-            // invalidating cached snapshot
-            mergeChildrenIntoModification(modification, children, version);
+            case MERGE:
+                // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
+                // as MERGE, invalidating cached snapshot
+                mergeChildrenIntoModification(modification, children, version);
                 modification.updateOperationType(LogicalOperation.MERGE);
-            return;
-        case DELETE:
-            // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means we
-            // are really performing a write. One thing that ruins that are any child modifications. If there are any,
-            // we will perform a read() to get the current state of affairs, turn this into into a WRITE 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(), Version.initial());
-                if (current.isPresent()) {
-                    modification.updateValue(LogicalOperation.WRITE, current.get().getData());
-                    mergeChildrenIntoModification(modification, children, version);
-                    return;
+                return;
+            case DELETE:
+                // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
+                // we are really performing a write. One thing that ruins that are any child modifications. If there
+                // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
+                // 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(),
+                        Version.initial());
+                    if (current.isPresent()) {
+                        modification.updateValue(LogicalOperation.WRITE, current.get().getData());
+                        mergeChildrenIntoModification(modification, children, version);
+                        return;
+                    }
                 }
-            }
 
-            modification.updateValue(LogicalOperation.WRITE, value);
-            return;
-        case WRITE:
-            // We are augmenting a previous write. We'll just walk value's children, get the corresponding ModifiedNode
-            // and run recursively on it
-            mergeChildrenIntoModification(modification, children, version);
-            modification.updateOperationType(LogicalOperation.WRITE);
-            return;
+                modification.updateValue(LogicalOperation.WRITE, value);
+                return;
+            case WRITE:
+                // We are augmenting a previous write. We'll just walk value's children, get the corresponding
+                // ModifiedNode and run recursively on it
+                mergeChildrenIntoModification(modification, children, version);
+                modification.updateOperationType(LogicalOperation.WRITE);
+                return;
+            default:
+                throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
         }
-
-        throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
     }
 
     @Override
@@ -246,7 +251,7 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
         final Collection<ModifiedNode> children = modification.getChildren();
         if (!children.isEmpty()) {
             @SuppressWarnings("rawtypes")
-            final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
+            final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
             final MutableTreeNode newMeta = currentMeta.mutable();
             newMeta.setSubtreeVersion(version);
             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
@@ -275,16 +280,15 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
     }
 
     @Override
-    protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
+    protected void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
-            throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
-        }
-
-        if (!current.isPresent()) {
-            throw new ConflictingModificationAppliedException(path, "Node was deleted by other transaction.");
+            final YangInstanceIdentifier id = path.toInstanceIdentifier();
+            throw new ModifiedNodeDoesNotExistException(id,
+                String.format("Node %s does not exist. Cannot apply modification to its children.", id));
         }
 
+        checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
         checkChildPreconditions(path, modification, current.get(), version);
     }
 
@@ -295,19 +299,23 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
      * @param modification current modification
      * @param current Current data tree node.
      */
-    private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification,
+    private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
             final TreeNode current, final Version version) throws DataValidationFailedException {
         for (final NodeModification childMod : modification.getChildren()) {
-            final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
+            final PathArgument childId = childMod.getIdentifier();
             final Optional<TreeNode> childMeta = current.getChild(childId);
 
-            final YangInstanceIdentifier childPath = path.node(childId);
-            resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta, version);
+            path.push(childId);
+            try {
+                resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
+            } finally {
+                path.pop();
+            }
         }
     }
 
     @Override
-    protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
+    protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
         if (current.isPresent()) {
             checkChildPreconditions(path, modification, current.get(), version);
@@ -318,8 +326,12 @@ abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareAppl
         return verifyChildrenStructure;
     }
 
-    @SuppressWarnings("rawtypes")
-    protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
+    @Override
+    public final String toString() {
+        return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
+    }
 
-    protected abstract NormalizedNode<?, ?> createEmptyValue(NormalizedNode<?, ?> original);
+    ToStringHelper addToStringAttributes(final ToStringHelper helper) {
+        return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);
+    }
 }