90ece03d585b877eb5d786b64403a1c6d124e3d3
[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<T extends DataSchemaNode & ElementCountConstraintAware>
29         extends ModificationApplyOperation {
30     private static final Logger LOG = LoggerFactory.getLogger(MinMaxElementsValidation.class);
31
32     private final SchemaAwareApplyOperation<T> delegate;
33     private final int minElements;
34     private final int maxElements;
35
36     private MinMaxElementsValidation(final SchemaAwareApplyOperation<T> delegate, final Integer minElements,
37             final Integer maxElements) {
38         this.delegate = requireNonNull(delegate);
39         this.minElements = minElements != null ? minElements : 0;
40         this.maxElements = maxElements != null ? maxElements : Integer.MAX_VALUE;
41     }
42
43     static <T extends DataSchemaNode & ElementCountConstraintAware> ModificationApplyOperation from(
44             final SchemaAwareApplyOperation<T> delegate) {
45         final Optional<ElementCountConstraint> optConstraint = delegate.getSchema().getElementCountConstraint();
46         if (!optConstraint.isPresent()) {
47             return delegate;
48         }
49
50         final ElementCountConstraint constraint = optConstraint.get();
51         return new MinMaxElementsValidation<>(delegate, constraint.getMinElements(), constraint.getMaxElements());
52     }
53
54     @Override
55     Optional<? extends TreeNode> apply(final ModifiedNode modification, final Optional<? extends TreeNode> storeMeta,
56             final Version version) {
57         Optional<? extends TreeNode> ret = modification.getValidatedNode(this, storeMeta);
58         if (ret == null) {
59             // Deal with the result moving on us
60             ret = delegate.apply(modification, storeMeta, version);
61             if (ret.isPresent()) {
62                 checkChildren(ret.get().getData());
63             }
64         }
65
66         return ret;
67     }
68
69     @Override
70     void checkApplicable(final ModificationPath path, final NodeModification modification,
71             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
72         delegate.checkApplicable(path, modification, current, version);
73
74         if (!(modification instanceof ModifiedNode)) {
75             LOG.debug("Could not validate {}, does not implement expected class {}", modification, ModifiedNode.class);
76             return;
77         }
78         final ModifiedNode modified = (ModifiedNode) modification;
79
80         // We need to actually perform the operation to deal with merge in a sane manner. We know the modification
81         // is immutable, so the result of validation will probably not change. Note we should not be checking number
82         final Optional<? extends TreeNode> maybeApplied = delegate.apply(modified, current, version);
83         if (maybeApplied.isPresent()) {
84             // We only enforce min/max on present data and rely on MandatoryLeafEnforcer to take care of the empty case
85             validateMinMaxElements(path, maybeApplied.get().getData());
86         }
87
88         // Everything passed. We now have a snapshot of the result node, it would be too bad if we just threw it out.
89         // We know what the result of an apply operation is going to be *if* the following are kept unchanged:
90         // - the 'current' node
91         // - the schemacontext (therefore, the fact this object is associated with the modification)
92         //
93         // So let's stash the result. We will pick it up during apply operation.
94         modified.setValidatedNode(this, current, maybeApplied);
95     }
96
97     @Override
98     void fullVerifyStructure(final NormalizedNode<?, ?> modification) {
99         delegate.fullVerifyStructure(modification);
100         checkChildren(modification);
101     }
102
103     @Override
104     public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
105         return delegate.getChild(child);
106     }
107
108     @Override
109     ChildTrackingPolicy getChildPolicy() {
110         return delegate.getChildPolicy();
111     }
112
113     @Override
114     void mergeIntoModifiedNode(final ModifiedNode node, final NormalizedNode<?, ?> value, final Version version) {
115         delegate.mergeIntoModifiedNode(node, value, version);
116     }
117
118     @Override
119     void quickVerifyStructure(final NormalizedNode<?, ?> modification) {
120         delegate.quickVerifyStructure(modification);
121     }
122
123     @Override
124     void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
125         delegate.recursivelyVerifyStructure(value);
126     }
127
128     private void validateMinMaxElements(final ModificationPath path, final NormalizedNode<?, ?> value)
129             throws DataValidationFailedException {
130         final PathArgument id = value.getIdentifier();
131         final int children = numOfChildrenFromValue(value);
132         if (minElements > children) {
133             throw new RequiredElementCountException(path.toInstanceIdentifier(), minElements, maxElements, children,
134                 "%s does not have enough elements (%s), needs at least %s", id, children, minElements);
135         }
136         if (maxElements < children) {
137             throw new RequiredElementCountException(path.toInstanceIdentifier(), minElements, maxElements, children,
138                 "%s has too many elements (%s), can have at most %s", id, children, maxElements);
139         }
140     }
141
142     private void checkChildren(final NormalizedNode<?, ?> value) {
143         final PathArgument id = value.getIdentifier();
144         final int children = numOfChildrenFromValue(value);
145         checkArgument(minElements <= children, "Node %s does not have enough elements (%s), needs at least %s", id,
146                 children, minElements);
147         checkArgument(maxElements >= children, "Node %s has too many elements (%s), can have at most %s", id, children,
148                 maxElements);
149     }
150
151     private static int numOfChildrenFromValue(final NormalizedNode<?, ?> value) {
152         if (value instanceof NormalizedNodeContainer) {
153             return ((NormalizedNodeContainer<?, ?, ?>) value).size();
154         } else if (value instanceof UnkeyedListNode) {
155             return ((UnkeyedListNode) value).getSize();
156         }
157
158         throw new IllegalArgumentException(String.format(
159                 "Unexpected type '%s', expected types are NormalizedNodeContainer and UnkeyedListNode",
160                 value.getClass()));
161     }
162 }