private void addSimilarNodes(
     SearchFieldTreeNode parent,
     SearchableFieldChoiceItem[] choices,
     int startAt,
     MiniLocalization localizationToUse) {
   String label = parent.toString();
   int index = startAt;
   while (index < choices.length && choices[index].getSpec().getLabel().equals(label)) {
     SearchableFieldChoiceItem choice = choices[index];
     parent.add(new SearchFieldTreeNode(choice, localizationToUse));
     ++index;
   }
 }
  private SearchFieldTreeNode[] getIndexesOfReusableDropdownChildren(SearchFieldTreeNode parent) {
    Vector reusableDropdownNodes = new Vector();
    for (int i = 0; i < parent.getChildCount(); ++i) {
      SearchFieldTreeNode child = (SearchFieldTreeNode) parent.getChildAt(i);
      if (!child.isSearchableFieldChoiceItemNode()) continue;
      SearchableFieldChoiceItem choice = child.getChoiceItem();
      FieldSpec spec = choice.getSpec();
      if (spec.getReusableChoicesCodes().length == 0) continue;
      reusableDropdownNodes.add(child);
    }

    return (SearchFieldTreeNode[]) reusableDropdownNodes.toArray(new SearchFieldTreeNode[0]);
  }
 private void differentiateChildNodes(SearchFieldTreeNode parent) {
   SearchFieldTreeNode[] needDifferentiation = getIndexesOfReusableDropdownChildren(parent);
   for (int i = 0; i < needDifferentiation.length; ++i) {
     SearchFieldTreeNode child = needDifferentiation[i];
     SearchableFieldChoiceItem choice = child.getChoiceItem();
     FieldSpec spec = choice.getSpec();
     String reusableListLabels = "";
     for (int level = 0; level < spec.getReusableChoicesCodes().length; ++level) {
       if (level > 0) reusableListLabels += ", ";
       reusableListLabels += spec.getReusableChoicesCodes()[level];
     }
     child.setLabel(child.toString() + " (" + reusableListLabels + ")");
   }
 }
  public TreeNode asTree(MiniLocalization localizationToUse) {
    Collections.sort(allChoices, new ChoiceItemSorterByLabelTagType(localizationToUse));
    mergeSimilarDropdowns();
    sortAllChoicesWithinDropdowns();

    SearchFieldTreeNode root = new SearchFieldTreeNode("", localizationToUse);
    SearchableFieldChoiceItem[] choices = getChoicesAsArray();
    int index = 0;
    while (index < choices.length) {
      String label = choices[index].getSpec().getLabel();
      SearchFieldTreeNode node = new SearchFieldTreeNode(label, localizationToUse);
      node.add(new SearchFieldTreeNode(choices[index], localizationToUse));
      addSimilarNodes(node, choices, index + 1, localizationToUse);
      index += node.getChildCount();
      node = pullUpIfOnlyOneChild(node);
      differentiateChildNodes(node);
      root.add(node);
    }

    return root;
  }
 private SearchFieldTreeNode pullUpIfOnlyOneChild(SearchFieldTreeNode node) {
   if (node.getChildCount() == 1) node = (SearchFieldTreeNode) node.getChildAt(0);
   return node;
 }