use of java.nio.file.WatchKey in project Gargoyle by callakrsos.
the class FileUtilTest method watchTest.
@Test
public void watchTest() throws IOException {
File file = new File("c:\\someDir");
file.mkdirs();
WatchService newWatchService = FileSystems.getDefault().newWatchService();
WatchKey register = file.toPath().register(newWatchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watch Service Registered ..");
while (true) {
try {
System.out.println("start");
WatchKey key = newWatchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
@SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
if (key == ENTRY_MODIFY && fileName.toString().equals("DirectoryWatchDemo.java")) {
System.out.println("My source file has changed!!!");
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
} catch (InterruptedException e) {
break;
}
}
System.out.println("end ");
}
use of java.nio.file.WatchKey in project OpenGrok by OpenGrok.
the class RuntimeEnvironment method startWatchDogService.
/**
* Starts a watch dog service for a directory. It automatically reloads the
* AuthorizationFramework if there was a change in <b>real-time</b>.
* Suitable for plugin development.
*
* You can control start of this service by a configuration parameter
* {@link Configuration#authorizationWatchdogEnabled}
*
* @param directory root directory for plugins
*/
public void startWatchDogService(File directory) {
stopWatchDogService();
if (directory == null || !directory.isDirectory() || !directory.canRead()) {
LOGGER.log(Level.INFO, "Watch dog cannot be started - invalid directory: {0}", directory);
return;
}
LOGGER.log(Level.INFO, "Starting watchdog in: {0}", directory);
watchDogThread = new Thread(new Runnable() {
@Override
public void run() {
try {
watchDogWatcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get(directory.getAbsolutePath());
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException {
// attach monitor
LOGGER.log(Level.FINEST, "Watchdog registering {0}", d);
d.register(watchDogWatcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return CONTINUE;
}
});
LOGGER.log(Level.INFO, "Watch dog started {0}", directory);
while (!Thread.currentThread().isInterrupted()) {
final WatchKey key;
try {
key = watchDogWatcher.take();
} catch (ClosedWatchServiceException x) {
break;
}
boolean reload = false;
for (WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
if (kind == ENTRY_CREATE) {
reload = true;
} else if (kind == ENTRY_DELETE) {
reload = true;
} else if (kind == ENTRY_MODIFY) {
reload = true;
}
}
if (reload) {
// experimental wait if file is being written right now
Thread.sleep(THREAD_SLEEP_TIME);
getAuthorizationFramework().reload();
}
if (!key.reset()) {
break;
}
}
} catch (InterruptedException | IOException ex) {
LOGGER.log(Level.FINEST, "Watchdog finishing (exiting)", ex);
Thread.currentThread().interrupt();
}
LOGGER.log(Level.FINER, "Watchdog finishing (exiting)");
}
}, "watchDogService");
watchDogThread.start();
}
use of java.nio.file.WatchKey in project hutool by looly.
the class WatchMonitor method registerPath.
/**
* 将指定路径加入到监听中
* @param path 路径
* @param maxDepth 递归下层目录的最大深度
* @return {@link WatchKey}
*/
private void registerPath(Path path, int maxDepth) {
try {
final WatchKey key = path.register(watchService, ArrayUtil.isEmpty(this.events) ? EVENTS_ALL : this.events);
watchKeyPathMap.put(key, path);
if (maxDepth > 1) {
// 遍历所有子目录并加入监听
Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), maxDepth, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
// 继续添加目录
registerPath(dir, 0);
return super.postVisitDirectory(dir, exc);
}
});
}
} catch (IOException e) {
if (e instanceof AccessDeniedException) {
// 对于禁止访问的目录,跳过监听
return;
}
throw new WatchException(e);
}
}
use of java.nio.file.WatchKey in project felix by apache.
the class Watcher method rescan.
// Implementation methods
// -------------------------------------------------------------------------
public void rescan() throws IOException {
for (WatchKey key : keys.keySet()) {
key.cancel();
}
keys.clear();
Files.walkFileTree(root, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FilteringFileVisitor());
}
use of java.nio.file.WatchKey in project felix by apache.
the class Watcher method processEvents.
public void processEvents() {
while (true) {
WatchKey key = watcher.poll();
if (key == null) {
break;
}
Path dir = keys.get(key);
if (dir == null) {
warn("Could not find key for " + key);
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
WatchEvent<Path> ev = (WatchEvent<Path>) event;
// Context for directory entry event is the file name of entry
Path name = ev.context();
Path child = dir.resolve(name);
debug("Processing event {} on path {}", kind, child);
if (kind == OVERFLOW) {
// rescan();
continue;
}
try {
if (kind == ENTRY_CREATE) {
if (Files.isDirectory(child)) {
// if directory is created, and watching recursively, then
// register it and its sub-directories
Files.walkFileTree(child, new FilteringFileVisitor());
} else if (Files.isRegularFile(child)) {
scan(child);
}
} else if (kind == ENTRY_MODIFY) {
if (Files.isRegularFile(child)) {
scan(child);
}
} else if (kind == ENTRY_DELETE) {
unscan(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
x.printStackTrace();
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
debug("Removing key " + key + " and dir " + dir + " from keys");
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
Aggregations