1 19 package org.netbeans.modules.xml.core.lib; 20 21 import java.util.*; 22 23 import org.openide.util.*; 24 25 30 public abstract class LookupManager { 31 32 private static final Map handles = new WeakHashMap(); 34 35 private Handle handle = null; 36 37 38 42 45 public LookupManager () { 46 } 47 48 49 52 protected final void register (Class clazz) { 53 if ( handle != null ) { 54 throw new IllegalStateException (); 55 } 56 synchronized (handles) { 57 handle = (Handle)handles.get (clazz); 58 if ( handle == null ) { 59 handles.put (clazz, handle = new Handle (clazz)); 60 } 61 } 62 handle.register (this); 63 } 64 65 66 70 72 protected final Collection getResult() { 73 return handle.getInstances(); 74 } 75 76 77 79 protected abstract void removedFromResult (Collection removed); 80 81 83 protected abstract void addedToResult (Collection added); 84 85 86 90 93 private static final class Handle implements LookupListener { 94 95 private final Class clazz; 96 private Lookup.Result lookupResult = null; 97 private Collection lastResult = null; 98 private final Set lms = new WeakSet(300); 100 104 106 private Handle (Class clazz) { 107 this.clazz = clazz; 108 } 109 110 112 public void register (LookupManager lm) { 113 synchronized (lms) { 114 lms.add (lm); 115 } 116 } 117 118 119 123 125 private Lookup.Result getLookupResult () { 126 if ( lookupResult == null ) { 127 lookupResult = (Lookup.getDefault()).lookup (new Lookup.Template (clazz)); 128 lookupResult.addLookupListener (this); 129 } 130 return lookupResult; 131 } 132 133 135 public void resultChanged (LookupEvent evt) { 136 Collection currentResult = getLookupResult().allInstances(); 137 138 Collection removed = new HashSet (lastResult); 139 removed.removeAll (currentResult); 140 Collection added = new HashSet (currentResult); 141 added.removeAll (lastResult); 142 143 if ( ( removed.isEmpty() == false ) || 144 ( added.isEmpty() == false ) ) { 145 synchronized (lms) { 146 Iterator it = lms.iterator(); 147 while (it.hasNext()) { 148 LookupManager lm = (LookupManager)it.next(); 149 if ( removed.isEmpty() == false ) { 150 lm.removedFromResult(removed); 151 } 152 if ( added.isEmpty() == false ) { 153 lm.addedToResult(added); 154 } 155 } 156 } 157 } 158 159 lastResult = currentResult; 160 } 161 162 164 public Collection getInstances() { 165 if (lastResult == null) { 169 lastResult = getLookupResult().allInstances(); 170 } 171 return lastResult; 172 } 173 174 } 176 } 177 | Popular Tags |