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

com.alterioncorp.jpa.entitygraphbuilder.RelationshipNode Maven / Gradle / Ivy

The newest version!
package com.alterioncorp.jpa.entitygraphbuilder;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.EntityGraph;
import javax.persistence.Subgraph;

class RelationshipNode {

	private final String value;
	private final Set children;

	public RelationshipNode(String value) {
		if (value == null) {
			throw new IllegalArgumentException("value is required");
		}
		this.value = value;
		this.children = new HashSet();
	}

	public String getValue() {
		return value;
	}

	public Set getChildren() {
		return children;
	}
	
	boolean merge(RelationshipNode that) {
		
		if (! this.equals(that)) {
			return false;
		}

		this.mergeChildren(that.children);
		return true;
	}
	
	private void mergeChildren(Set childrenToMerge) {
		for (RelationshipNode childToMerge : childrenToMerge) {
			if (this.children.contains(childToMerge)) {
				this.getChild(childToMerge.value).mergeChildren(childToMerge.children);
			}
			else {
				this.children.add(childToMerge);
			}
		}
	}
	
	public RelationshipNode getChild(String value) {
		for (RelationshipNode child : children) {
			if (child.getValue().equals(value)) {
				return child;
			}
		}
		return null;
	}
	
	@Override
	public int hashCode() {
		return value.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		RelationshipNode other = (RelationshipNode) obj;
		return this.value.equals(other.value);
	}

	void addToGraph(EntityGraph graph) {
		if (children.isEmpty()) {
			graph.addAttributeNodes(value);
		}
		else {
			Subgraph subgraph = graph.addSubgraph(value);
			for (RelationshipNode child : children) {
				child.addToSubgraph(subgraph);
			}
		}
	}
	
	private void addToSubgraph(Subgraph graph) {
		if (children.isEmpty()) {
			graph.addAttributeNodes(value);
		}
		else {
			Subgraph subgraph = graph.addSubgraph(value);
			for (RelationshipNode child : children) {
				child.addToSubgraph(subgraph);
			}
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy