All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.liferay.object.tree.Tree Maven / Gradle / Ivy

There is a newer version: 93.0.0
Show newest version
/**
 * SPDX-FileCopyrightText: (c) 2023 Liferay, Inc. https://liferay.com
 * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06
 */

package com.liferay.object.tree;

import com.liferay.object.tree.constants.TreeConstants;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @author Feliphe Marinho
 */
public class Tree {

	public Tree(Node rootNode) {
		this.rootNode = rootNode;
	}

	public List getAncestorEdges(long primaryKey) {
		Node node = getNode(primaryKey);

		if (node.isRoot()) {
			return Collections.emptyList();
		}

		List edges = new ArrayList<>();

		Node parentNode = node.getParentNode();

		edges.add(node.getEdge());

		while (!parentNode.isRoot()) {
			edges.add(parentNode.getEdge());

			parentNode = parentNode.getParentNode();
		}

		return edges;
	}

	public Node getNode(long primaryKey) {
		Node node = null;

		Iterator iterator = iterator();

		while (iterator.hasNext()) {
			node = iterator.next();

			if (node.getPrimaryKey() == primaryKey) {
				break;
			}
		}

		return node;
	}

	public Node getRootNode() {
		return rootNode;
	}

	public Iterator iterator() {
		return iterator(TreeConstants.ITERATOR_TYPE_BREADTH_FIRST);
	}

	public Iterator iterator(long primaryKey) {
		return new BreadthFirstIterator(getNode(primaryKey));
	}

	public Iterator iterator(String iteratorType) {
		if (Objects.equals(
				iteratorType, TreeConstants.ITERATOR_TYPE_BREADTH_FIRST)) {

			return new BreadthFirstIterator(rootNode);
		}
		else if (Objects.equals(
					iteratorType, TreeConstants.ITERATOR_TYPE_POST_ORDER)) {

			return new PostOrderIterator(rootNode);
		}

		return null;
	}

	protected final Node rootNode;

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy