Bundle: fix memory leak at init/reset
[fanfix.git] / ui / DataTree.java
CommitLineData
a917f100
NR
1package be.nikiroo.utils.ui;
2
3import java.io.IOException;
4import java.util.ArrayList;
5import java.util.Collections;
6import java.util.Comparator;
7import java.util.List;
8
9import javax.swing.tree.DefaultMutableTreeNode;
10import javax.swing.tree.MutableTreeNode;
11
12public 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}