01: /*
02: * Copyright 2006 Davide Deidda
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: /*
18: * EventDispatcher.java
19: *
20: * Created on 10 aprile 2005, 16.50
21: */
22:
23: package it.biobytes.ammentos.event;
24:
25: import java.util.concurrent.*;
26: import java.util.logging.*;
27:
28: /**
29: *
30: * @author davide
31: */
32: public class EventDispatcher implements Runnable {
33: private LinkedBlockingQueue<PersistenceEvent> m_events; // Events queue
34: private CopyOnWriteArrayList<PersistenceListener> m_listeners;// Event listeners
35: private Logger m_logger = Logger.getLogger("ammentos");
36:
37: /** Creates a new instance of EventDispatcher */
38: public EventDispatcher() {
39: m_events = new LinkedBlockingQueue<PersistenceEvent>();
40: m_listeners = new CopyOnWriteArrayList<PersistenceListener>();
41: }
42:
43: public void dispatchEvent(PersistenceEvent e) {
44: // If there's no registered listeners the event is ignored
45: if (!m_listeners.isEmpty()) {
46: try {
47: m_events.put(e);
48: } catch (InterruptedException ex) {
49: }
50: }
51: }
52:
53: private void dispatchNextEvent() {
54: PersistenceEvent e = null;
55: try {
56: e = m_events.take();
57: } catch (InterruptedException ex) {
58: }
59:
60: if (e != null) {
61: switch (e.getType()) {
62: case OBJECT_SAVED:
63: dispatchSaveEvent(e);
64: break;
65: case OBJECT_DELETED:
66: dispatchDeleteEvent(e);
67: break;
68: }
69: }
70: }
71:
72: private void dispatchSaveEvent(PersistenceEvent e) {
73: m_logger.info("dispatching save event");
74: for (PersistenceListener l : m_listeners) {
75: l.objectSaved(e);
76: }
77: }
78:
79: private void dispatchDeleteEvent(PersistenceEvent e) {
80: m_logger.info("dispatching delete event");
81: for (PersistenceListener l : m_listeners) {
82: l.objectDeleted(e);
83: }
84: }
85:
86: public void addPersistenceListener(PersistenceListener l) {
87: m_listeners.add(l);
88: }
89:
90: public void removePersistenceListener(PersistenceListener l) {
91: m_listeners.remove(l);
92: }
93:
94: public void run() {
95: while (true)
96: dispatchNextEvent();
97: }
98:
99: }
|