DataContainerChild is identified by NodeIdentifier
[yangtools.git] / data / yang-data-api / src / main / java / org / opendaylight / yangtools / yang / data / api / schema / NormalizedNodes.java
1 /*
2  * Copyright (c) 2014 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.api.schema;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Maps;
15 import java.util.Arrays;
16 import java.util.Map;
17 import java.util.Optional;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Descendant;
26
27 /**
28  * A set of utility methods for interacting with {@link NormalizedNode} objects.
29  */
30 @Beta
31 public final class NormalizedNodes {
32     private static final int STRINGTREE_INDENT = 4;
33
34     private NormalizedNodes() {
35         // Hidden on purpose
36     }
37
38     /**
39      * Find duplicate NormalizedNode instances within a subtree. Duplicates are those, which compare
40      * as equal, but do not refer to the same object.
41      *
42      * @param node A normalized node subtree, may not be null
43      * @return A Map of NormalizedNode/DuplicateEntry relationships.
44      */
45     public static Map<NormalizedNode, DuplicateEntry> findDuplicates(final @NonNull NormalizedNode node) {
46         return Maps.filterValues(DuplicateFinder.findDuplicates(node), input -> !input.getDuplicates().isEmpty());
47     }
48
49     public static Optional<NormalizedNode> findNode(final YangInstanceIdentifier rootPath,
50             final NormalizedNode rootNode, final YangInstanceIdentifier childPath) {
51         final var relativePath = childPath.relativeTo(rootPath);
52         return relativePath.isPresent() ? findNode(rootNode, relativePath.orElseThrow()) : Optional.empty();
53     }
54
55     public static Optional<NormalizedNode> findNode(final Optional<NormalizedNode> parent,
56             final Iterable<PathArgument> relativePath) {
57         final var pathIterator = requireNonNull(relativePath, "Relative path must not be null").iterator();
58         var currentNode = requireNonNull(parent, "Parent must not be null");
59         while (currentNode.isPresent() && pathIterator.hasNext()) {
60             currentNode = getDirectChild(currentNode.orElseThrow(), pathIterator.next());
61         }
62         return currentNode;
63     }
64
65     public static Optional<NormalizedNode> findNode(final Optional<NormalizedNode> parent,
66             final PathArgument pathArg) {
67         return parent.flatMap(node -> getDirectChild(node, pathArg));
68     }
69
70     public static Optional<NormalizedNode> findNode(final Optional<NormalizedNode> parent,
71             final PathArgument... relativePath) {
72         return findNode(parent, Arrays.asList(relativePath));
73     }
74
75     public static Optional<NormalizedNode> findNode(final @Nullable NormalizedNode parent,
76             final PathArgument pathArg) {
77         return parent == null ? Optional.empty() : getDirectChild(parent, pathArg);
78     }
79
80     public static Optional<NormalizedNode> findNode(final NormalizedNode parent,
81             final Iterable<PathArgument> relativePath) {
82         return findNode(Optional.ofNullable(parent), relativePath);
83     }
84
85     public static Optional<NormalizedNode> findNode(final NormalizedNode parent, final Descendant path) {
86         return findNode(Optional.ofNullable(parent),
87             Lists.transform(path.getNodeIdentifiers(), NodeIdentifier::new));
88     }
89
90     public static Optional<NormalizedNode> findNode(final NormalizedNode parent,
91             final PathArgument... relativePath) {
92         return findNode(parent, Arrays.asList(relativePath));
93     }
94
95     public static Optional<NormalizedNode> findNode(final NormalizedNode tree,
96             final YangInstanceIdentifier path) {
97         return findNode(Optional.of(requireNonNull(tree, "Tree must not be null")),
98             requireNonNull(path, "Path must not be null").getPathArguments());
99     }
100
101     public static Optional<NormalizedNode> getDirectChild(final NormalizedNode node,
102             final PathArgument pathArg) {
103         final NormalizedNode child;
104         if (node instanceof DataContainerNode dataContainer && pathArg instanceof NodeIdentifier nid) {
105             child = dataContainer.childByArg(nid);
106         } else if (node instanceof MapNode map && pathArg instanceof NodeIdentifierWithPredicates nip) {
107             child = map.childByArg(nip);
108         } else if (node instanceof LeafSetNode<?> leafSet && pathArg instanceof NodeWithValue<?> nwv) {
109             child = leafSet.childByArg(nwv);
110         } else {
111             // Anything else, including ValueNode
112             child = null;
113         }
114         return Optional.ofNullable(child);
115     }
116
117     /**
118      * Convert a data subtree under a node into a human-readable string format.
119      *
120      * @param node Data subtree root
121      * @return String containing a human-readable form of the subtree.
122      */
123     public static String toStringTree(final NormalizedNode node) {
124         final StringBuilder sb = new StringBuilder();
125         toStringTree(sb, node, 0);
126         return sb.toString();
127     }
128
129     private static void toStringTree(final StringBuilder sb, final NormalizedNode node, final int offset) {
130         final String prefix = " ".repeat(offset);
131         appendPathArgument(sb.append(prefix), node.getIdentifier());
132         if (node instanceof NormalizedNodeContainer<?> container) {
133             sb.append(" {\n");
134             for (var child : container.body()) {
135                 toStringTree(sb, child, offset + STRINGTREE_INDENT);
136             }
137             sb.append(prefix).append('}');
138         } else {
139             sb.append(' ').append(node.body());
140         }
141         sb.append('\n');
142     }
143
144     private static void appendPathArgument(final StringBuilder sb, final PathArgument arg) {
145         sb.append(arg.getNodeType().getLocalName());
146         if (arg instanceof NodeIdentifierWithPredicates nip) {
147             sb.append(nip.values());
148         }
149     }
150 }