1 13 package com.tonbeller.wcf.tree; 14 15 import java.util.Comparator ; 16 import java.util.HashMap ; 17 import java.util.Map ; 18 import java.util.TreeMap ; 19 20 import org.apache.log4j.Logger; 21 22 26 public class CachingTreeModelDecorator extends TreeModelDecorator { 27 Object [] roots = null; 28 Map getParentMap; 29 Map getChildrenMap; 30 Map hasChildrenMap; 31 32 private static Logger logger = Logger.getLogger(CachingTreeModelDecorator.class); 33 36 public CachingTreeModelDecorator(TreeModel decoree) { 37 super(decoree); 38 getParentMap = new HashMap (); 39 getChildrenMap = new HashMap (); 40 hasChildrenMap = new HashMap (); 41 decoree.addTreeModelChangeListener(listener); 42 } 43 44 47 public CachingTreeModelDecorator(TreeModel decoree, Comparator nodeComparator) { 48 super(decoree); 49 getParentMap = new TreeMap (nodeComparator); 50 getChildrenMap = new TreeMap (nodeComparator); 51 hasChildrenMap = new TreeMap (nodeComparator); 52 decoree.addTreeModelChangeListener(listener); 53 } 54 55 58 TreeModelChangeListener listener = new TreeModelChangeListener() { 59 public void treeModelChanged(TreeModelChangeEvent e) { 60 logger.info("invalidating TreeModelCache"); 61 roots = null; 62 getParentMap.clear(); 63 getChildrenMap.clear(); 64 hasChildrenMap.clear(); 65 } 66 }; 67 68 public Object [] getRoots() { 69 if (roots == null) 70 roots = super.getRoots(); 71 return roots; 72 } 73 74 public boolean hasChildren(Object node) { 75 Boolean b = (Boolean ) hasChildrenMap.get(node); 76 if (b == null) { 77 b = new Boolean (super.hasChildren(node)); 78 hasChildrenMap.put(node, b); 79 } 80 return b.booleanValue(); 81 } 82 83 public Object [] getChildren(Object node) { 84 Object [] children = (Object []) getChildrenMap.get(node); 85 if (children == null) { 86 children = super.getChildren(node); 87 if (children == null) 88 children = new Object [0]; 89 getChildrenMap.put(node, children); 90 for (int i = 0; i < children.length; i++) 91 getParentMap.put(children[i], node); 92 } 93 return children; 94 } 95 96 public Object getParent(Object node) { 97 Object parent = getParentMap.get(node); 98 if (parent == null && !getParentMap.containsKey(node)) { 99 parent = super.getParent(node); 100 getParentMap.put(node, parent); 101 } 102 return parent; 103 } 104 105 } 106 | Popular Tags |