Split out AbstractValidation
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / MinMaxElementsValidation.java
index a474e4e8d664df6a95d04dae176b6d2014990842..f5c75a6524eafc0d2b56ed2ccc19025f79aa9450 100644 (file)
@@ -7,93 +7,80 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Verify;
+import com.google.common.base.MoreObjects.ToStringHelper;
 import java.util.Optional;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
 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.UnkeyedListNode;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
+import org.opendaylight.yangtools.yang.data.api.schema.tree.RequiredElementCountException;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraintAware;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
-final class MinMaxElementsValidation extends SchemaAwareApplyOperation {
-    private static final Logger LOG = LoggerFactory.getLogger(MinMaxElementsValidation.class);
-
-    private final SchemaAwareApplyOperation delegate;
+final class MinMaxElementsValidation<T extends DataSchemaNode & ElementCountConstraintAware>
+        extends AbstractValidation {
     private final int minElements;
     private final int maxElements;
 
-    private MinMaxElementsValidation(final SchemaAwareApplyOperation delegate, final Integer minElements,
+    private MinMaxElementsValidation(final SchemaAwareApplyOperation<T> delegate, final Integer minElements,
             final Integer maxElements) {
-        this.delegate = Preconditions.checkNotNull(delegate);
+        super(delegate);
         this.minElements = minElements != null ? minElements : 0;
         this.maxElements = maxElements != null ? maxElements : Integer.MAX_VALUE;
     }
 
-    static SchemaAwareApplyOperation from(final SchemaAwareApplyOperation delegate, final DataSchemaNode schema) {
-        if (!(schema instanceof ElementCountConstraintAware)) {
-            return delegate;
-        }
-        final Optional<ElementCountConstraint> optConstraint = ((ElementCountConstraintAware) schema)
-                .getElementCountConstraint();
+    static <T extends DataSchemaNode & ElementCountConstraintAware> ModificationApplyOperation from(
+            final SchemaAwareApplyOperation<T> delegate) {
+        final Optional<ElementCountConstraint> optConstraint = delegate.getSchema().getElementCountConstraint();
         if (!optConstraint.isPresent()) {
             return delegate;
         }
 
         final ElementCountConstraint constraint = optConstraint.get();
-        return new MinMaxElementsValidation(delegate, constraint.getMinElements(), constraint.getMaxElements());
+        return new MinMaxElementsValidation<>(delegate, constraint.getMinElements(), constraint.getMaxElements());
+    }
+
+    @Override
+    void enforceOnData(final NormalizedNode<?, ?> data) {
+        enforceOnData(data, (actual, message) -> new IllegalArgumentException(message));
+    }
+
+    @Override
+    void enforceOnData(final ModificationPath path, final NormalizedNode<?, ?> data)
+            throws RequiredElementCountException {
+        enforceOnData(data, (actual, message) -> new RequiredElementCountException(path.toInstanceIdentifier(),
+            minElements, maxElements, actual, message));
+    }
+
+    @FunctionalInterface
+    @NonNullByDefault
+    interface ExceptionSupplier<T extends Exception> {
+        T get(int actual, String message);
     }
 
-    private void validateMinMaxElements(final YangInstanceIdentifier path, final PathArgument id,
-            final NormalizedNode<?, ?> data) throws DataValidationFailedException {
-        final int children = numOfChildrenFromValue(data);
+    private <X extends @NonNull Exception> void enforceOnData(final NormalizedNode<?, ?> value,
+            final ExceptionSupplier<X> exceptionSupplier) throws X {
+        final int children = numOfChildrenFromValue(value);
         if (minElements > children) {
-            throw new DataValidationFailedException(path, String.format(
-                    "%s does not have enough elements (%s), needs at least %s", id, children, minElements));
+            throw exceptionSupplier.get(children, value.getIdentifier()
+                + " does not have enough elements (" + children + "), needs at least " + minElements);
         }
         if (maxElements < children) {
-            throw new DataValidationFailedException(path, String.format(
-                    "%s has too many elements (%s), can have at most %s", id, children, maxElements));
+            throw exceptionSupplier.get(children, value.getIdentifier()
+                + " has too many elements (" + children + "), can have at most " + maxElements);
         }
     }
 
-    private void checkMinMaxElements(final YangInstanceIdentifier path, final NodeModification nodeMod,
-            final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
-        if (!(nodeMod instanceof ModifiedNode)) {
-            LOG.debug("Could not validate {}, does not implement expected class {}", nodeMod, ModifiedNode.class);
-            return;
-        }
-
-        final ModifiedNode modification = (ModifiedNode) nodeMod;
-
-        // We need to actually perform the operation to get deal with merge in a sane manner. We know the modification
-        // is immutable, so the result of validation will probably not change.
-        final Optional<TreeNode> maybeApplied = delegate.apply(modification, current, version);
-        Verify.verify(maybeApplied.isPresent());
-
-        final TreeNode applied = maybeApplied.get();
-        validateMinMaxElements(path, modification.getIdentifier(), applied.getData());
-
-        // Everything passed. We now have a snapshot of the result node, it would be too bad if we just threw it out.
-        // We know what the result of an apply operation is going to be *if* the following are kept unchanged:
-        // - the 'current' node
-        // - the schemacontext (therefore, the fact this object is associated with the modification)
-        //
-        // So let's stash the result. We will pick it up during apply operation.
-        modification.setValidatedNode(this, current, applied);
+    @Override
+    ToStringHelper addToStringAttributes(final ToStringHelper helper) {
+        return super.addToStringAttributes(helper.add("min", minElements).add("max", maxElements));
     }
 
     private static int numOfChildrenFromValue(final NormalizedNode<?, ?> value) {
         if (value instanceof NormalizedNodeContainer) {
-            return ((NormalizedNodeContainer<?, ?, ?>) value).getValue().size();
+            return ((NormalizedNodeContainer<?, ?, ?>) value).size();
         } else if (value instanceof UnkeyedListNode) {
             return ((UnkeyedListNode) value).getSize();
         }
@@ -102,84 +89,4 @@ final class MinMaxElementsValidation extends SchemaAwareApplyOperation {
                 "Unexpected type '%s', expected types are NormalizedNodeContainer and UnkeyedListNode",
                 value.getClass()));
     }
-
-    @Override
-    protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
-            final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
-        delegate.checkTouchApplicable(path, modification, current, version);
-        checkMinMaxElements(path, modification, current, version);
-    }
-
-    @Override
-    protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
-            final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
-        delegate.checkMergeApplicable(path, modification, current, version);
-        checkMinMaxElements(path, modification, current, version);
-    }
-
-    @Override
-    protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
-            final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
-        delegate.checkWriteApplicable(path, modification, current, version);
-        checkMinMaxElements(path, modification, current, version);
-    }
-
-    @Override
-    public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
-        return delegate.getChild(child);
-    }
-
-    @Override
-    protected void verifyStructure(final NormalizedNode<?, ?> modification, final boolean verifyChildren) {
-        delegate.verifyStructure(modification, verifyChildren);
-    }
-
-    @Override
-    protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
-        final TreeNode validated = modification.getValidatedNode(this, Optional.of(currentMeta));
-        if (validated != null) {
-            return validated;
-        }
-
-        // FIXME: the result moved, make sure we enforce again
-        return delegate.applyMerge(modification, currentMeta, version);
-    }
-
-    @Override
-    protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
-        final TreeNode validated = modification.getValidatedNode(this, Optional.of(currentMeta));
-        if (validated != null) {
-            return validated;
-        }
-
-        // FIXME: the result moved, make sure we enforce again
-        return delegate.applyTouch(modification, currentMeta, version);
-    }
-
-    @Override
-    protected TreeNode applyWrite(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
-            final Version version) {
-        final TreeNode validated = modification.getValidatedNode(this, currentMeta);
-        if (validated != null) {
-            return validated;
-        }
-
-        // FIXME: the result moved, make sure we enforce again
-        return delegate.applyWrite(modification, currentMeta, version);
-    }
-
-    @Override
-    protected ChildTrackingPolicy getChildPolicy() {
-        return delegate.getChildPolicy();
-    }
-
-    @Override
-    void mergeIntoModifiedNode(final ModifiedNode node, final NormalizedNode<?, ?> value, final Version version) {
-        delegate.mergeIntoModifiedNode(node, value, version);
-    }
-
-    @Override
-    void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
-        delegate.recursivelyVerifyStructure(value);
-    }
 }