- return new MinMaxElementsValidation(delegate, constraints.getMinElements(), constraints.getMaxElements());
-
- }
-
- private static int findChildrenBefore(final Optional<TreeNode> current) {
- if (current.isPresent()) {
- return numOfChildrenFromValue(current.get().getData());
- } else {
- return 0;
- }
- }
-
- private static int findChildrenAfter(final ModifiedNode modification) {
- if (modification.getWrittenValue() != null) {
- return numOfChildrenFromValue(modification.getWrittenValue());
- } else {
- return 0;
- }
- }
-
- private void checkMinMaxElements(final YangInstanceIdentifier path, final NodeModification nodeMod,
- final Optional<TreeNode> current) 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;
-
- final int childrenBefore = findChildrenBefore(current);
-
- final int childrenAfter = findChildrenAfter(modification);
-
- final int childrenTotal = childrenBefore + childrenAfter + numOfChildrenFromChildMods(modification, current);
- if (minElements != null && minElements > childrenTotal) {
- throw new DataValidationFailedException(path, String.format(
- "%s does not have enough elements (%s), needs at least %s", modification.getIdentifier(),
- childrenTotal, minElements));
- }
- if (maxElements != null && maxElements < childrenTotal) {
- throw new DataValidationFailedException(path, String.format(
- "%s has too many elements (%s), can have at most %s", modification.getIdentifier(), childrenTotal,
- maxElements));
- }
- }
-
- 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()));
- }
-
- private static int numOfChildrenFromChildMods(final ModifiedNode modification, final Optional<TreeNode> current) {
- int result = 0;
- for (final ModifiedNode modChild : modification.getChildren()) {
- switch (modChild.getOperation()) {
- case WRITE:
- result++;
- break;
- case MERGE:
- if (!current.isPresent()) {
- result++;
- }
- break;
- case DELETE:
- result--;
- break;
- case NONE:
- case TOUCH:
- // NOOP
- break;
- default:
- throw new IllegalArgumentException("Unsupported operation type: " + modChild.getOperation());
- }
- }
- return result;
- }