use of java.nio.file.ClosedWatchServiceException in project tomee by apache.
the class FileWatcher method watch.
public Closeable watch(final String folder) {
final File file = new File(folder);
if (!file.isDirectory()) {
throw new IllegalArgumentException(folder + " is not a directory");
}
try {
final AtomicBoolean again = new AtomicBoolean(true);
final Path path = file.getAbsoluteFile().toPath();
final WatchService watchService = path.getFileSystem().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
final Thread watcherThread = new Thread(new Runnable() {
@Override
public void run() {
while (again.get()) {
try {
// don't use take to not block forever
final WatchKey key = watchService.poll(1, TimeUnit.SECONDS);
if (key == null) {
continue;
}
for (final WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE && kind != StandardWatchEventKinds.ENTRY_MODIFY) {
continue;
}
final Path updatedPath = Path.class.cast(event.context());
if (kind == StandardWatchEventKinds.ENTRY_DELETE || updatedPath.toFile().isFile()) {
final String path = updatedPath.toString();
if (path.endsWith("___jb_tmp___") || path.endsWith("___jb_old___")) {
continue;
} else if (path.endsWith("~")) {
onChange(path.replace(File.pathSeparatorChar, '/').substring(0, path.length() - 1));
} else {
onChange(path.replace(File.pathSeparatorChar, '/'));
}
}
}
key.reset();
} catch (final InterruptedException e) {
Thread.interrupted();
again.set(false);
} catch (final ClosedWatchServiceException cwse) {
// ok, we finished there
}
}
}
});
watcherThread.setName("livereload-tomee-watcher(" + folder + ")");
watcherThread.start();
return new Closeable() {
@Override
public void close() throws IOException {
synchronized (this) {
for (final Session s : sessions) {
removeSession(s);
try {
s.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "container shutdowned"));
} catch (final Exception e) {
// ok: not important there
}
}
}
again.compareAndSet(true, false);
try {
watchService.close();
} catch (final IOException ioe) {
logger.warning("Error closing the watch service for " + folder + "(" + ioe.getMessage() + ")");
}
try {
watcherThread.join(TimeUnit.MINUTES.toMillis(1));
} catch (final InterruptedException e) {
Thread.interrupted();
}
}
};
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
}
Aggregations