1 package at.ac.tuwien.sbc.valesriegler.xvsm.spacehelpers;
3 import java.io.Serializable;
6 import java.util.Timer;
7 import java.util.TimerTask;
9 import at.ac.tuwien.sbc.valesriegler.xvsm.AbstractXVSMConnector;
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 at.ac.tuwien.sbc.valesriegler.xvsm.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 SpaceAction spaceAction;
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 spaceAction.inNotification.set(true);
45 spaceAction.onEntriesWritten(entries);
46 } catch (Exception e) {
47 // e.printStackTrace();
53 abstract List<? extends Serializable> getEntries() throws Exception;
55 public void startHandlingAbsenceOfNotifications() {
56 if(!lookAround) return;
57 AbstractXVSMConnector.timeOflastOperation.set(new Date().getTime() + 3500);
59 Timer timer = new Timer();
61 timer.schedule(new SpaceTask(), 3000, 3000);
64 class SpaceTask extends TimerTask {
68 if(new Date().getTime()-timeout <= AbstractXVSMConnector.timeOflastOperation.get()) {
71 synchronized(AbstractXVSMConnector.lockObject) {
73 AbstractXVSMConnector.timeOflastOperation.set(new Date().getTime());
74 log.info("Timer task running");
76 List<? extends Serializable> entries = getEntries();
77 if(entries.size() != 0) {
78 log.info("{} entries in timer", entries.size());
79 spaceAction.inNotification.set(false);
80 spaceAction.onEntriesWritten(entries);
82 log.info("No entries in timer!");
84 } catch (Exception e) {
85 log.info(e.getMessage());
86 // e.printStackTrace();