Commit | Line | Data |
---|---|---|
a917f100 NR |
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> { | |
e5f04731 | 13 | protected DataNode<E> data; |
a917f100 NR |
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 | } | |
a917f100 | 68 | } |