// collect the children of this entity and put them in order
Collection rels = findRelationships(layoutEntity, AS_SOURCE, relationships);
List children = new ArrayList ();
for (Iterator iter = rels.iterator(); iter.hasNext();) {
InternalRelationship layoutRel = (InternalRelationship) iter.next();
InternalNode childEntity = layoutRel.getDestination();
children.add(childEntity);
}
if (comparator != null) {
Collections.sort(children, comparator);
} else {
// sort the children by level, then by number of descendents, then by number of children
// TODO: SLOW
Collections.sort(children, new Comparator () {
public int compare(Object o1, Object o2) {
InternalNode node1 = (InternalNode) o1;
InternalNode node2 = (InternalNode) o2;
int [] numDescendentsAndLevel1 = new int [2];
int [] numDescendentsAndLevel2 = new int [2];
int level1 = numDescendentsAndLevel1[NUM_LEVELS_INDEX];
int level2 = numDescendentsAndLevel2[NUM_LEVELS_INDEX];
if (level1 == level2) {
getNumDescendentsAndLevel(node1, relationships, numDescendentsAndLevel1);
getNumDescendentsAndLevel(node2, relationships, numDescendentsAndLevel2);
int numDescendents1 = numDescendentsAndLevel1[NUM_DESCENDENTS_INDEX];
int numDescendents2 = numDescendentsAndLevel2[NUM_DESCENDENTS_INDEX];
if (numDescendents1 == numDescendents2) {
int numChildren1 = getNumChildren(node1, relationships);
int numChildren2 = getNumChildren(node1, relationships);
return numChildren2 - numChildren1;
} else {
return numDescendents2 - numDescendents1;
}
} else {
return level2 - level1;
}
//return getNumChildren(node2, relationships) - getNumChildren(node1, relationships);
}
});
}
// map children to this parent, and vice versa
for (Iterator iter = children.iterator(); iter.hasNext();) {
InternalNode childEntity = (InternalNode) iter.next();
int childEntityIndex = indexOfInternalNode(entities, childEntity);
if (!childrenLists[i].contains(childEntity)) {
childrenLists[i].add(childEntity);
}
if (!parentLists[childEntityIndex].contains(layoutEntity)) {
parentLists[childEntityIndex].add(layoutEntity);
}
}
for (Iterator iter = children.iterator(); iter.hasNext();) {
InternalNode childEntity = (InternalNode) iter.next();
int childEntityIndex = indexOfInternalNode(entities, childEntity);
buildTreeRecursively(childEntity, childEntityIndex, weight + 1, entities, relationships);
}
}