View Javadoc

1   /*
2    * BeanTreeContent.java
3    *
4    * Created on February 4, 2007, 12:54 PM
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   * A useful {@link ITreeContentProvider} that can recreate the tree structure
20   * using a root bean (of any type) and the property name that will return its
21   * children (a {@link Collection} of the same type).
22   * 
23   * This class is meant to be used for quickly prototyping trees. You're advised to
24   * create your own implementation in order to tweek performance issues.
25   * 
26   * @author andyhot
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  }