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