1
2
3
4
5
6
7 package net.sf.tacos.model.impl;
8
9 import java.util.Collection;
10 import java.util.Collections;
11 import java.util.HashMap;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Map;
15 import net.sf.tacos.model.ITreeContentProvider;
16 import org.apache.commons.beanutils.PropertyUtils;
17
18
19
20
21
22
23
24
25
26
27
28 public class BeanWithChildrenTreeContentProvider implements ITreeContentProvider {
29
30 private Object root;
31 private String childProperty;
32 private Map parents;
33
34 public BeanWithChildrenTreeContentProvider(Object root, String childProperty) {
35 this.root = root;
36 this.childProperty = childProperty;
37 buildParents();
38 }
39
40 private void buildParents() {
41 parents = new HashMap();
42 appendChildren(root, parents);
43 }
44
45 private void appendChildren(Object base, Map map) {
46 for (Iterator iter = getChildren(base).iterator(); iter.hasNext();) {
47 Object object = iter.next();
48 map.put(object, base);
49 appendChildren(object, map);
50 }
51 }
52
53 public Collection getChildren(Object parentElement) {
54 try {
55 Collection children = (Collection) PropertyUtils.getProperty(parentElement, childProperty);
56 if (children == null)
57 children = Collections.emptyList();
58 return children;
59 } catch (Exception e) {
60 throw new RuntimeException("Error getting property", e);
61 }
62 }
63
64 public boolean hasChildren(Object parentElement) {
65 return getChildren(parentElement).size() > 0;
66 }
67
68 public Object getParent(Object childElement) {
69 return parents.get(childElement);
70 }
71
72 public List getElements() {
73 return Collections.singletonList(root);
74 }
75
76 }