1 package org.smartcomps.twister.common.event;
2
3 import org.smartcomps.twister.common.util.logger.Logger;
4 import org.smartcomps.twister.common.configuration.CommonConfiguration;
5 import org.smartcomps.twister.common.lifecycle.LifecycleAwareResource;
6 import org.smartcomps.twister.common.lifecycle.LifecycleException;
7
8 import java.util.*;
9
10 /***
11 * A simple event manager that forwards events to registered
12 * listeners. Listeners can be registered either through a property
13 * file or using the <code>register(Listener listener)</code> method.
14 * @see TwisterListener
15 */
16 public class EventManager implements LifecycleAwareResource {
17
18 private static Logger log = Logger.getLogger(EventManager.class);
19 private static Collection listeners;
20
21 public void create() throws LifecycleException {
22 listeners = new ArrayList();
23 try {
24 List listenerNames = CommonConfiguration.getEventListeners();
25 for (int m = 0; m < listenerNames.size(); m++) {
26 String listener = (String) listenerNames.get(m);
27 Class listenerClass = Class.forName(listener);
28 if (TwisterListener.class.isAssignableFrom(listenerClass)) {
29 listeners.add(listenerClass.newInstance());
30 } else {
31 log.warn("Class " + listener + " doesn't implement the TwisterListener interface, it can't " +
32 "be registered as a listener.");
33 }
34 }
35 } catch (ClassNotFoundException e) {
36 log.warn("Could not find a class declared as an event listener", e);
37 } catch (InstantiationException e) {
38 log.warn("Could not instantiate a class declared as an event listener", e);
39 } catch (IllegalAccessException e) {
40 log.warn("Could not access a class declared as an event listener", e);
41 }
42 }
43
44 public void start() throws LifecycleException { }
45
46 public void stop() throws LifecycleException { }
47
48 public void destroy() throws LifecycleException {
49 listeners = null;
50 }
51
52 public static void register(TwisterListener listener) {
53 getListeners().add(listener);
54 }
55
56 public static void fireError(Exception error) {
57 for (Iterator listenersIter = getListeners().iterator(); listenersIter.hasNext();) {
58 TwisterListener listener = (TwisterListener) listenersIter.next();
59 try {
60 listener.errorEvent(error);
61 } catch (Throwable t) {
62 // The caller of this method should not get any trouble if a listener fails.
63 log.warn("Listener of class " + listener.getClass() + " failed to receive exception " + error);
64 }
65 }
66 }
67
68 private static Collection getListeners() {
69 return listeners;
70 }
71
72 }
This page was automatically generated by Maven