Clean up DataTreeCandidateNode contract
[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.base.Strings;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Maps;
17 import java.util.Arrays;
18 import java.util.Iterator;
19 import java.util.Map;
20 import java.util.Optional;
21 import org.eclipse.jdt.annotation.NonNull;
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
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         throw new UnsupportedOperationException("Utility class should not be instantiated");
39     }
40
41     public static Optional<NormalizedNode<?, ?>> findNode(final YangInstanceIdentifier rootPath,
42             final NormalizedNode<?, ?> rootNode, final YangInstanceIdentifier childPath) {
43         final Optional<YangInstanceIdentifier> relativePath = childPath.relativeTo(rootPath);
44         return relativePath.isPresent() ? findNode(rootNode, relativePath.get()) : Optional.empty();
45     }
46
47     public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent,
48             final Iterable<PathArgument> relativePath) {
49         requireNonNull(parent, "Parent must not be null");
50         requireNonNull(relativePath, "Relative path must not be null");
51
52         Optional<NormalizedNode<?, ?>> currentNode = parent;
53         final Iterator<PathArgument> pathIterator = relativePath.iterator();
54         while (currentNode.isPresent() && pathIterator.hasNext()) {
55             currentNode = getDirectChild(currentNode.get(), pathIterator.next());
56         }
57         return currentNode;
58     }
59
60     public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent,
61             final PathArgument... relativePath) {
62         return findNode(parent, Arrays.asList(relativePath));
63     }
64
65     public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent,
66             final Iterable<PathArgument> relativePath) {
67         return findNode(Optional.ofNullable(parent), relativePath);
68     }
69
70     public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent,
71             final SchemaPath relativePath) {
72         checkArgument(!relativePath.isAbsolute(), "%s is not a relative path", relativePath);
73         return findNode(Optional.ofNullable(parent), Iterables.transform(relativePath.getPathFromRoot(),
74             NodeIdentifier::new));
75     }
76
77     public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent,
78             final PathArgument... relativePath) {
79         return findNode(parent, Arrays.asList(relativePath));
80     }
81
82     public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree,
83             final YangInstanceIdentifier path) {
84         requireNonNull(tree, "Tree must not be null");
85         requireNonNull(path, "Path must not be null");
86
87         return findNode(Optional.of(tree), path.getPathArguments());
88     }
89
90     @SuppressWarnings({ "unchecked", "rawtypes" })
91     public static Optional<NormalizedNode<?, ?>> getDirectChild(final NormalizedNode<?, ?> node,
92             final PathArgument pathArg) {
93         if (node instanceof LeafNode<?> || node instanceof LeafSetEntryNode<?>) {
94             return Optional.empty();
95         } else if (node instanceof DataContainerNode<?>) {
96             return (Optional) ((DataContainerNode<?>) node).getChild(pathArg);
97         } else if (node instanceof MapNode && pathArg instanceof NodeIdentifierWithPredicates) {
98             return (Optional) ((MapNode) node).getChild((NodeIdentifierWithPredicates) pathArg);
99         } else if (node instanceof LeafSetNode<?> && pathArg instanceof NodeWithValue) {
100             return (Optional) ((LeafSetNode<?>) node).getChild((NodeWithValue) pathArg);
101         }
102         return Optional.empty();
103     }
104
105     /**
106      * Convert a data subtree under a node into a human-readable string format.
107      *
108      * @param node Data subtree root
109      * @return String containing a human-readable form of the subtree.
110      */
111     public static String toStringTree(final NormalizedNode<?, ?> node) {
112         final StringBuilder builder = new StringBuilder();
113         toStringTree(builder, node, 0);
114         return builder.toString();
115     }
116
117     private static void toStringTree(final StringBuilder builder, final NormalizedNode<?, ?> node, final int offset) {
118         final String prefix = Strings.repeat(" ", offset);
119
120         builder.append(prefix).append(toStringTree(node.getIdentifier()));
121         if (node instanceof NormalizedNodeContainer<?, ?, ?>) {
122             final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) node;
123
124             builder.append(" {\n");
125             for (NormalizedNode<?, ?> child : container.getValue()) {
126                 toStringTree(builder, child, offset + STRINGTREE_INDENT);
127             }
128
129             builder.append(prefix).append('}');
130         } else {
131             builder.append(' ').append(node.getValue());
132         }
133         builder.append('\n');
134     }
135
136     private static String toStringTree(final PathArgument identifier) {
137         if (identifier instanceof NodeIdentifierWithPredicates) {
138             return identifier.getNodeType().getLocalName()
139                 + ((NodeIdentifierWithPredicates) identifier).getKeyValues().values();
140         } else if (identifier instanceof AugmentationIdentifier) {
141             return "augmentation";
142         } else {
143             return identifier.getNodeType().getLocalName();
144         }
145     }
146
147     /**
148      * Find duplicate NormalizedNode instances within a subtree. Duplicates are those, which compare
149      * as equal, but do not refer to the same object.
150      *
151      * @param node A normalized node subtree, may not be null
152      * @return A Map of NormalizedNode/DuplicateEntry relationships.
153      */
154     public static Map<NormalizedNode<?, ?>, DuplicateEntry> findDuplicates(final @NonNull NormalizedNode<?, ?> node) {
155         return Maps.filterValues(DuplicateFinder.findDuplicates(node), input -> !input.getDuplicates().isEmpty());
156     }
157 }