- return new MinMaxElementsValidation(delegate, constraint.getMinElements(), constraint.getMaxElements());
- }
-
- private void validateMinMaxElements(final YangInstanceIdentifier path, final PathArgument id,
- final NormalizedNode<?, ?> data) throws DataValidationFailedException {
- final int children = numOfChildrenFromValue(data);
- if (minElements > children) {
- throw new RequiredElementCountException(path, minElements, maxElements,
- children, "%s does not have enough elements (%s), needs at least %s", id, children, minElements);
- }
- if (maxElements < children) {
- throw new RequiredElementCountException(path, minElements, maxElements,
- children, "%s has too many elements (%s), can have at most %s", id, children, maxElements);
- }
- }
-
- private void checkMinMaxElements(final YangInstanceIdentifier path, final NodeModification nodeMod,
- final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
- if (!(nodeMod instanceof ModifiedNode)) {
- LOG.debug("Could not validate {}, does not implement expected class {}", nodeMod, ModifiedNode.class);
- return;
- }
-
- final ModifiedNode modification = (ModifiedNode) nodeMod;
-
- // We need to actually perform the operation to get deal with merge in a sane manner. We know the modification
- // is immutable, so the result of validation will probably not change.
- final Optional<TreeNode> maybeApplied = delegate.apply(modification, current, version);
- Verify.verify(maybeApplied.isPresent());
-
- final TreeNode applied = maybeApplied.get();
- validateMinMaxElements(path, modification.getIdentifier(), applied.getData());
-
- // Everything passed. We now have a snapshot of the result node, it would be too bad if we just threw it out.
- // We know what the result of an apply operation is going to be *if* the following are kept unchanged:
- // - the 'current' node
- // - the schemacontext (therefore, the fact this object is associated with the modification)
- //
- // So let's stash the result. We will pick it up during apply operation.
- modification.setValidatedNode(this, current, applied);
- }
-
- private static int numOfChildrenFromValue(final NormalizedNode<?, ?> value) {
- if (value instanceof NormalizedNodeContainer) {
- return ((NormalizedNodeContainer<?, ?, ?>) value).getValue().size();
- } else if (value instanceof UnkeyedListNode) {
- return ((UnkeyedListNode) value).getSize();
- }
-
- throw new IllegalArgumentException(String.format(
- "Unexpected type '%s', expected types are NormalizedNodeContainer and UnkeyedListNode",
- value.getClass()));
- }
-
- @Override
- protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
- final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
- delegate.checkTouchApplicable(path, modification, current, version);
- checkMinMaxElements(path, modification, current, version);