Add LeafRefValidatation.computeValues()
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / leafref / LeafRefValidatation.java
index e39c88ec70ef4c4014354a1539de0f847ff60515..10265d3a3d5e334fa6b139c091dece197990245d 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.leafref;
 
+import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -18,10 +19,12 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.Set;
+import java.util.stream.Collectors;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
@@ -36,10 +39,10 @@ import org.opendaylight.yangtools.yang.data.api.schema.ValueNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+// FIXME: 3.0.0: Rename to LeafRefValidation
 public final class LeafRefValidatation {
 
     private static final Logger LOG = LoggerFactory.getLogger(LeafRefValidatation.class);
@@ -220,8 +223,13 @@ public final class LeafRefValidatation {
             final DataContainerNode<?> dataContainerNode = (DataContainerNode<?>) node;
 
             for (final DataContainerChild<? extends PathArgument, ?> child : dataContainerNode.getValue()) {
-                final QName qname = child.getNodeType();
+                if (child instanceof AugmentationNode) {
+                    validateNodeData(child, referencedByCtx, referencingCtx, modificationType, current
+                        .node(child.getIdentifier()));
+                    return;
+                }
 
+                final QName qname = child.getNodeType();
                 final LeafRefContext childReferencedByCtx;
                 if (referencedByCtx != null) {
                     childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
@@ -249,8 +257,13 @@ public final class LeafRefValidatation {
             for (final MapEntryNode mapEntry : map.getValue()) {
                 final YangInstanceIdentifier mapEntryYangInstanceIdentifier = current.node(mapEntry.getIdentifier());
                 for (final DataContainerChild<? extends PathArgument, ?> mapEntryNode : mapEntry.getValue()) {
-                    final QName qname = mapEntryNode.getNodeType();
+                    if (mapEntryNode instanceof AugmentationNode) {
+                        validateNodeData(mapEntryNode, referencedByCtx, referencingCtx, modificationType, current
+                            .node(mapEntryNode.getIdentifier()));
+                        return;
+                    }
 
+                    final QName qname = mapEntryNode.getNodeType();
                     final LeafRefContext childReferencedByCtx;
                     if (referencedByCtx != null) {
                         childReferencedByCtx = referencedByCtx.getReferencedChildByName(qname);
@@ -303,104 +316,77 @@ public final class LeafRefValidatation {
 
     private void validateLeafRefTargetNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext
             referencedByCtx, final ModificationType modificationType) {
-        final Map<LeafRefContext, Set<?>> leafRefsValues = new HashMap<>();
-        if (validatedLeafRefCtx.contains(referencedByCtx)) {
-            leafRefTargetNodeDataLog(leaf, referencedByCtx, modificationType, leafRefsValues, null);
+        if (!validatedLeafRefCtx.add(referencedByCtx)) {
+            LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] -> SKIP: Already "
+                    + "validated", modificationType, referencedByCtx.getNodeName(), leaf.getValue());
             return;
         }
 
-        final Map<QName, LeafRefContext> allReferencedByLeafRefCtxs = referencedByCtx.getAllReferencedByLeafRefCtxs();
-        for (final LeafRefContext leafRefContext : allReferencedByLeafRefCtxs.values()) {
-            if (leafRefContext.isReferencing()) {
-                final Set<Object> values = new HashSet<>();
-
-                final SchemaPath leafRefNodeSchemaPath = leafRefContext.getCurrentNodePath();
-                final LeafRefPath leafRefNodePath = LeafRefUtils.schemaPathToLeafRefPath(leafRefNodeSchemaPath,
-                                leafRefContext.getLeafRefContextModule());
-                final Iterable<QNameWithPredicate> pathFromRoot = leafRefNodePath.getPathFromRoot();
-                addValues(values, tree.getRootNode().getDataAfter(), pathFromRoot, null, QNameWithPredicate.ROOT);
-                leafRefsValues.put(leafRefContext, values);
-            }
+        LOG.trace("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]", modificationType,
+            referencedByCtx.getNodeName(), leaf.getValue());
+        final Set<LeafRefContext> leafRefs = referencedByCtx.getAllReferencedByLeafRefCtxs().values().stream()
+                .filter(LeafRefContext::isReferencing).collect(Collectors.toSet());
+        if (leafRefs.isEmpty()) {
+            return;
         }
 
-        if (!leafRefsValues.isEmpty()) {
-            final Set<Object> leafRefTargetNodeValues = new HashSet<>();
-            final SchemaPath nodeSchemaPath = referencedByCtx.getCurrentNodePath();
-            final LeafRefPath nodePath = LeafRefUtils.schemaPathToLeafRefPath(nodeSchemaPath, referencedByCtx
-                    .getLeafRefContextModule());
-            addValues(leafRefTargetNodeValues, tree.getRootNode().getDataAfter(), nodePath.getPathFromRoot(), null,
-                    QNameWithPredicate.ROOT);
-            leafRefTargetNodeDataLog(leaf, referencedByCtx, modificationType, leafRefsValues,
-                    leafRefTargetNodeValues);
-        } else {
-            leafRefTargetNodeDataLog(leaf, referencedByCtx, modificationType, null, null);
-        }
-        validatedLeafRefCtx.add(referencedByCtx);
+        final Set<Object> leafRefTargetNodeValues = extractRootValues(referencedByCtx);
+        leafRefs.forEach(leafRefContext -> {
+            extractRootValues(leafRefContext).forEach(leafRefsValue -> {
+                if (leafRefTargetNodeValues.contains(leafRefsValue)) {
+                    LOG.trace("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
+                    return;
+                }
+
+                LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: {} path "
+                        + "of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
+                        leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
+                        leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
+                errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation of leafref"
+                        + " TARGET node: %s path of invalid LEAFREF node: %s leafRef target path: %s %s", leafRefsValue,
+                        leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
+                        leafRefContext.getAbsoluteLeafRefTargetPath(),
+                        FAILED));
+            });
+        });
     }
 
-    private void leafRefTargetNodeDataLog(final NormalizedNode<?, ?> leaf, final LeafRefContext referencedByCtx,
-            final ModificationType modificationType, final Map<LeafRefContext, Set<?>> leafRefsValues,
-            final Set<Object> leafRefTargetNodeValues) {
-
-        if (leafRefsValues != null && !leafRefsValues.isEmpty()) {
-            final Set<Entry<LeafRefContext, Set<?>>> entrySet = leafRefsValues.entrySet();
-            LOG.debug("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}]",
-                    modificationType, referencedByCtx.getNodeName(), leaf.getValue());
-            for (final Entry<LeafRefContext, Set<?>> entry : entrySet) {
-                final LeafRefContext leafRefContext = entry.getKey();
-                final Set<?> leafRefValuesSet = entry.getValue();
-                for (final Object leafRefsValue : leafRefValuesSet) {
-                    if (leafRefTargetNodeValues != null && !leafRefTargetNodeValues.contains(leafRefsValue)) {
-                        LOG.debug("Invalid leafref value [{}] allowed values {} by validation of leafref TARGET node: "
-                                + "{} path of invalid LEAFREF node: {} leafRef target path: {} {}", leafRefsValue,
-                                leafRefTargetNodeValues, leaf.getNodeType(), leafRefContext.getCurrentNodePath(),
-                                leafRefContext.getAbsoluteLeafRefTargetPath(), FAILED);
-                        errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s by validation "
-                                        + "of leafref TARGET node: %s path of invalid LEAFREF node: %s leafRef target "
-                                        + "path: %s %s", leafRefsValue, leafRefTargetNodeValues, leaf.getNodeType(),
-                                leafRefContext.getCurrentNodePath(), leafRefContext.getAbsoluteLeafRefTargetPath(),
-                                FAILED));
-                    } else {
-                        LOG.debug("Valid leafref value [{}] {}", leafRefsValue, SUCCESS);
-                    }
-                }
-            }
-        } else if (leafRefsValues != null) {
-            LOG.debug("Operation [{}] validate data of leafref TARGET node: name[{}] = value[{}] "
-                    + "-> SKIP: Already validated", modificationType, referencedByCtx.getNodeName(), leaf.getValue());
-        }
+    private Set<Object> extractRootValues(final LeafRefContext context) {
+        return tree.getRootNode().getDataAfter()
+                .map(root -> computeValues(root, context.getLeafRefNodePath().getPathFromRoot(), null))
+                .orElse(ImmutableSet.of());
     }
 
     private void validateLeafRefNodeData(final NormalizedNode<?, ?> leaf, final LeafRefContext referencingCtx,
             final ModificationType modificationType, final YangInstanceIdentifier current) {
-        final HashSet<Object> values = new HashSet<>();
-        final LeafRefPath targetPath = referencingCtx.getAbsoluteLeafRefTargetPath();
-        final Iterable<QNameWithPredicate> pathFromRoot = targetPath.getPathFromRoot();
-
-        addValues(values, tree.getRootNode().getDataAfter(), pathFromRoot, current, QNameWithPredicate.ROOT);
-
-        if (!values.contains(leaf.getValue())) {
-            LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}",
-                    modificationType, referencingCtx.getNodeName(), leaf.getValue(), FAILED);
-            LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
-                    leaf.getValue(), values, leaf.getNodeType(), referencingCtx.getAbsoluteLeafRefTargetPath());
-            errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s "
-                            + "leafRef target path: %s", leaf.getValue(), values, leaf.getNodeType(), referencingCtx
-                    .getAbsoluteLeafRefTargetPath()));
-        } else {
+        final Set<Object> values = tree.getRootNode().getDataAfter().map(
+            root -> computeValues(root, referencingCtx.getAbsoluteLeafRefTargetPath().getPathFromRoot(), current))
+                .orElse(ImmutableSet.of());
+        if (values.contains(leaf.getValue())) {
             LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
-                    referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
+                referencingCtx.getNodeName(), leaf.getValue(), SUCCESS);
+            return;
         }
+
+        LOG.debug("Operation [{}] validate data of LEAFREF node: name[{}] = value[{}] {}", modificationType,
+            referencingCtx.getNodeName(), leaf.getValue(), FAILED);
+        LOG.debug("Invalid leafref value [{}] allowed values {} of LEAFREF node: {} leafRef target path: {}",
+            leaf.getValue(), values, leaf.getNodeType(), referencingCtx.getAbsoluteLeafRefTargetPath());
+        errorsMessages.add(String.format("Invalid leafref value [%s] allowed values %s of LEAFREF node: %s leafRef "
+                + "target path: %s", leaf.getValue(), values, leaf.getNodeType(),
+                referencingCtx.getAbsoluteLeafRefTargetPath()));
+    }
+
+    private Set<Object> computeValues(final NormalizedNode<?, ?> node, final Iterable<QNameWithPredicate> path,
+            final YangInstanceIdentifier current) {
+        final HashSet<Object> values = new HashSet<>();
+        addValues(values, node, path, current, QNameWithPredicate.ROOT);
+        return values;
     }
 
-    private void addValues(final Set<Object> values, final Optional<? extends NormalizedNode<?, ?>> optDataNode,
+    private void addValues(final Set<Object> values, final NormalizedNode<?, ?> node,
             final Iterable<QNameWithPredicate> path, final YangInstanceIdentifier current,
             final QNameWithPredicate previousQName) {
-
-        if (!optDataNode.isPresent()) {
-            return;
-        }
-        final NormalizedNode<?, ?> node = optDataNode.get();
         if (node instanceof ValueNode) {
             values.add(node.getValue());
             return;
@@ -426,11 +412,10 @@ public final class LeafRefValidatation {
                     .getChild(pathArgument);
 
             if (child.isPresent()) {
-                addValues(values, child, nextLevel(path), current, qnameWithPredicate);
+                addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
             } else {
                 for (final ChoiceNode choiceNode : getChoiceNodes(dataContainerNode)) {
-                    addValues(values, Optional.of(choiceNode), path, current,
-                            qnameWithPredicate);
+                    addValues(values, choiceNode, path, current, qnameWithPredicate);
                 }
             }
 
@@ -444,10 +429,10 @@ public final class LeafRefValidatation {
                             .getChild(pathArgument);
 
                     if (child.isPresent()) {
-                        addValues(values, child, nextLevel(path), current, qnameWithPredicate);
+                        addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
                     } else {
                         for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
-                            addValues(values, Optional.of(choiceNode), path, current, qnameWithPredicate);
+                            addValues(values, choiceNode, path, current, qnameWithPredicate);
                         }
                     }
                 }
@@ -458,11 +443,8 @@ public final class LeafRefValidatation {
                 while (predicates.hasNext()) {
                     final QNamePredicate predicate = predicates.next();
                     final QName identifier = predicate.getIdentifier();
-                    final LeafRefPath predicatePathKeyExpression = predicate
-                            .getPathKeyExpression();
-
-                    final Set<?> pathKeyExprValues = getPathKeyExpressionValues(
-                            predicatePathKeyExpression, current);
+                    final LeafRefPath predicatePathKeyExpression = predicate.getPathKeyExpression();
+                    final Set<?> pathKeyExprValues = getPathKeyExpressionValues(predicatePathKeyExpression, current);
 
                     keyValues.put(identifier, pathKeyExprValues);
                 }
@@ -473,10 +455,10 @@ public final class LeafRefValidatation {
                                 .getChild(pathArgument);
 
                         if (child.isPresent()) {
-                            addValues(values, child, nextLevel(path), current, qnameWithPredicate);
+                            addValues(values, child.get(), nextLevel(path), current, qnameWithPredicate);
                         } else {
                             for (final ChoiceNode choiceNode : getChoiceNodes(mapEntryNode)) {
-                                addValues(values, Optional.of(choiceNode),  path, current, qnameWithPredicate);
+                                addValues(values, choiceNode,  path, current, qnameWithPredicate);
                             }
                         }
                     }
@@ -509,18 +491,9 @@ public final class LeafRefValidatation {
 
     private Set<?> getPathKeyExpressionValues(final LeafRefPath predicatePathKeyExpression,
             final YangInstanceIdentifier current) {
-
-        final Optional<NormalizedNode<?, ?>> parent = findParentNode(tree.getRootNode().getDataAfter(), current);
-        final Iterable<QNameWithPredicate> predicatePathExpr = predicatePathKeyExpression.getPathFromRoot();
-        final Iterable<QNameWithPredicate> predicatePath = nextLevel(predicatePathExpr);
-
-        final Set<Object> values = new HashSet<>();
-        // FIXME: this null check does not look right
-        if (parent != null) {
-            addValues(values, parent, predicatePath, null, QNameWithPredicate.ROOT);
-        }
-
-        return values;
+        return findParentNode(tree.getRootNode().getDataAfter(), current)
+                .map(parent -> computeValues(parent, nextLevel(predicatePathKeyExpression.getPathFromRoot()), null))
+                .orElse(ImmutableSet.of());
     }
 
     private static Optional<NormalizedNode<?, ?>> findParentNode(