@Override
public void run()
{
while (alive)
{
WatchKey key;
try
{
key = watcher.take();
}
catch (ClosedWatchServiceException | InterruptedException e)
{
break;
}
List<WatchEvent<?>> pollEvents = key.pollEvents();
for (WatchEvent<?> event : pollEvents)
{
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW)
{
continue;
}
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path name = ev.context();
ResourceMonitorImpl resourceMonitor = keys.get(key);
if (resourceMonitor == null)
{
log.finest("WatchKey not recognized " + name + " - " + key.watchable() + "> " + kind);
continue;
}
Path resourcePath = resourceMonitor.getResourcePath();
Path child = resourcePath.resolve(name);
log.log(Level.FINE, String.format("%s: %s %s %s\n", event.kind().name(), child, key, keys.keySet()));
if (kind == ENTRY_CREATE)
{
try
{
if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
{
registerAll(child, resourceMonitor);
}
}
catch (IOException e)
{
log.log(Level.SEVERE, "Error while registering child directories", e);
}
resourceMonitor.onPathCreate(child);
}
else if (kind == ENTRY_DELETE)
{
resourceMonitor.onPathDelete(child);
}
else if (kind == ENTRY_MODIFY)
{
resourceMonitor.onPathModify(child);
}
}
if (!keys.containsKey(key))
{
// key is no longer available in the keys Map. Cancel it
key.cancel();
}
else
{
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid)
{
keys.remove(key);
}
}