use of java.nio.file.WatchEvent in project fabric8 by jboss-fuse.
the class FileWatcher method processEvents.
private void processEvents() {
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException e) {
return;
}
Path dir;
synchronized (keysMonitor) {
dir = keys.get(key);
}
if (dir == null) {
LOGGER.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);
LOGGER.debug("Processing event {} on path {}", kind, child);
if (kind == OVERFLOW) {
// rescan();
continue;
}
try {
if (kind == ENTRY_CREATE) {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
// if directory is created, and watching recursively, then
// register it and its sub-directories
Files.walkFileTree(child, new FilteringFileVisitor());
} else if (Files.isRegularFile(child, NOFOLLOW_LINKS)) {
scan(child);
}
} else if (kind == ENTRY_MODIFY) {
if (Files.isRegularFile(child, NOFOLLOW_LINKS)) {
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) {
LOGGER.debug("Removing key " + key + " and dir " + dir + " from keys");
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
use of java.nio.file.WatchEvent in project smarthome by eclipse.
the class WatchQueueReader method run.
@Override
public void run() {
try {
for (; ; ) {
WatchKey key;
try {
key = watchService.take();
} catch (InterruptedException exc) {
logger.info("Caught InterruptedException: {}", exc.getLocalizedMessage());
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
logger.warn("Found an event of kind 'OVERFLOW': {}. File system changes might have been missed.", event);
continue;
}
Path resolvedPath = resolvePath(key, event);
if (resolvedPath != null) {
// Process the event only when a relative path to it is resolved
AbstractWatchService service;
synchronized (this) {
service = keyToService.get(key);
}
if (service != null) {
File f = resolvedPath.toFile();
if (kind == ENTRY_MODIFY && f.isDirectory()) {
logger.trace("Skipping modification event for directory: {}", f);
} else {
if (kind == ENTRY_MODIFY) {
processModificationEvent(key, event, resolvedPath, service);
} else {
service.processWatchEvent(event, kind, resolvedPath);
}
}
if (kind == ENTRY_CREATE && f.isDirectory() && service.watchSubDirectories() && service.getWatchEventKinds(resolvedPath) != null) {
registerDirectoryInternal(service, service.getWatchEventKinds(resolvedPath), resolvedPath);
} else if (kind == ENTRY_DELETE) {
synchronized (this) {
WatchKey toCancel = null;
for (WatchKey k : registeredKeys.keySet()) {
if (registeredKeys.get(k).equals(resolvedPath)) {
toCancel = k;
break;
}
}
if (toCancel != null) {
registeredKeys.remove(toCancel);
keyToService.remove(toCancel);
toCancel.cancel();
}
forgetChecksum(service, resolvedPath);
Map<Path, @Nullable ScheduledFuture<?>> keyFutures = futures.get(key);
if (keyFutures != null) {
ScheduledFuture<?> future = keyFutures.remove(resolvedPath);
if (future != null) {
future.cancel(true);
}
}
}
}
}
}
}
key.reset();
}
} catch (Exception exc) {
logger.debug("ClosedWatchServiceException caught! {}. \n{} Stopping ", exc.getLocalizedMessage(), Thread.currentThread().getName());
return;
}
}
use of java.nio.file.WatchEvent in project smarthome by eclipse.
the class AbstractFileTransformationService method processFolderEvents.
/**
* Ensures that a modified or deleted cached files does not stay in the cache
*/
private void processFolderEvents() {
WatchKey key = watchService.poll();
if (key != null) {
for (WatchEvent<?> e : key.pollEvents()) {
if (e.kind() == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
@SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) e;
Path path = ev.context();
logger.debug("Refreshing transformation file '{}'", path);
for (String fileEntry : cachedFiles.keySet()) {
if (fileEntry.endsWith(path.toString())) {
cachedFiles.remove(fileEntry);
}
}
}
key.reset();
}
}
use of java.nio.file.WatchEvent in project ariADDna by StnetixDevTeam.
the class Consumer method checkOtherEvents.
/**
* find MOVE, CREATE, DELETE events
* bufferQueue processing
* wen we delete file the fileSystem generate ENTRY_DELETE and ENTRY_CREATE events but not in a strict order
* therefore we take a event from bufferQueue and fid a pair, the remove these events from queue
* if we did not find a pair
*/
private void checkOtherEvents() {
// collection for prepared events
List<Pair<Path, WatchEvent<?>>> doneList = new ArrayList<>();
for (Pair<Path, WatchEvent<?>> p : bufferQueue) {
if (p != null && !doneList.contains(p)) {
@SuppressWarnings("unchecked") WatchEvent<Path> event = (WatchEvent<Path>) p.getValue();
Path name = event.context();
final boolean[] isMoveEvent = { false };
WatchEvent.Kind<Path> from = event.kind();
WatchEvent.Kind<Path> to = from.equals(ENTRY_DELETE) ? ENTRY_CREATE : ENTRY_DELETE;
bufferQueue.forEach(e -> {
if (!doneList.contains(e)) {
WatchEvent<Path> ev = (WatchEvent<Path>) e.getValue();
Path newName = ev.context();
if (ev.kind().equals(to) && newName.equals(name)) {
if (from.equals(ENTRY_DELETE)) {
LOGGER.debug("defined MOVE event from {} to {}", p.getKey().resolve(name), e.getKey().resolve(name));
service.runEvents(new FileSystemWatchEvent(FileSystemWatchEvent.Type.MOVE, p.getKey().resolve(name), e.getKey().resolve(name)));
} else {
LOGGER.debug("defined MOVE event from {} to {}", e.getKey().resolve(name), p.getKey().resolve(name));
service.runEvents(new FileSystemWatchEvent(FileSystemWatchEvent.Type.MOVE, e.getKey().resolve(name), p.getKey().resolve(name)));
}
bufferQueue.remove(e);
doneList.add(e);
isMoveEvent[0] = true;
}
}
});
if (!isMoveEvent[0]) {
FileSystemWatchEvent.Type eventType = from.equals(ENTRY_CREATE) ? FileSystemWatchEvent.Type.CREATE : FileSystemWatchEvent.Type.DELETE;
if (from == ENTRY_CREATE) {
LOGGER.debug("defined CREATE event from {}", p.getKey().resolve(name));
try {
if (Files.isDirectory(p.getKey().resolve(name))) {
service.registerDirectories(p.getKey().resolve(name));
}
} catch (IOException x) {
LOGGER.trace("Cant register folder {}", x.getMessage());
}
} else if (from == ENTRY_DELETE) {
LOGGER.debug("defined DELETE event from {}", p.getKey().resolve(name));
}
service.runEvents(new FileSystemWatchEvent(eventType, p.getKey().resolve(name)));
isMoveEvent[0] = false;
}
}
bufferQueue.remove(p);
doneList.add(p);
}
// queue.clear();
bufferQueue.clear();
}
use of java.nio.file.WatchEvent in project rxjava-file by davidmoten.
the class FileObservable method from.
/**
* Returns an {@link Observable} of {@link WatchEvent}s from a
* {@link WatchService}.
*
* @param watchService
* WatchService to generate events from
* @param scheduler
* schedules polls of the watchService
* @param pollDuration
* duration of each poll
* @param pollDurationUnit
* time unit for the duration of each poll
* @param pollInterval
* interval between polls of the watchService
* @param pollIntervalUnit
* time unit for the interval between polls
* @param backpressureStrategy
* backpressures strategy to apply
* @return an observable of WatchEvents from watchService
*/
public static final Observable<WatchEvent<?>> from(WatchService watchService, Scheduler scheduler, long pollDuration, TimeUnit pollDurationUnit, long pollInterval, TimeUnit pollIntervalUnit, BackpressureStrategy backpressureStrategy) {
Preconditions.checkNotNull(watchService);
Preconditions.checkNotNull(scheduler);
Preconditions.checkNotNull(pollDurationUnit);
Preconditions.checkNotNull(backpressureStrategy);
Observable<WatchEvent<?>> o = Observable.create(new OnSubscribeWatchServiceEvents(watchService, scheduler, pollDuration, pollDurationUnit, pollInterval, pollIntervalUnit));
if (backpressureStrategy == BackpressureStrategy.BUFFER) {
return o.onBackpressureBuffer();
} else if (backpressureStrategy == BackpressureStrategy.DROP)
return o.onBackpressureDrop();
else if (backpressureStrategy == BackpressureStrategy.LATEST)
return o.onBackpressureLatest();
else
throw new RuntimeException("unrecognized backpressureStrategy " + backpressureStrategy);
}
Aggregations