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