02335ff6765a2cb82181a7a09ffe80ce6673952b
[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 com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import java.util.Optional;
13 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
14 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
15 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
16 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
17 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
18 import org.opendaylight.yangtools.yang.data.api.schema.tree.RequiredElementCountException;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
21 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
23 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraintAware;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 final class MinMaxElementsValidation extends SchemaAwareApplyOperation {
28     private static final Logger LOG = LoggerFactory.getLogger(MinMaxElementsValidation.class);
29
30     private final SchemaAwareApplyOperation delegate;
31     private final int minElements;
32     private final int maxElements;
33
34     private MinMaxElementsValidation(final SchemaAwareApplyOperation delegate, final Integer minElements,
35             final Integer maxElements) {
36         this.delegate = Preconditions.checkNotNull(delegate);
37         this.minElements = minElements != null ? minElements : 0;
38         this.maxElements = maxElements != null ? maxElements : Integer.MAX_VALUE;
39     }
40
41     static SchemaAwareApplyOperation from(final SchemaAwareApplyOperation delegate, final DataSchemaNode schema) {
42         if (!(schema instanceof ElementCountConstraintAware)) {
43             return delegate;
44         }
45         final Optional<ElementCountConstraint> optConstraint = ((ElementCountConstraintAware) schema)
46                 .getElementCountConstraint();
47         if (!optConstraint.isPresent()) {
48             return delegate;
49         }
50
51         final ElementCountConstraint constraint = optConstraint.get();
52         return new MinMaxElementsValidation(delegate, constraint.getMinElements(), constraint.getMaxElements());
53     }
54
55     private void validateMinMaxElements(final ModificationPath path, final PathArgument id,
56             final NormalizedNode<?, ?> data) throws DataValidationFailedException {
57         final int children = numOfChildrenFromValue(data);
58         if (minElements > children) {
59             throw new RequiredElementCountException(path.toInstanceIdentifier(), minElements, maxElements,
60                 children, "%s does not have enough elements (%s), needs at least %s", id, children, minElements);
61         }
62         if (maxElements < children) {
63             throw new RequiredElementCountException(path.toInstanceIdentifier(), minElements, maxElements,
64                 children, "%s has too many elements (%s), can have at most %s", id, children, maxElements);
65         }
66     }
67
68     private void checkMinMaxElements(final ModificationPath path, final NodeModification nodeMod,
69             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
70         if (!(nodeMod instanceof ModifiedNode)) {
71             LOG.debug("Could not validate {}, does not implement expected class {}", nodeMod, ModifiedNode.class);
72             return;
73         }
74
75         final ModifiedNode modification = (ModifiedNode) nodeMod;
76
77         // We need to actually perform the operation to get deal with merge in a sane manner. We know the modification
78         // is immutable, so the result of validation will probably not change.
79         final Optional<TreeNode> maybeApplied = delegate.apply(modification, current, version);
80         Verify.verify(maybeApplied.isPresent());
81
82         final TreeNode applied = maybeApplied.get();
83         validateMinMaxElements(path, modification.getIdentifier(), applied.getData());
84
85         // Everything passed. We now have a snapshot of the result node, it would be too bad if we just threw it out.
86         // We know what the result of an apply operation is going to be *if* the following are kept unchanged:
87         // - the 'current' node
88         // - the schemacontext (therefore, the fact this object is associated with the modification)
89         //
90         // So let's stash the result. We will pick it up during apply operation.
91         modification.setValidatedNode(this, current, applied);
92     }
93
94     private static int numOfChildrenFromValue(final NormalizedNode<?, ?> value) {
95         if (value instanceof NormalizedNodeContainer) {
96             return ((NormalizedNodeContainer<?, ?, ?>) value).getValue().size();
97         } else if (value instanceof UnkeyedListNode) {
98             return ((UnkeyedListNode) value).getSize();
99         }
100
101         throw new IllegalArgumentException(String.format(
102                 "Unexpected type '%s', expected types are NormalizedNodeContainer and UnkeyedListNode",
103                 value.getClass()));
104     }
105
106     @Override
107     protected void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
108             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
109         delegate.checkTouchApplicable(path, modification, current, version);
110         checkMinMaxElements(path, modification, current, version);
111     }
112
113     @Override
114     protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
115             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
116         delegate.checkMergeApplicable(path, modification, current, version);
117         checkMinMaxElements(path, modification, current, version);
118     }
119
120     @Override
121     protected void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
122             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
123         delegate.checkWriteApplicable(path, modification, current, version);
124         checkMinMaxElements(path, modification, current, version);
125     }
126
127     @Override
128     public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
129         return delegate.getChild(child);
130     }
131
132     @Override
133     protected void verifyStructure(final NormalizedNode<?, ?> modification, final boolean verifyChildren) {
134         delegate.verifyStructure(modification, verifyChildren);
135         if (verifyChildren) {
136             final int children = numOfChildrenFromValue(modification);
137             Preconditions.checkArgument(minElements <= children,
138                     "Node %s does not have enough elements (%s), needs at least %s", modification.getIdentifier(),
139                     children, minElements);
140             Preconditions.checkArgument(maxElements >= children,
141                     "Node %s has too many elements (%s), can have at most %s", modification.getIdentifier(), children,
142                     maxElements);
143         }
144     }
145
146     @Override
147     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
148         final TreeNode validated = modification.getValidatedNode(this, Optional.of(currentMeta));
149         if (validated != null) {
150             return validated;
151         }
152
153         // FIXME: the result moved, make sure we enforce again
154         return delegate.applyMerge(modification, currentMeta, version);
155     }
156
157     @Override
158     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
159         final TreeNode validated = modification.getValidatedNode(this, Optional.of(currentMeta));
160         if (validated != null) {
161             return validated;
162         }
163
164         // FIXME: the result moved, make sure we enforce again
165         return delegate.applyTouch(modification, currentMeta, version);
166     }
167
168     @Override
169     protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
170             final Optional<TreeNode> currentMeta, final Version version) {
171         final TreeNode validated = modification.getValidatedNode(this, currentMeta);
172         if (validated != null) {
173             return validated;
174         }
175
176         // FIXME: the result moved, make sure we enforce again
177         return delegate.applyWrite(modification, newValue, currentMeta, version);
178     }
179
180     @Override
181     protected ChildTrackingPolicy getChildPolicy() {
182         return delegate.getChildPolicy();
183     }
184
185     @Override
186     void mergeIntoModifiedNode(final ModifiedNode node, final NormalizedNode<?, ?> value, final Version version) {
187         delegate.mergeIntoModifiedNode(node, value, version);
188     }
189
190     @Override
191     void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
192         delegate.recursivelyVerifyStructure(value);
193     }
194 }