blob: 95581e35aba7338b0184ddc9dd1f59faf3572a12 [file] [log] [blame]
tomd7356722014-08-26 01:07:39 -07001package org.onlab.onos.event;
2
3import org.slf4j.Logger;
tomd7356722014-08-26 01:07:39 -07004
5import java.util.Set;
6import java.util.concurrent.CopyOnWriteArraySet;
7
8import static com.google.common.base.Preconditions.checkArgument;
9import static com.google.common.base.Preconditions.checkNotNull;
tom5f38b3a2014-08-27 23:50:54 -070010import static org.slf4j.LoggerFactory.getLogger;
tomd7356722014-08-26 01:07:39 -070011
12/**
tom96dfcab2014-08-28 09:26:03 -070013 * Base implementation of an event sink and a registry capable of tracking
14 * listeners and dispatching events to them as part of event sink processing.
tomd7356722014-08-26 01:07:39 -070015 */
tom96dfcab2014-08-28 09:26:03 -070016public class AbstractListenerRegistry<E extends Event, L extends EventListener<E>>
tomd7356722014-08-26 01:07:39 -070017 implements EventSink<E> {
18
tom5f38b3a2014-08-27 23:50:54 -070019 private final Logger log = getLogger(getClass());
tomd7356722014-08-26 01:07:39 -070020
21 private final Set<L> listeners = new CopyOnWriteArraySet<>();
Thomas Vachuska7d693f52014-10-21 19:17:57 -070022 private volatile boolean shutdown = false;
tomd7356722014-08-26 01:07:39 -070023
24 /**
25 * Adds the specified listener.
26 *
27 * @param listener listener to be added
28 */
29 public void addListener(L listener) {
30 checkNotNull(listener, "Listener cannot be null");
31 listeners.add(listener);
32 }
33
34 /**
35 * Removes the specified listener.
36 *
37 * @param listener listener to be removed
38 */
39 public void removeListener(L listener) {
40 checkNotNull(listener, "Listener cannot be null");
41 checkArgument(listeners.remove(listener), "Listener not registered");
42 }
43
44 @Override
45 public void process(E event) {
46 for (L listener : listeners) {
47 try {
48 listener.event(event);
tom19bf4212014-08-29 13:08:29 -070049 } catch (Exception error) {
tomd7356722014-08-26 01:07:39 -070050 reportProblem(event, error);
51 }
52 }
53 }
54
tomb36046e2014-08-27 00:22:24 -070055 /**
56 * Reports a problem encountered while processing an event.
57 *
58 * @param event event being processed
59 * @param error error encountered while processing
60 */
61 protected void reportProblem(E event, Throwable error) {
Thomas Vachuska7d693f52014-10-21 19:17:57 -070062 if (!shutdown) {
63 log.warn("Exception encountered while processing event " + event, error);
64 }
tomd7356722014-08-26 01:07:39 -070065 }
66
Thomas Vachuska7d693f52014-10-21 19:17:57 -070067 /**
68 * Prepares the registry for normal operation.
69 */
70 public void activate() {
71 shutdown = false;
72 }
73
74 /**
75 * Prepares the registry for shutdown.
76 */
77 public void deactivate() {
78 shutdown = true;
79 }
80
81
tomd7356722014-08-26 01:07:39 -070082}