Convert MinMaxElementsValidation to ModificationApplyOperation
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / MinMaxElementsValidation.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import java.util.Optional;
14 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
15 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
16 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
17 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.RequiredElementCountException;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
24 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraintAware;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 final class MinMaxElementsValidation extends DelegatingModificationApplyOperation {
29     private static final Logger LOG = LoggerFactory.getLogger(MinMaxElementsValidation.class);
30
31     private final SchemaAwareApplyOperation delegate;
32     private final int minElements;
33     private final int maxElements;
34
35     private MinMaxElementsValidation(final SchemaAwareApplyOperation delegate, final Integer minElements,
36             final Integer maxElements) {
37         this.delegate = requireNonNull(delegate);
38         this.minElements = minElements != null ? minElements : 0;
39         this.maxElements = maxElements != null ? maxElements : Integer.MAX_VALUE;
40     }
41
42     static ModificationApplyOperation from(final SchemaAwareApplyOperation delegate, final DataSchemaNode schema) {
43         if (!(schema instanceof ElementCountConstraintAware)) {
44             return delegate;
45         }
46         final Optional<ElementCountConstraint> optConstraint = ((ElementCountConstraintAware) schema)
47                 .getElementCountConstraint();
48         if (!optConstraint.isPresent()) {
49             return delegate;
50         }
51
52         final ElementCountConstraint constraint = optConstraint.get();
53         return new MinMaxElementsValidation(delegate, constraint.getMinElements(), constraint.getMaxElements());
54     }
55
56     @Override
57     ModificationApplyOperation delegate() {
58         return delegate;
59     }
60
61     @Override
62     Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> storeMeta,
63             final Version version) {
64         Optional<TreeNode> ret = modification.getValidatedNode(this, storeMeta);
65         if (ret == null) {
66             // Deal with the result moving on us
67             ret = delegate.apply(modification, storeMeta, version);
68             checkChildren(modification.getIdentifier(), numOfChildrenFromTreeNode(ret));
69         }
70         return ret;
71     }
72
73     @Override
74     void checkApplicable(final ModificationPath path, final NodeModification modification,
75             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
76         delegate.checkApplicable(path, modification, current, version);
77
78         if (!(modification instanceof ModifiedNode)) {
79             LOG.debug("Could not validate {}, does not implement expected class {}", modification, ModifiedNode.class);
80             return;
81         }
82         final ModifiedNode modified = (ModifiedNode) modification;
83
84         // We need to actually perform the operation to deal with merge in a sane manner. We know the modification
85         // is immutable, so the result of validation will probably not change.
86         final Optional<TreeNode> maybeApplied = delegate.apply(modified, current, version);
87         validateMinMaxElements(path, modified.getIdentifier(), numOfChildrenFromTreeNode(maybeApplied));
88
89         // Everything passed. We now have a snapshot of the result node, it would be too bad if we just threw it out.
90         // We know what the result of an apply operation is going to be *if* the following are kept unchanged:
91         // - the 'current' node
92         // - the schemacontext (therefore, the fact this object is associated with the modification)
93         //
94         // So let's stash the result. We will pick it up during apply operation.
95         modified.setValidatedNode(this, current, maybeApplied);
96     }
97
98     @Override
99     void verifyStructure(final NormalizedNode<?, ?> modification, final boolean verifyChildren) {
100         delegate.verifyStructure(modification, verifyChildren);
101         if (verifyChildren) {
102             checkChildren(modification.getIdentifier(), numOfChildrenFromValue(modification));
103         }
104     }
105
106     private void validateMinMaxElements(final ModificationPath path, final PathArgument id, final int children)
107             throws DataValidationFailedException {
108         if (minElements > children) {
109             throw new RequiredElementCountException(path.toInstanceIdentifier(), minElements, maxElements,
110                 children, "%s does not have enough elements (%s), needs at least %s", id, children, minElements);
111         }
112         if (maxElements < children) {
113             throw new RequiredElementCountException(path.toInstanceIdentifier(), minElements, maxElements,
114                 children, "%s has too many elements (%s), can have at most %s", id, children, maxElements);
115         }
116     }
117
118     private void checkChildren(final PathArgument id, final int children) {
119         checkArgument(minElements <= children, "Node %s does not have enough elements (%s), needs at least %s", id,
120                 children, minElements);
121         checkArgument(maxElements >= children, "Node %s has too many elements (%s), can have at most %s", id, children,
122                 maxElements);
123     }
124
125     private static int numOfChildrenFromTreeNode(final Optional<TreeNode> node) {
126         return node.isPresent() ? numOfChildrenFromValue(node.get().getData()) : 0;
127     }
128
129     private static int numOfChildrenFromValue(final NormalizedNode<?, ?> value) {
130         if (value instanceof NormalizedNodeContainer) {
131             return ((NormalizedNodeContainer<?, ?, ?>) value).getValue().size();
132         } else if (value instanceof UnkeyedListNode) {
133             return ((UnkeyedListNode) value).getSize();
134         }
135
136         throw new IllegalArgumentException(String.format(
137                 "Unexpected type '%s', expected types are NormalizedNodeContainer and UnkeyedListNode",
138                 value.getClass()));
139     }
140 }