package uk.ac.vamsas.client.simpleclient; public abstract class WatcherElement { private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(VamsasFileWatcherElement.class); protected FileWatcher watcher = null; protected WatcherCallBack handler = null; /** * set this to false to stop the thread */ private boolean watchForChange = true; /** * true when the handler is being called for this watcher */ protected boolean handlerCalled = false; public WatcherElement(WatcherCallBack handler) { this.handler = handler; } /** * will instruct watcher to stop and wait around for one WATCH_SLEEP * before returning. If no thread is running then it returns immediately. */ public void haltWatch() { if (log.isDebugEnabled()) log.debug("haltWatch on "+watcher.getSubject()); // set the flag to skip this watch element. watchForChange=false; endWatch(); // watcher=null; } /** * called by haltWatch before * clearing the FileWatcher reference. * */ protected abstract void endWatch(); /** * called to generate the watcher object * by enableWatch and in doWatch * */ protected abstract void initWatch(); /** * implemented for debug information purposes. * @return Informative string about what the watcher is watching */ protected abstract String getSubject(); /** * must be called by implementations of * enablewatch */ protected void enableWatch() { watchForChange=true; initWatch(); if (log.isDebugEnabled()) log.debug("enableWatch returning on "+getSubject()); } /** * Originally from the uk.ac.vamsas.test.simpleclient.ArchiveClient method * @return true if the handler was called for a changeEvent */ public boolean doWatch() { if (!watchForChange || handler==null) return false; if (watcher==null) initWatch(); // somehow not done the first time handlerCalled=false; Lock doclock=null; try { doclock=watcher.getChangedState(); } catch (Exception e) { log.error("Whilst watching "+watcher.getSubject(), e); } if (doclock==null) return false; handlerCalled=true; if (log.isDebugEnabled()) log.debug("Triggering watchEvent for change on "+watcher.getSubject()); boolean finish=!handler.handleWatchEvent(this, doclock); doclock=null; // TODO: check that lock should really be released rather than dereferenced if (finish) haltWatch(); else enableWatch(); handlerCalled=false; return true; } /** * @return the handler */ public WatcherCallBack getHandler() { return handler; } /** * @return the handlerCalled */ public boolean isHandlerCalled() { return handlerCalled; } /** * * @return true if watcher is enabled */ public boolean isWatchEnabled() { return watchForChange; } /** * @param handler the handler to set */ public void setHandler(WatcherCallBack handler) { this.handler = handler; } /** * @return the watcher */ public FileWatcher getWatcher() { return watcher; } }