1 19 20 21 package org.apache.cayenne.event; 22 23 import java.util.ArrayList ; 24 import java.util.Collection ; 25 import java.util.HashSet ; 26 import java.util.Iterator ; 27 import java.util.Map ; 28 import java.util.Set ; 29 import java.util.WeakHashMap ; 30 31 import org.apache.cayenne.event.EventManager.Dispatch; 32 import org.apache.cayenne.util.Invocation; 33 34 43 class DispatchQueue { 44 45 private Set subjectInvocations = new HashSet (); 46 private Map invocationsBySender = new WeakHashMap (); 47 48 52 synchronized void dispatchEvent(Dispatch dispatch) { 53 dispatchEvent(subjectInvocations, dispatch); 55 56 Object sender = dispatch.getSender(); 58 dispatchEvent(invocationsForSender(sender, false), dispatch); 59 } 60 61 synchronized void addInvocation(Invocation invocation, Object sender) { 62 if (sender == null) { 63 subjectInvocations.add(invocation); 64 } 65 else { 66 invocationsForSender(sender, true).add(invocation); 67 } 68 } 69 70 synchronized boolean removeInvocations(Object listener, Object sender) { 71 72 if (sender != null) { 74 return removeInvocations(invocationsForSender(sender, false), listener); 75 } 76 77 boolean didRemove = false; 78 79 didRemove = removeInvocations(subjectInvocations, listener); 81 82 Iterator sets = invocationsBySender.values().iterator(); 83 while (sets.hasNext()) { 84 Collection senderInvocations = (Collection ) sets.next(); 85 if (senderInvocations == null) { 86 continue; 87 } 88 89 Iterator it = senderInvocations.iterator(); 90 while (it.hasNext()) { 91 Invocation invocation = (Invocation) it.next(); 92 if (invocation.getTarget() == listener) { 93 it.remove(); 94 didRemove = true; 95 } 96 } 97 } 98 99 return didRemove; 100 } 101 102 private Collection invocationsForSender(Object sender, boolean create) { 103 Collection senderInvocations = (Collection ) invocationsBySender.get(sender); 104 if (create && senderInvocations == null) { 105 senderInvocations = new HashSet (); 106 invocationsBySender.put(sender, senderInvocations); 107 } 108 109 return senderInvocations; 110 } 111 112 private boolean removeInvocations(Collection invocations, Object listener) { 114 if (invocations == null || invocations.isEmpty()) { 115 return false; 116 } 117 118 boolean didRemove = false; 119 120 Iterator invocationsIt = invocations.iterator(); 121 while (invocationsIt.hasNext()) { 122 Invocation invocation = (Invocation) invocationsIt.next(); 123 if (invocation.getTarget() == listener) { 124 invocationsIt.remove(); 125 didRemove = true; 126 } 127 } 128 129 return didRemove; 130 } 131 132 private void dispatchEvent(Collection invocations, Dispatch dispatch) { 134 if (invocations == null || invocations.isEmpty()) { 135 return; 136 } 137 138 Iterator it = new ArrayList (invocations).iterator(); 141 while (it.hasNext()) { 142 Invocation invocation = (Invocation) it.next(); 143 144 if (!dispatch.fire(invocation)) { 147 invocations.remove(invocation); 148 } 149 } 150 } 151 } 152 | Popular Tags |