2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.md.sal.dom.store.impl.tree;
10 import java.util.AbstractMap.SimpleEntry;
11 import java.util.Iterator;
14 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
15 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
17 import com.google.common.base.Optional;
19 public class TreeNodeUtils {
22 * Finds a node in tree
24 * @param tree Data Tree
25 * @param path Path to the node
26 * @return Optional with node if the node is present in tree, {@link Optional#absent()} otherwise.
29 public static <T extends StoreTreeNode<T>> Optional<T> findNode(final T tree, final InstanceIdentifier path) {
30 Optional<T> current = Optional.<T> of(tree);
31 Iterator<PathArgument> pathIter = path.getPath().iterator();
32 while (current.isPresent() && pathIter.hasNext()) {
33 current = current.get().getChild(pathIter.next());
39 * Finds a node or closest parent in the tree
41 * @param tree Data Tree
42 * @param path Path to the node
43 * @return Map.Entry Entry with key which is path to closest parent and value is parent node.
46 public static <T extends StoreTreeNode<T>> Map.Entry<InstanceIdentifier, T> findClosest(final T tree, final InstanceIdentifier path) {
47 Optional<T> parent = Optional.<T>of(tree);
48 Optional<T> current = Optional.<T> of(tree);
51 Iterator<PathArgument> pathIter = path.getPath().iterator();
52 while (current.isPresent() && pathIter.hasNext()) {
54 current = current.get().getChild(pathIter.next());
57 if(current.isPresent()) {
58 final InstanceIdentifier currentPath = new InstanceIdentifier(path.getPath().subList(0, nesting));
59 return new SimpleEntry<InstanceIdentifier,T>(currentPath,current.get());
61 // Nesting minus one is safe, since current is allways present when nesting = 0
62 // so this prat of code is never triggered, in cases nesting == 0;
63 final InstanceIdentifier parentPath = new InstanceIdentifier(path.getPath().subList(0, nesting - 1));
64 return new SimpleEntry<InstanceIdentifier,T>(parentPath,parent.get());