01 package biz.xsoftware.examples.timer;
02
03 import java.util.HashMap;
04 import java.util.Map;
05 import java.util.TimerTask;
06
07 import javax.swing.event.EventListenerList;
08
09 import biz.xsoftware.examples.advanced.ScheduleListener;
10
11 /**
12 * The SysUnderTest here is a Calendar which notifies users of a
13 * scheduled event.
14 */
15 public class CalendarServiceImpl implements CalendarService {
16
17 private TimerInterface timer;
18 private EventListenerList listenerList = new EventListenerList();
19 private Map<String, CalendarEvent> titleToEvent = new HashMap<String, CalendarEvent>();
20
21
22 /**
23 * @showcode
24 */
25 public CalendarServiceImpl(TimerInterface t) {
26 timer = t;
27 }
28 /* (non-Javadoc)
29 * @see biz.xsoftware.examples.timer2.CalendarService#addEvent(java.lang.String, long)
30 */
31 public void addEvent(String title, long delay) {
32 CalendarEvent evt = new CalendarEvent(title);
33 titleToEvent.put(title, evt);
34 timer.schedule(evt, delay);
35 }
36
37 /* (non-Javadoc)
38 * @see biz.xsoftware.examples.timer2.CalendarService#addScheduleListener(biz.xsoftware.examples.timer.ScheduleListener)
39 */
40 public void addScheduleListener(ScheduleListener l) {
41 listenerList.add(ScheduleListener.class, l);
42 }
43 /* (non-Javadoc)
44 * @see biz.xsoftware.examples.timer2.CalendarService#removeScheduleListener(biz.xsoftware.examples.timer.ScheduleListener)
45 */
46 public void removeScheduleListener(ScheduleListener l) {
47 listenerList.remove(ScheduleListener.class, l);
48 }
49 private class CalendarEvent extends TimerTask {
50
51 private String title;
52 /**
53 * @showcode
54 */
55 public CalendarEvent(String title) {
56 this.title = title;
57 }
58 /**
59 * @showcode
60 */
61 @Override
62 public void run() {
63 fireEventStarted(title);
64 }
65 }
66 /**
67 * @showcode
68 */
69 protected void fireEventStarted(String title) {
70 // Guaranteed to return a non-null array
71 Object[] listeners = listenerList.getListenerList();
72 // Process the listeners last to first, notifying
73 // those that are interested in this event
74 for (int i = listeners.length-2; i>=0; i-=2) {
75 if (listeners[i]==ScheduleListener.class) {
76 ((ScheduleListener)listeners[i+1]).eventStarted(title);
77 }
78 }
79 }
80 /* (non-Javadoc)
81 * @see biz.xsoftware.examples.timer2.CalendarService#cancelEvent(java.lang.String)
82 */
83 public void cancelEvent(String title) {
84 CalendarEvent event = titleToEvent.get(title);
85 timer.cancelTask(event);
86 }
87 }
|