Select copyPolicy for each StatementSupport class
[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.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).getChild(pathArg);
124         } else if (node instanceof MapNode && pathArg instanceof NodeIdentifierWithPredicates) {
125             return (Optional) ((MapNode) node).getChild((NodeIdentifierWithPredicates) pathArg);
126         } else if (node instanceof LeafSetNode && pathArg instanceof NodeWithValue) {
127             return (Optional) ((LeafSetNode<?>) node).getChild((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 builder = new StringBuilder();
141         toStringTree(builder, node, 0);
142         return builder.toString();
143     }
144
145     private static void toStringTree(final StringBuilder builder, final NormalizedNode<?, ?> node, final int offset) {
146         final String prefix = " ".repeat(offset);
147
148         builder.append(prefix).append(toStringTree(node.getIdentifier()));
149         if (node instanceof NormalizedNodeContainer) {
150             final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) node;
151
152             builder.append(" {\n");
153             for (NormalizedNode<?, ?> child : container.getValue()) {
154                 toStringTree(builder, child, offset + STRINGTREE_INDENT);
155             }
156
157             builder.append(prefix).append('}');
158         } else {
159             builder.append(' ').append(node.getValue());
160         }
161         builder.append('\n');
162     }
163
164     private static String toStringTree(final PathArgument identifier) {
165         if (identifier instanceof NodeIdentifierWithPredicates) {
166             return identifier.getNodeType().getLocalName() + ((NodeIdentifierWithPredicates) identifier).values();
167         } else if (identifier instanceof AugmentationIdentifier) {
168             return "augmentation";
169         } else {
170             return identifier.getNodeType().getLocalName();
171         }
172     }
173 }