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