932f20a810092d5d9543a5cabb94ebe0446deaf9
[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
9 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
10
11
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Verify;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
19 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
23 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
24 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 final class MinMaxElementsValidation extends SchemaAwareApplyOperation {
29
30     private static final Logger LOG = LoggerFactory.getLogger(MinMaxElementsValidation.class);
31     private final SchemaAwareApplyOperation delegate;
32     private final Integer minElements;
33     private final Integer 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;
39         this.maxElements = maxElements;
40     }
41
42     static SchemaAwareApplyOperation from(final SchemaAwareApplyOperation delegate, final DataSchemaNode schema) {
43         final ConstraintDefinition constraints = schema.getConstraints();
44         if (constraints == null || (constraints.getMinElements() == null && constraints.getMaxElements() == null)) {
45             return delegate;
46         }
47         return new MinMaxElementsValidation(delegate, constraints.getMinElements(), constraints.getMaxElements());
48
49     }
50
51     private static int findChildrenBefore(final Optional<TreeNode> current) {
52         if (current.isPresent()) {
53             return numOfChildrenFromValue(current.get().getData());
54         } else {
55             return 0;
56         }
57     }
58
59     private static int findChildrenAfter(final ModifiedNode modification) {
60         if (modification.getWrittenValue() != null) {
61             return numOfChildrenFromValue(modification.getWrittenValue());
62         } else {
63             return 0;
64         }
65     }
66
67     private void checkMinMaxElements(final YangInstanceIdentifier path, final NodeModification nodeMod,
68             final Optional<TreeNode> current) throws DataValidationFailedException {
69         if (!(nodeMod instanceof ModifiedNode)) {
70             LOG.debug("Could not validate {}, does not implement expected class {}", nodeMod, ModifiedNode.class);
71             return;
72         }
73
74         final ModifiedNode modification = (ModifiedNode) nodeMod;
75         final int childrenBefore = (modification.getOperation() == LogicalOperation.WRITE) ? 0 : findChildrenBefore
76                 (current);
77         Verify.verify(childrenBefore >= 0, "Child count before is %s (from %s)", childrenBefore, current);
78
79         final int childrenAfter = findChildrenAfter(modification);
80         Verify.verify(childrenAfter >= 0, "Child count after is %s (from %s)", childrenAfter, modification);
81
82         final int childrenModified = numOfChildrenFromChildMods(modification, current);
83         LOG.debug("Modified child count is %s (from %s and %s)", childrenModified, modification, current);
84
85         final int childrenTotal = childrenBefore + childrenAfter + childrenModified;
86         Verify.verify(childrenTotal >= 0, "Total child count is %s (from %s and %s)", childrenTotal, modification, current);
87
88         if (minElements != null && minElements > childrenTotal) {
89             throw new DataValidationFailedException(path, String.format(
90                     "%s does not have enough elements (%s), needs at least %s", modification.getIdentifier(),
91                     childrenTotal, minElements));
92         }
93         if (maxElements != null && maxElements < childrenTotal) {
94             throw new DataValidationFailedException(path, String.format(
95                     "%s has too many elements (%s), can have at most %s", modification.getIdentifier(), childrenTotal,
96                     maxElements));
97         }
98     }
99
100     private static int numOfChildrenFromValue(final NormalizedNode<?, ?> value) {
101         if (value instanceof NormalizedNodeContainer) {
102             return ((NormalizedNodeContainer<?, ?, ?>) value).getValue().size();
103         } else if (value instanceof UnkeyedListNode) {
104             return ((UnkeyedListNode) value).getSize();
105         }
106
107         throw new IllegalArgumentException(String.format(
108                 "Unexpected type '%s', expected types are NormalizedNodeContainer and UnkeyedListNode",
109                 value.getClass()));
110     }
111
112     private static int numOfChildrenFromChildMods(final ModifiedNode modification, final Optional<TreeNode> current) {
113         int result = 0;
114         for (final ModifiedNode modChild : modification.getChildren()) {
115             switch (modChild.getOperation()) {
116                 case WRITE:
117                     if (!modChild.getOriginal().isPresent()) {
118                         result++;
119                     }
120                     break;
121                 case MERGE:
122                     if (!current.isPresent()) {
123                         result++;
124                     }
125                     break;
126                 case DELETE:
127                     if (modChild.getOriginal().isPresent()) {
128                         result--;
129                     }
130                     break;
131                 case NONE:
132                 case TOUCH:
133                     // NOOP
134                     break;
135                 default:
136                     throw new IllegalArgumentException("Unsupported operation type: " + modChild.getOperation());
137             }
138         }
139         return result;
140     }
141
142     @Override
143     protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
144             final Optional<TreeNode> current) throws DataValidationFailedException {
145         delegate.checkTouchApplicable(path, modification, current);
146         checkMinMaxElements(path, modification, current);
147     }
148
149     @Override
150     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
151             final Optional<TreeNode> current) throws DataValidationFailedException {
152         delegate.checkMergeApplicable(path, modification, current);
153         checkMinMaxElements(path, modification, current);
154     }
155
156     @Override
157     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
158             final Optional<TreeNode> current) throws DataValidationFailedException {
159         delegate.checkWriteApplicable(path, modification, current);
160         checkMinMaxElements(path, modification, current);
161     }
162
163
164     @Override
165     public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
166         return delegate.getChild(child);
167     }
168
169     @Override
170     protected void verifyStructure(final NormalizedNode<?, ?> modification, final boolean verifyChildren) {
171         delegate.verifyStructure(modification, verifyChildren);
172     }
173
174     @Override
175     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
176         return delegate.applyMerge(modification, currentMeta, version);
177     }
178
179     @Override
180     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
181         return delegate.applyTouch(modification, currentMeta, version);
182     }
183
184     @Override
185     protected TreeNode applyWrite(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
186             final Version version) {
187         return delegate.applyWrite(modification, currentMeta, version);
188     }
189
190     @Override
191     protected ChildTrackingPolicy getChildPolicy() {
192         return delegate.getChildPolicy();
193     }
194 }