try {
Path root = Paths.get(path);
WatchService watcher = root.getFileSystem().newWatchService();
register(root, watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
final WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
@SuppressWarnings("unchecked")
Path item = ((WatchEvent<Path>) event).context();
Path dir = keys.get(key);
File file = new File(dir.toString(), item.toString()).getAbsoluteFile();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
if (file.isDirectory()) {
//recursive registration of sub-directories
register(Paths.get(dir.toString(), item.toString()), watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
task.updateProgress(++count);
} else {
URI context = getTargetContext(file);
log.debug("Importing '{}'...", file.getAbsolutePath());
task.updateMessage("importing...");
task.updateDetailMessage(TASK_DETAIL_PATH, file.getAbsolutePath());
task.updateDetailMessage(TASK_DETAIL_CONTEXT, context.stringValue());
if (execImport(file, context)) {
log.info("Sucessfully imported file '{}' into {}", file.getAbsolutePath(), context.stringValue());
try {
//delete the imported file
log.debug("Deleting {}...", file.getAbsolutePath());
file.delete();
} catch (Exception ex) {
log.error("Error deleing {}: {}", file.getAbsolutePath(), ex.getMessage());
}
}
task.updateProgress(++count);
task.updateMessage("watching...");
task.updateDetailMessage(TASK_DETAIL_PATH, path);
task.removeDetailMessage(TASK_DETAIL_CONTEXT);
}
} else if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind()) && Files.isDirectory(item)) {
//TODO: unregister deleted directories?
task.updateProgress(++count);
}
}
if (!key.reset()) {
// exit loop if the key is not valid
// e.g. if the directory was deleted
break;
}
}