(no commit message)
[utils] / support / src / main / java / org / wamblee / io / DirectoryMonitor.java
1 /*
2  * Copyright 2006 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */ 
16
17 package org.wamblee.io;
18
19 import java.io.File;
20 import java.io.FileFilter;
21 import java.util.ArrayList;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 /**
31  * Monitors a directory for changes. 
32  */
33 public class DirectoryMonitor {
34     
35     private static final Log LOG = LogFactory.getLog(DirectoryMonitor.class);
36     
37     public static interface Listener { 
38         void fileChanged(File aFile); 
39         void fileCreated(File aFile); 
40         void fileDeleted(File aFile);
41     };
42     
43     private File _directory;
44     private FileFilter _filter; 
45     private Listener _listener;
46     private Map<File,Date> _contents; 
47     
48     public DirectoryMonitor(File aDirectory, FileFilter aFilefilter, Listener aListener) {
49         _directory = aDirectory;
50         _filter = aFilefilter; 
51         _listener = aListener;
52         _contents = new HashMap<File,Date>();
53     }
54     
55     public void poll() {
56         LOG.info("Polling " + _directory);
57         Map<File,Date> newContents = new HashMap<File,Date>();
58         File[] files = _directory.listFiles(_filter);
59         for (File file: files) { 
60             if ( _contents.containsKey(file)) { 
61                 Date oldDate = _contents.get(file);
62                 if (file.lastModified() != oldDate.getTime()) { 
63                     _listener.fileChanged(file);
64                 } else { 
65                     // No change. 
66                 }
67                 _contents.remove(file);
68                 newContents.put(file, new Date(file.lastModified()));
69             } else { 
70                 _listener.fileCreated(file);
71                 newContents.put(file, new Date(file.lastModified()));
72             }
73         }
74         for (File file: _contents.keySet()) { 
75             _listener.fileDeleted(file);
76         }
77         _contents = newContents;
78     }
79
80 }