1 4 package nl.justobjects.pushlet.core; 5 6 import nl.justobjects.pushlet.util.Log; 7 8 14 public class Dispatcher implements Protocol, ConfigDefs { 15 16 private static Dispatcher instance; 17 18 static { 19 String className = Config.getProperty(DISPATCHER_CLASS); 22 23 try { 24 instance = (Dispatcher) Class.forName(className).newInstance(); 25 Log.info("Dispatcher created className=" + className); 26 } catch (Throwable t) { 27 Log.fatal("Cannot instantiate Dispatcher className=" + className, t); 28 } 29 } 30 31 32 private Dispatcher() { 33 } 34 35 36 public static Dispatcher getInstance() { 37 return instance; 38 } 39 40 41 public synchronized void broadcast(Event event) { 42 Session[] sessions = getSessions(); 44 45 for (int i = 0; i < sessions.length; i++) { 47 48 if (sessions[i] == null) { 50 break; 51 } 52 sessions[i].getSubscriber().onEvent((Event) event.clone()); 53 } 54 } 55 56 57 public synchronized void multicast(Event event) { 58 Session[] sessions = getSessions(); 60 61 Event clonedEvent = null; 63 Subscription subscription = null; 64 Subscriber subscriber = null; 65 for (int i = 0; i < sessions.length; i++) { 66 67 if (sessions[i] == null) { 69 break; 70 } 71 72 subscriber = sessions[i].getSubscriber(); 73 74 if ((subscription = subscriber.match(event)) != null) { 77 clonedEvent = (Event) event.clone(); 79 80 clonedEvent.setField(P_SUBSCRIPTION_ID, subscription.getId()); 82 if (subscription.getLabel() != null) { 83 event.setField(P_SUBSCRIPTION_LABEL, subscription.getLabel()); 84 } 85 86 subscriber.onEvent(clonedEvent); 87 } 88 } 89 90 } 91 92 93 public synchronized void unicast(Event event, String aSessionId) { 94 Session session = SessionManager.getInstance().getSession(aSessionId); 96 if (session == null) { 97 Log.warn("unicast: session with id=" + aSessionId + " does not exist"); 98 return; 99 } 100 101 session.getSubscriber().onEvent((Event) event.clone()); 103 } 104 105 106 public void start() { 107 Log.info("Dispatcher started"); 108 } 109 110 111 public void stop() { 112 Log.info("Dispatcher stopped: broadcast abort to all subscribers"); 114 broadcast(new Event(E_ABORT)); 115 } 116 117 private Session[] getSessions() { 118 return SessionManager.getInstance().getSnapshot(); 119 } 120 } 121 122 201 | Popular Tags |