BUG-4295: instantiate MERGE operations lazily
[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 (!checkOriginalPresent(modChild)) {
118                         result++;
119                     }
120                     break;
121                 case MERGE:
122                     if (!checkOriginalPresent(modChild)) {
123                         result++;
124                     }
125                     break;
126                 case DELETE:
127                     if (checkOriginalPresent(modChild)) {
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     private static boolean checkOriginalPresent(ModifiedNode child) {
143         return child.getOriginal().isPresent();
144     }
145
146     @Override
147     protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
148             final Optional<TreeNode> current) throws DataValidationFailedException {
149         delegate.checkTouchApplicable(path, modification, current);
150         checkMinMaxElements(path, modification, current);
151     }
152
153     @Override
154     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
155             final Optional<TreeNode> current) throws DataValidationFailedException {
156         delegate.checkMergeApplicable(path, modification, current);
157         checkMinMaxElements(path, modification, current);
158     }
159
160     @Override
161     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
162             final Optional<TreeNode> current) throws DataValidationFailedException {
163         delegate.checkWriteApplicable(path, modification, current);
164         checkMinMaxElements(path, modification, current);
165     }
166
167
168     @Override
169     public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
170         return delegate.getChild(child);
171     }
172
173     @Override
174     protected void verifyStructure(final NormalizedNode<?, ?> modification, final boolean verifyChildren) {
175         delegate.verifyStructure(modification, verifyChildren);
176     }
177
178     @Override
179     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
180         return delegate.applyMerge(modification, currentMeta, version);
181     }
182
183     @Override
184     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
185         return delegate.applyTouch(modification, currentMeta, version);
186     }
187
188     @Override
189     protected TreeNode applyWrite(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
190             final Version version) {
191         return delegate.applyWrite(modification, currentMeta, version);
192     }
193
194     @Override
195     protected ChildTrackingPolicy getChildPolicy() {
196         return delegate.getChildPolicy();
197     }
198
199     @Override
200     void mergeIntoModifiedNode(final ModifiedNode node, final NormalizedNode<?, ?> value, final Version version) {
201         delegate.mergeIntoModifiedNode(node, value, version);
202     }
203
204     @Override
205     void recursivelyVerifyStructure(NormalizedNode<?, ?> value) {
206         delegate.recursivelyVerifyStructure(value);
207     }
208 }