001: package desktop;
002:
003: import com.sun.syndication.feed.synd.SyndFeed;
004: import com.sun.syndication.feed.synd.SyndFeedImpl;
005: import com.sun.syndication.io.SyndFeedInput;
006: import com.sun.syndication.io.XmlReader;
007: import org.wings.event.*;
008:
009: import java.net.URL;
010: import java.util.*;
011:
012: public class Poller extends Timer {
013:
014: private List<PollerTask> pollerTasks = new ArrayList<PollerTask>();
015: private long pollingInterval = 60000;
016:
017: public long getPollingInterval() {
018: return pollingInterval;
019: }
020:
021: public void setPollingInterval(long pollingInterval) {
022: this .pollingInterval = pollingInterval;
023: }
024:
025: public synchronized void registerFeedUpdatedListener(String url,
026: FeedUpdatedListener listener) {
027: PollerTask pt = getPollerTask(url);
028:
029: if (pt != null)
030: pt.addListener(listener);
031: else {
032: pt = new PollerTask(url);
033: //pt.setUrl(url);
034: pt.addListener(listener);
035: pollerTasks.add(pt);
036: System.out.println("Listener Session: "
037: + listener.getSession().toString());
038:
039: listener.getSession().addExitListener(
040: new SessionExitListener(pt));
041: this .scheduleAtFixedRate(pt, 0, pollingInterval);
042: }
043: //run the poller immediately to have the feeds filled at startup
044: //pt.run();
045: }
046:
047: public synchronized void unregisterFeedUpdatedListener(String url,
048: FeedUpdatedListener listener) {
049: PollerTask pt = getPollerTask(url);
050:
051: if (pt == null) {
052: System.err
053: .println("Cannot unregister FeedUpdateListener because it doesn't exist");
054: return;
055: }
056:
057: pt.removeListener(listener);
058:
059: if (pt.getListeners().isEmpty()) {
060: System.out.println("Destroying listener for URL "
061: + pt.getUrl());
062: pt.cancel();
063:
064: pollerTasks.remove(pt);
065: }
066: }
067:
068: private PollerTask getPollerTask(String url) {
069: for (PollerTask pt : pollerTasks) {
070: if (pt.getUrl().equalsIgnoreCase(url))
071: return pt;
072: }
073: return null;
074: }
075:
076: private class SessionExitListener implements SExitListener {
077:
078: private PollerTask task;
079:
080: public SessionExitListener(PollerTask task) {
081: this .task = task;
082: }
083:
084: public void prepareExit(SExitEvent e) throws ExitVetoException {
085: System.out.println("Session "
086: + e.getSourceSession().toString() + " timed out.");
087: List<FeedUpdatedListener> listenersToRemove = new ArrayList<FeedUpdatedListener>();
088: for (FeedUpdatedListener ful : task.getListeners()) {
089: if (e.getSourceSession().equals(ful.getSession())) {
090: System.out.println("Unregistering Listener for "
091: + task.getUrl() + " from Session "
092: + ful.getSession());
093: listenersToRemove.add(ful);
094: }
095: }
096: for (FeedUpdatedListener ful : listenersToRemove) {
097: Poller.this.unregisterFeedUpdatedListener(
098: task.getUrl(), ful);
099: }
100: }
101: }
102: }
|