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