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

org.nqcx.tree.TreeBuilder Maven / Gradle / Ivy

/* 
 * Copyright 2012-2013 nqcx.org All right reserved. This software is the 
 * confidential and proprietary information of nqcx.org ("Confidential 
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with nqcx.org.
 */

package org.nqcx.tree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * tree builder
 * 
 * @author huangbaoguang 2013-3-27 下午5:02:48
 * 
 * @param 
 */
public class TreeBuilder implements Serializable {

	private static final long serialVersionUID = -3889238862426715948L;

	private final Map> nodeMap = new LinkedHashMap>();

	public void put(O o) {
		if (o == null || containsNodeId(o.getNodeId()))
			return;

		// 放入列表
		nodeMap.put(o.getNodeId(), new LinkedNode(o));
		// 关联上级
		relateParentNode(nodeMap.get(o.getNodeId()));
		// 关联下级
		relateChildNodes(nodeMap.get(o.getNodeId()));
	}

	public O get(Object nodeId) {
		return getNode(nodeId) != null ? getNode(nodeId).getObject() : null;
	}

	private void relateParentNode(LinkedNode dataNode) {
		LinkedNode parent = getNode(dataNode.getParentNodeId());
		if (parent != null) {
			parent.addChildNode(dataNode);
			dataNode.setParentNode(parent);
		}
	}

	private void relateChildNodes(LinkedNode dataNode) {
		// 关联下级
		Set nodeIds = nodeMap.keySet();
		for (Object nodeId : nodeIds) {
			LinkedNode dataNodeTmp = nodeMap.get(nodeId);
			if (dataNode.getNodeId().equals(dataNodeTmp.getParentNodeId())) {
				dataNode.addChildNode(dataNodeTmp);
				dataNodeTmp.setParentNode(dataNode);
			}
		}

	}

	/**
	 * @author naqichuan Dec 15, 2013
	 * @param nodeId
	 * @return
	 */
	public boolean containsNodeId(Object nodeId) {
		return nodeMap.containsKey(nodeId);
	}

	public void clean() {
		nodeMap.clear();
	}

	public int size() {
		return nodeMap.size();
	}

	public boolean isEmpty() {
		return size() == 0;
	}

	public LinkedNode getNode(Object nodeId) {
		return nodeMap.get(nodeId);
	}

	public List> getNodesByParentId(String parentId) {
		if (parentId == null)
			return null;

		List> list = new ArrayList>();
		Set nodeIds = nodeMap.keySet();
		for (Object nodeId : nodeIds) {
			LinkedNode dataNodeTmp = nodeMap.get(nodeId);
			if (parentId.equals(dataNodeTmp.getParentNodeId())) {
				list.add(dataNodeTmp);
			}
		}
		return list;
	}
}