1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
| import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The recursive file watcher monitors a folder (and its sub-folders).
*
* <p>The class walks through the file tree and registers to a watch to every sub-folder.
* For new folders, a new watch is registered, and stale watches are removed.
*
* <p>When a file event occurs, a timer is started to wait for the file operations
* to settle. It is reset whenever a new event occurs. When the timer times out,
* an event is thrown through the {@link WatchListener}.
*
* @author Philipp C. Heckel <philipp.heckel@gmail.com>
*/
public class RecursiveWatcher {
private static final Logger logger = Logger.getLogger(RecursiveWatcher.class.getSimpleName());
private Path root;
private List<Path> ignorePaths;
private int settleDelay;
private WatchListener listener;
private AtomicBoolean running;
private WatchService watchService;
private Thread watchThread;
private Map<Path, WatchKey> watchPathKeyMap;
private Timer timer;
public RecursiveWatcher(Path root, List<Path> ignorePaths, int settleDelay, WatchListener listener) {
this.root = root;
this.ignorePaths = ignorePaths;
this.settleDelay = settleDelay;
this.listener = listener;
this.running = new AtomicBoolean(false);
this.watchService = null;
this.watchThread = null;
this.watchPathKeyMap = new HashMap<Path, WatchKey>();
this.timer = null;
}
/**
* Starts the watcher service and registers watches in all of the sub-folders of
* the given root folder.
*
* <p><b>Important:</b> This method returns immediately, even though the watches
* might not be in place yet. For large file trees, it might take several seconds
* until all directories are being monitored. For normal cases (1-100 folders), this
* should not take longer than a few milliseconds.
* @throws java.io.IOException
*/
public void start() throws IOException {
watchService = FileSystems.getDefault().newWatchService();
watchThread = new Thread(new Runnable() {
@Override
public void run() {
running.set(true);
walkTreeAndSetWatches();
while (running.get()) {
try {
WatchKey watchKey = watchService.take();
watchKey.pollEvents(); // Take events, but don't care what they are!
watchKey.reset();
resetWaitSettlementTimer();
}
catch (InterruptedException | ClosedWatchServiceException e) {
running.set(false);
}
}
}
}, "Watcher");
watchThread.start();
}
public synchronized void stop() {
if (watchThread != null) {
try {
watchService.close();
running.set(false);
watchThread.interrupt();
}
catch (IOException e) {
// Don't care
}
}
}
private synchronized void resetWaitSettlementTimer() {
logger.log(Level.FINE, "File system events registered. Waiting {0}ms for settlement ....", settleDelay);
if (timer != null) {
timer.cancel();
timer = null;
}
timer = new Timer("WatchTimer");
timer.schedule(new TimerTask() {
@Override
public void run() {
logger.log(Level.INFO, "File system actions (on watched folders) settled. Updating watches ...");
walkTreeAndSetWatches();
unregisterStaleWatches();
fireListenerEvents();
}
}, settleDelay);
}
private synchronized void walkTreeAndSetWatches() {
logger.log(Level.INFO, "Registering new folders at watch service ...");
try {
Files.walkFileTree(root, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (ignorePaths.contains(dir)) {
return FileVisitResult.SKIP_SUBTREE;
}
else {
registerWatch(dir);
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
// Don't care
}
}
private synchronized void unregisterStaleWatches() {
Set<Path> paths = new HashSet<Path>(watchPathKeyMap.keySet());
Set<Path> stalePaths = new HashSet<Path>();
for (Path path : paths) {
if (!Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
stalePaths.add(path);
}
}
if (stalePaths.size() > 0) {
logger.log(Level.INFO, "Cancelling stale path watches ...");
for (Path stalePath : stalePaths) {
unregisterWatch(stalePath);
}
}
}
private synchronized void fireListenerEvents() {
if (listener != null) {
logger.log(Level.INFO, "- Firing watch event (watchEventsOccurred) ...");
listener.watchEventsOccurred();
}
}
private synchronized void registerWatch(Path dir) {
if (!watchPathKeyMap.containsKey(dir)) {
logger.log(Level.INFO, "- Registering " + dir);
try {
WatchKey watchKey = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW);
watchPathKeyMap.put(dir, watchKey);
}
catch (IOException e) {
// Don't care!
}
}
}
private synchronized void unregisterWatch(Path dir) {
WatchKey watchKey = watchPathKeyMap.get(dir);
if (watchKey != null) {
logger.log(Level.INFO, "- Cancelling " + dir);
watchKey.cancel();
watchPathKeyMap.remove(dir);
}
}
public interface WatchListener {
public void watchEventsOccurred();
}
} |
Partager