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