001    package org.nanocontainer.deployer;
002    
003    import org.apache.commons.vfs.FileObject;
004    import org.apache.commons.vfs.FileSystemException;
005    import org.picocontainer.Startable;
006    
007    /**
008     * Component that polls a folder for children at regular intervals.
009     * @author Aslak Hellesøy
010     * @version $Revision: 2343 $
011     */
012    public class FolderContentPoller implements Startable {
013        private FolderContentHandler folderContentHandler;
014        private FileObject folder;
015    
016        private Runnable poller = new Runnable() {
017            public void run() {
018                while (!Thread.interrupted()) {
019                    try {
020                        // Have to "close" the folder to invalidate child cache
021                        folder.close();
022                        FileObject[] currentChildren = folder.getChildren();
023                        folderContentHandler.setCurrentChildren(currentChildren);
024                        synchronized(FolderContentPoller.this) {
025                            FolderContentPoller.this.notify();
026                            FolderContentPoller.this.wait(2000);
027                        }
028                    } catch (FileSystemException e) {
029                        e.printStackTrace();
030                    } catch (InterruptedException e) {
031                        thread.interrupt();
032                    }
033                }
034            }
035        };
036        private Thread thread;
037        private boolean started = false;
038    
039    
040        public FolderContentPoller(FolderContentHandler folderChangeNotifier) {
041            this.folderContentHandler = folderChangeNotifier;
042            folder = folderChangeNotifier.getFolder();
043        }
044    
045        public void start() {
046            if(started) throw new IllegalStateException("Already started");
047            thread = new Thread(poller);
048            thread.start();
049            started = true;
050        }
051    
052        public void stop() {
053            if(!started) throw new IllegalStateException("Already stopped");
054            thread.interrupt();
055            started = true;
056        }
057    
058    }