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