001: package org.objectweb.celtix.bus.busimpl;
002:
003: import java.util.*;
004: import java.util.logging.Level;
005: import java.util.logging.Logger;
006:
007: import org.objectweb.celtix.Bus;
008: import org.objectweb.celtix.BusEvent;
009: import org.objectweb.celtix.BusEventCache;
010: import org.objectweb.celtix.BusEventFilter;
011: import org.objectweb.celtix.BusEventListener;
012: import org.objectweb.celtix.BusException;
013: import org.objectweb.celtix.common.i18n.Message;
014: import org.objectweb.celtix.common.logging.LogUtils;
015:
016: public class BusEventProcessor {
017: private static final Logger LOG = LogUtils
018: .getL7dLogger(BusEventProcessor.class);
019: protected Bus theBus;
020: protected List<BusEventListenerInfo> listenerList;
021: protected BusEventCache cache;
022:
023: public BusEventProcessor(Bus bus, BusEventCache eventCache) {
024: theBus = bus;
025: listenerList = new ArrayList<BusEventListenerInfo>();
026: cache = eventCache;
027: }
028:
029: public void addListener(BusEventListener l, BusEventFilter filter)
030: throws BusException {
031: if (l == null) {
032: throw new BusException(new Message(
033: "Listener can't be null", LOG));
034: }
035:
036: synchronized (listenerList) {
037: listenerList.add(new BusEventListenerInfo(l, filter));
038: }
039: }
040:
041: public void removeListener(BusEventListener l) throws BusException {
042: boolean found = false;
043: BusEventListenerInfo li;
044: synchronized (listenerList) {
045: for (Iterator<BusEventListenerInfo> i = listenerList
046: .iterator(); i.hasNext();) {
047: li = i.next();
048: if (li.listener == l) {
049: i.remove();
050: found = true;
051: }
052: }
053: }
054:
055: if (!found) {
056: throw new BusException(
057: new Message(
058: "Error while removing listener. Specified listener is not found.",
059: LOG));
060: }
061: }
062:
063: public void processEvent(BusEvent e) {
064: if (e == null) {
065: return;
066: }
067:
068: BusEventListenerInfo li;
069: boolean eventProcessed = false;
070:
071: synchronized (listenerList) {
072: for (int i = 0; i < listenerList.size(); i++) {
073: li = (BusEventListenerInfo) listenerList.get(i);
074:
075: if ((li.filter == null)
076: || (li.filter.isEventEnabled(e))) {
077: eventProcessed = true;
078:
079: try {
080: li.listener.processEvent(e);
081: } catch (BusException ex) {
082: //NOTE now just log the exception and not throw the exception to bus
083: LOG.log(Level.WARNING,
084: "PROCESS_EVENT_FAILURE_MSG",
085: new Object[] { li.getClass().getName(),
086: e.getID(), ex });
087: }
088: }
089: }
090: }
091:
092: if (!eventProcessed) {
093: cache.addEvent(e);
094: }
095: }
096:
097: class BusEventListenerInfo {
098: BusEventListener listener;
099: BusEventFilter filter;
100:
101: public BusEventListenerInfo(BusEventListener l, BusEventFilter f) {
102: listener = l;
103: filter = f;
104: }
105: }
106: }
|