use of java.nio.file.WatchKey in project smarthome by eclipse.
the class WatchQueueReader method stopWatchService.
public synchronized void stopWatchService(AbstractWatchService service) {
if (watchService != null) {
List<WatchKey> keys = new LinkedList<>();
for (WatchKey key : keyToService.keySet()) {
if (keyToService.get(key) == service) {
keys.add(key);
}
}
if (keys.size() == keyToService.size()) {
try {
watchService.close();
} catch (IOException e) {
logger.warn("Cannot deactivate folder watcher", e);
}
watchService = null;
keyToService.clear();
registeredKeys.clear();
hashes.clear();
futures.values().forEach(keyFutures -> keyFutures.values().forEach(future -> future.cancel(true)));
futures.clear();
} else {
for (WatchKey key : keys) {
key.cancel();
keyToService.remove(key);
registeredKeys.remove(key);
hashes.remove(service);
Map<Path, @Nullable ScheduledFuture<?>> keyFutures = futures.remove(key);
if (keyFutures != null) {
keyFutures.values().forEach(future -> future.cancel(true));
}
}
}
}
}
use of java.nio.file.WatchKey in project hazelcast by hazelcast.
the class StreamFilesP method drainWatcherEvents.
/**
* @return false, if the watcher should be closed
*/
private boolean drainWatcherEvents() {
final ILogger logger = getLogger();
// poll with blocking only when there is no other work to do
final WatchKey key;
try {
key = (currentFile == null && eventQueue.isEmpty()) ? watcher.poll(1, SECONDS) : watcher.poll();
} catch (InterruptedException e) {
return false;
}
if (key == null) {
if (!Files.exists(watchedDirectory)) {
logger.info("Directory " + watchedDirectory + " does not exist, stopped watching");
return false;
}
return true;
}
for (WatchEvent<?> event : key.pollEvents()) {
final WatchEvent.Kind<?> kind = event.kind();
final Path fileName = ((WatchEvent<Path>) event).context();
final Path filePath = watchedDirectory.resolve(fileName);
if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
if (glob.matches(fileName) && belongsToThisProcessor(fileName) && !Files.isDirectory(filePath)) {
logFine(logger, "Will open file to read new content: %s", filePath);
eventQueue.add(filePath);
}
} else if (kind == ENTRY_DELETE) {
logFinest(logger, "File was deleted: %s", filePath);
fileOffsets.remove(filePath);
} else if (kind == OVERFLOW) {
logger.warning("Detected OVERFLOW in " + watchedDirectory);
} else {
throw new JetException("Unknown kind of WatchEvent: " + kind);
}
}
if (!key.reset()) {
logger.info("Watch key is invalid. Stopping watcher.");
return false;
}
return true;
}
use of java.nio.file.WatchKey in project pravega by pravega.
the class FileModificationEventWatcher method run.
@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
WatchKey watchKey = null;
WatchService watchService = null;
try {
watchService = FileSystems.getDefault().newWatchService();
log.debug("Done creating watch service for watching file at path: {}", this.watchedFilePath);
String fileName = getWatchedFileName();
Path directoryPath = getWatchedDirectory();
log.debug("Directory being watched is {}", directoryPath);
assert directoryPath != null;
directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
log.debug("Registered the watch for the file: {}", this.watchedFilePath);
isWatchRegistered = true;
while (!Thread.currentThread().isInterrupted()) {
try {
watchKey = retrieveWatchKeyFrom(watchService);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logException(e);
// Allow thread to exit.
}
if (watchKey != null) {
Optional<WatchEvent<?>> modificationDetectionEvent = watchKey.pollEvents().stream().filter(event -> event.context().toString().contains(fileName)).findAny();
if (modificationDetectionEvent.isPresent()) {
log.info("Detected that the file [{}] has modified", this.watchedFilePath);
callback.accept(modificationDetectionEvent.get());
}
boolean isKeyValid = watchKey.reset();
log.debug("Done resetting watch key.");
if (!isKeyValid) {
log.info("No longer watching file [{}]", this.watchedFilePath);
break;
}
}
if (!loopContinuously) {
break;
}
}
} catch (IOException e) {
logException(e);
throw new RuntimeException(e);
} finally {
if (watchKey != null) {
watchKey.cancel();
}
if (watchService != null) {
try {
watchService.close();
} catch (IOException e) {
log.warn("Error closing watch service", e);
}
}
}
log.info("Thread [{}], watching for modifications in file [{}] exiting,", getName(), this.watchedFilePath);
}
use of java.nio.file.WatchKey in project tutorials by eugenp.
the class DirectoryWatcherExample method main.
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
}
key.reset();
}
watchService.close();
}
use of java.nio.file.WatchKey in project chatty by chatty.
the class FileWatcher method run.
@Override
public void run() {
for (; ; ) {
WatchKey key;
/**
* Wait for a modification to occur.
*/
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
/**
* Wait a bit for events to accumulate. This prevents several
* consecutive modifications (e.g. several writes or change of file
* modification date) from all triggering the listener.
*/
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
Path changedFile = directory.resolve(fileName);
if (changedFile.equals(file)) {
listener.fileChanged();
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
Aggregations