| 1 | package be.nikiroo.utils.ui; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.util.ArrayList; |
| 5 | import java.util.Collections; |
| 6 | import java.util.Comparator; |
| 7 | import java.util.List; |
| 8 | |
| 9 | import javax.swing.tree.DefaultMutableTreeNode; |
| 10 | import javax.swing.tree.MutableTreeNode; |
| 11 | |
| 12 | public abstract class DataTree<E> { |
| 13 | private DataNode<E> data; |
| 14 | |
| 15 | public DataNode<E> loadData() throws IOException { |
| 16 | return this.data = extractData(); |
| 17 | } |
| 18 | |
| 19 | public DataNode<E> getRoot() { |
| 20 | return getRoot(null); |
| 21 | } |
| 22 | |
| 23 | public DataNode<E> getRoot(String filter) { |
| 24 | return filterNode(data, filter); |
| 25 | } |
| 26 | |
| 27 | protected abstract DataNode<E> extractData() throws IOException; |
| 28 | |
| 29 | // filter cannot be null nor empty |
| 30 | protected abstract boolean checkFilter(String filter, E userData); |
| 31 | |
| 32 | protected boolean checkFilter(DataNode<E> node, String filter) { |
| 33 | if (filter == null || filter.isEmpty()) { |
| 34 | return true; |
| 35 | } |
| 36 | |
| 37 | if (checkFilter(filter, node.getUserData())) |
| 38 | return true; |
| 39 | |
| 40 | for (DataNode<E> child : node.getChildren()) { |
| 41 | if (checkFilter(child, filter)) |
| 42 | return true; |
| 43 | } |
| 44 | |
| 45 | return false; |
| 46 | } |
| 47 | |
| 48 | protected void sort(List<String> values) { |
| 49 | Collections.sort(values, new Comparator<String>() { |
| 50 | @Override |
| 51 | public int compare(String o1, String o2) { |
| 52 | return ("" + o1).compareToIgnoreCase("" + o2); |
| 53 | } |
| 54 | }); |
| 55 | } |
| 56 | |
| 57 | // note: we always send TAHT node, but filter children |
| 58 | private DataNode<E> filterNode(DataNode<E> source, String filter) { |
| 59 | List<DataNode<E>> children = new ArrayList<DataNode<E>>(); |
| 60 | for (DataNode<E> child : source.getChildren()) { |
| 61 | if (checkFilter(child, filter)) { |
| 62 | children.add(filterNode(child, filter)); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | return new DataNode<E>(children, source.getUserData()); |
| 67 | } |
| 68 | |
| 69 | // TODO: not in this class: |
| 70 | |
| 71 | public void loadInto(DefaultMutableTreeNode root, String filter) { |
| 72 | DataNode<E> filtered = getRoot(filter); |
| 73 | for (DataNode<E> child : filtered.getChildren()) { |
| 74 | root.add(nodeToNode(child)); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | private MutableTreeNode nodeToNode(DataNode<E> node) { |
| 79 | // TODO: node.toString |
| 80 | DefaultMutableTreeNode otherNode = new DefaultMutableTreeNode( |
| 81 | node.toString()); |
| 82 | for (DataNode<E> child : node.getChildren()) { |
| 83 | otherNode.add(nodeToNode(child)); |
| 84 | } |
| 85 | |
| 86 | return otherNode; |
| 87 | } |
| 88 | } |