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