1 package at.ac.tuwien.sbc.valesriegler.xvsm;
3 import java.io.Serializable;
6 import java.util.Timer;
7 import java.util.TimerTask;
8 import java.util.concurrent.atomic.AtomicBoolean;
10 import org.mozartspaces.notifications.Notification;
11 import org.mozartspaces.notifications.NotificationListener;
12 import org.mozartspaces.notifications.Operation;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
18 * The SpaceListener provides the {@link NotificationListener} interface.
20 * In {@link SpaceListener#getEntries()} a method for reading the entities, that are normally expected from the notification,
21 * must be supplied. Thus, it's possible in {@link SpaceListener#startHandlingAbsenceOfNotifications()} to start a timer and to
22 * execute the actions, which are normally triggered by the notification, with space objects read from {@link SpaceListener#getEntries()}.
23 * If {@link SpaceListener#lookAround} is true the timer periodically checks if the corresponding {@link AbstractXVSMConnector#timeOflastOperation} is old enough (= the agent is idle for some time)
24 * and possibly executes the action as a result.
26 * @author Gregor Riegler <gregor DOT riegler AT gmail DOT com>
29 public abstract class SpaceListener implements NotificationListener {
30 private static final Logger log = LoggerFactory
31 .getLogger(SpaceListener.class);
33 protected boolean lookAround = true;
34 protected long timeout = 3000;
35 protected AtomicBoolean inNotification = new AtomicBoolean(true);
38 public void entryOperationFinished(Notification arg0, Operation arg1,
39 List<? extends Serializable> entries) {
40 synchronized (AbstractXVSMConnector.lockObject) {
41 AbstractXVSMConnector.timeOflastOperation.set(new Date().getTime());
43 log.info("I am running a notification now!");
44 inNotification.set(true);
45 onEntriesWritten(entries);
46 } catch (Exception e) {
47 // e.printStackTrace();
53 abstract List<? extends Serializable> getEntries() throws Exception;
55 abstract void onEntriesWritten(List<? extends Serializable> entries)
58 public void startHandlingAbsenceOfNotifications() {
59 if(!lookAround) return;
60 AbstractXVSMConnector.timeOflastOperation.set(new Date().getTime() + 3500);
62 Timer timer = new Timer();
64 timer.schedule(new SpaceTask(), 3000, 3000);
67 class SpaceTask extends TimerTask {
71 if(new Date().getTime()-timeout <= AbstractXVSMConnector.timeOflastOperation.get()) {
74 synchronized(AbstractXVSMConnector.lockObject) {
76 AbstractXVSMConnector.timeOflastOperation.set(new Date().getTime());
77 log.info("Timer task running");
79 List<? extends Serializable> entries = getEntries();
80 if(entries.size() != 0) {
81 log.info("{} entries in timer", entries.size());
82 inNotification.set(false);
83 onEntriesWritten(entries);
85 log.info("No entries in timer!");
87 } catch (Exception e) {
88 log.info(e.getMessage());
89 // e.printStackTrace();