Search in sources :

Example 41 with WatchKey

use of java.nio.file.WatchKey in project grails-core by grails.

the class WatchServiceDirectoryWatcher method run.

@Override
public void run() {
    while (active) {
        try {
            WatchKey watchKey = watchService.poll(sleepTime, TimeUnit.MILLISECONDS);
            if (watchKey != null) {
                List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
                for (WatchEvent<?> watchEvent : watchEvents) {
                    WatchEvent.Kind<?> kind = watchEvent.kind();
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        // TODO how is this supposed to be handled? I think the best thing to do is ignore it, but I'm not positive
                        LOG.warn("WatchService Overflow occurred");
                        continue;
                    }
                    WatchEvent<Path> pathWatchEvent = cast(watchEvent);
                    Path name = pathWatchEvent.context();
                    Path dir = (Path) watchKey.watchable();
                    Path child = dir.resolve(name).toAbsolutePath();
                    File childFile = child.toFile();
                    if (individualWatchedFiles.contains(child) || individualWatchedFiles.contains(child.normalize())) {
                        if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            fireOnNew(childFile);
                        } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            fireOnChange(childFile);
                        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                        // do nothing... there's no way to communicate deletions
                        }
                    } else {
                        List<String> fileExtensions = watchKeyToExtensionsMap.get(watchKey);
                        if (fileExtensions == null) {
                            // this event didn't match a file in individualWatchedFiles so it's a not an individual file we're interested in
                            // this event also didn't match a directory that we're interested in (if it did, fileExtentions wouldn't be null)
                            // so it must be event for a file we're not interested in. An example of how this can happen is:
                            // there's a directory with files in it like this:
                            // /images/a.png
                            // /images/b.png
                            // by using the addWatchFile method, /images/a.png is watched.
                            // Now, /images/b.png is changed. Because java.nio.file.WatchService watches directories, it gets a WatchEvent
                            // for /images/b.png. But we aren't interested in that.
                            LOG.debug("WatchService received an event for a file/directory that it's not interested in.");
                        } else {
                            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                                // new directory created, so watch its contents
                                addWatchDirectory(child, fileExtensions);
                                if (childFile.isDirectory() && childFile.exists()) {
                                    final File[] files = childFile.listFiles();
                                    if (files != null) {
                                        for (File newFile : files) {
                                            if (isValidFileToMonitor(newFile, fileExtensions)) {
                                                fireOnNew(newFile);
                                            }
                                        }
                                    }
                                }
                            }
                            if (isValidFileToMonitor(childFile, fileExtensions)) {
                                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                                    fireOnNew(childFile);
                                } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                                    fireOnChange(childFile);
                                } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                                // do nothing... there's no way to communicate deletions
                                }
                            }
                        }
                    }
                }
                watchKey.reset();
            }
        } catch (InterruptedException e) {
        // ignore
        }
    }
    try {
        watchService.close();
    } catch (IOException e) {
        LOG.debug("Exception while closing watchService", e);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) IOException(java.io.IOException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Example 42 with WatchKey

use of java.nio.file.WatchKey in project neo4j by neo4j.

the class DefaultFileSystemWatcher method startWatching.

@Override
public void startWatching() throws InterruptedException {
    watch = true;
    while (watch) {
        WatchKey key = watchService.take();
        if (key != null) {
            List<WatchEvent<?>> watchEvents = key.pollEvents();
            for (WatchEvent<?> watchEvent : watchEvents) {
                WatchEvent.Kind<?> kind = watchEvent.kind();
                if (StandardWatchEventKinds.ENTRY_MODIFY == kind) {
                    notifyAboutModification(key, watchEvent);
                }
                if (StandardWatchEventKinds.ENTRY_DELETE == kind) {
                    notifyAboutDeletion(key, watchEvent);
                }
            }
            key.reset();
        }
    }
}
Also used : WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Example 43 with WatchKey

use of java.nio.file.WatchKey in project ninja by ninjaframework.

the class WatchAndRestartMachine method run.

@Override
public void run() {
    for (; ; ) {
        WatchKey watchKey;
        try {
            watchKey = watchService.take();
            takeCount.incrementAndGet();
        } catch (InterruptedException e) {
            if (!shutdown) {
                log.error("Unexpectedly interrupted while waiting for take()", e);
            }
            return;
        }
        Path path = mapOfWatchKeysToPaths.get(watchKey);
        if (path == null) {
            log.error("WatchKey not recognized!!");
            continue;
        }
        for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
            WatchEvent.Kind watchEventKind = watchEvent.kind();
            // TBD - provide example of how OVERFLOW watchEvent is handled
            if (watchEventKind == OVERFLOW) {
                continue;
            }
            // Context for directory entry watchEvent is the file name of entry
            WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
            Path name = ev.context();
            Path child = path.resolve(name);
            if (watchEventKind == ENTRY_MODIFY) {
                // we are not interested in events from parent directories...
                if (!child.toFile().isDirectory()) {
                    handleNewOrModifiedFile("Modified", child);
                }
            }
            // if directory is created, then register it and its sub-directories recursively
            if (watchEventKind == ENTRY_CREATE) {
                if (!child.toFile().isDirectory()) {
                    handleNewOrModifiedFile("New", child);
                }
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException e) {
                    log.error("Something fishy happened. Unable to register new dir for watching", e);
                }
            }
        }
        // reset watchKey and remove from set if directory no longer accessible
        boolean valid = watchKey.reset();
        if (!valid) {
            mapOfWatchKeysToPaths.remove(watchKey);
            // all directories are inaccessible
            if (mapOfWatchKeysToPaths.isEmpty()) {
                break;
            }
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException)

Example 44 with WatchKey

use of java.nio.file.WatchKey in project flink by apache.

the class FileBasedOneShotLatch method awaitLatchFile.

private void awaitLatchFile(final WatchService watchService) throws InterruptedException {
    while (true) {
        WatchKey watchKey = watchService.take();
        if (isReleasedOrReleasable()) {
            break;
        }
        watchKey.reset();
    }
}
Also used : WatchKey(java.nio.file.WatchKey)

Example 45 with WatchKey

use of java.nio.file.WatchKey in project moco by dreamhead.

the class WatcherService method loop.

private void loop() {
    try {
        WatchKey key = service.take();
        Collection<Path> paths = keys.get(key);
        List<WatchEvent<?>> events = key.pollEvents().stream().filter(e -> e.kind().equals(ENTRY_MODIFY)).collect(Collectors.toList());
        for (WatchEvent<?> event : events) {
            final Path context = (Path) event.context();
            List<Path> contextPaths = paths.stream().filter(p -> p.endsWith(context)).collect(Collectors.toList());
            for (Path path : contextPaths) {
                for (Function<File, Void> listener : this.listeners.get(path)) {
                    listener.apply(path.toFile());
                }
                break;
            }
        }
        key.reset();
    } catch (ClosedWatchServiceException ignored) {
    } catch (InterruptedException e) {
        logger.error("Error happens", e);
    }
}
Also used : Path(java.nio.file.Path) LoggerFactory(org.slf4j.LoggerFactory) HIGH(com.sun.nio.file.SensitivityWatchEventModifier.HIGH) MocoException(com.github.dreamhead.moco.MocoException) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) WatchKey(java.nio.file.WatchKey) Future(java.util.concurrent.Future) MocoExecutors(com.github.dreamhead.moco.util.MocoExecutors) HashMultimap(com.google.common.collect.HashMultimap) Map(java.util.Map) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) Files(com.github.dreamhead.moco.util.Files) ENTRY_MODIFY(java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) Logger(org.slf4j.Logger) Idles.idle(com.github.dreamhead.moco.util.Idles.idle) Maps.newHashMap(com.google.common.collect.Maps.newHashMap) WatchEvent(java.nio.file.WatchEvent) Collection(java.util.Collection) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) WatchService(java.nio.file.WatchService) List(java.util.List) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) FileSystems(java.nio.file.FileSystems) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Aggregations

WatchKey (java.nio.file.WatchKey)134 Path (java.nio.file.Path)88 WatchEvent (java.nio.file.WatchEvent)65 IOException (java.io.IOException)49 WatchService (java.nio.file.WatchService)30 File (java.io.File)27 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)18 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 HashMap (java.util.HashMap)7 Map (java.util.Map)7 FileSystems (java.nio.file.FileSystems)6 FileVisitResult (java.nio.file.FileVisitResult)6 HashSet (java.util.HashSet)6 List (java.util.List)6 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)5 InputStream (java.io.InputStream)4 AccessDeniedException (java.nio.file.AccessDeniedException)4 Kind (java.nio.file.WatchEvent.Kind)4 Logger (org.slf4j.Logger)4