Search in sources :

Example 76 with WatchKey

use of java.nio.file.WatchKey in project Gargoyle by callakrsos.

the class FileUtilTest method watchTest.

@Test
public void watchTest() throws IOException {
    File file = new File("c:\\someDir");
    file.mkdirs();
    WatchService newWatchService = FileSystems.getDefault().newWatchService();
    WatchKey register = file.toPath().register(newWatchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    System.out.println("Watch Service Registered ..");
    while (true) {
        try {
            System.out.println("start");
            WatchKey key = newWatchService.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path fileName = ev.context();
                System.out.println(kind.name() + ": " + fileName);
                if (key == ENTRY_MODIFY && fileName.toString().equals("DirectoryWatchDemo.java")) {
                    System.out.println("My source file has changed!!!");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        } catch (InterruptedException e) {
            break;
        }
    }
    System.out.println("end ");
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 77 with WatchKey

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

the class RuntimeEnvironment method startWatchDogService.

/**
 * Starts a watch dog service for a directory. It automatically reloads the
 * AuthorizationFramework if there was a change in <b>real-time</b>.
 * Suitable for plugin development.
 *
 * You can control start of this service by a configuration parameter
 * {@link Configuration#authorizationWatchdogEnabled}
 *
 * @param directory root directory for plugins
 */
public void startWatchDogService(File directory) {
    stopWatchDogService();
    if (directory == null || !directory.isDirectory() || !directory.canRead()) {
        LOGGER.log(Level.INFO, "Watch dog cannot be started - invalid directory: {0}", directory);
        return;
    }
    LOGGER.log(Level.INFO, "Starting watchdog in: {0}", directory);
    watchDogThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                watchDogWatcher = FileSystems.getDefault().newWatchService();
                Path dir = Paths.get(directory.getAbsolutePath());
                Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException {
                        // attach monitor
                        LOGGER.log(Level.FINEST, "Watchdog registering {0}", d);
                        d.register(watchDogWatcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
                        return CONTINUE;
                    }
                });
                LOGGER.log(Level.INFO, "Watch dog started {0}", directory);
                while (!Thread.currentThread().isInterrupted()) {
                    final WatchKey key;
                    try {
                        key = watchDogWatcher.take();
                    } catch (ClosedWatchServiceException x) {
                        break;
                    }
                    boolean reload = false;
                    for (WatchEvent<?> event : key.pollEvents()) {
                        final WatchEvent.Kind<?> kind = event.kind();
                        if (kind == ENTRY_CREATE) {
                            reload = true;
                        } else if (kind == ENTRY_DELETE) {
                            reload = true;
                        } else if (kind == ENTRY_MODIFY) {
                            reload = true;
                        }
                    }
                    if (reload) {
                        // experimental wait if file is being written right now
                        Thread.sleep(THREAD_SLEEP_TIME);
                        getAuthorizationFramework().reload();
                    }
                    if (!key.reset()) {
                        break;
                    }
                }
            } catch (InterruptedException | IOException ex) {
                LOGGER.log(Level.FINEST, "Watchdog finishing (exiting)", ex);
                Thread.currentThread().interrupt();
            }
            LOGGER.log(Level.FINER, "Watchdog finishing (exiting)");
        }
    }, "watchDogService");
    watchDogThread.start();
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent)

Example 78 with WatchKey

use of java.nio.file.WatchKey in project hutool by looly.

the class WatchMonitor method registerPath.

/**
 * 将指定路径加入到监听中
 * @param path 路径
 * @param maxDepth 递归下层目录的最大深度
 * @return {@link WatchKey}
 */
private void registerPath(Path path, int maxDepth) {
    try {
        final WatchKey key = path.register(watchService, ArrayUtil.isEmpty(this.events) ? EVENTS_ALL : this.events);
        watchKeyPathMap.put(key, path);
        if (maxDepth > 1) {
            // 遍历所有子目录并加入监听
            Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), maxDepth, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    // 继续添加目录
                    registerPath(dir, 0);
                    return super.postVisitDirectory(dir, exc);
                }
            });
        }
    } catch (IOException e) {
        if (e instanceof AccessDeniedException) {
            // 对于禁止访问的目录,跳过监听
            return;
        }
        throw new WatchException(e);
    }
}
Also used : Path(java.nio.file.Path) AccessDeniedException(java.nio.file.AccessDeniedException) FileVisitOption(java.nio.file.FileVisitOption) WatchKey(java.nio.file.WatchKey) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException)

Example 79 with WatchKey

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

the class Watcher method rescan.

// Implementation methods
// -------------------------------------------------------------------------
public void rescan() throws IOException {
    for (WatchKey key : keys.keySet()) {
        key.cancel();
    }
    keys.clear();
    Files.walkFileTree(root, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FilteringFileVisitor());
}
Also used : WatchKey(java.nio.file.WatchKey)

Example 80 with WatchKey

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

the class Watcher method processEvents.

public void processEvents() {
    while (true) {
        WatchKey key = watcher.poll();
        if (key == null) {
            break;
        }
        Path dir = keys.get(key);
        if (dir == null) {
            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);
            debug("Processing event {} on path {}", kind, child);
            if (kind == OVERFLOW) {
                // rescan();
                continue;
            }
            try {
                if (kind == ENTRY_CREATE) {
                    if (Files.isDirectory(child)) {
                        // if directory is created, and watching recursively, then
                        // register it and its sub-directories
                        Files.walkFileTree(child, new FilteringFileVisitor());
                    } else if (Files.isRegularFile(child)) {
                        scan(child);
                    }
                } else if (kind == ENTRY_MODIFY) {
                    if (Files.isRegularFile(child)) {
                        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) {
            debug("Removing key " + key + " and dir " + dir + " from keys");
            keys.remove(key);
            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

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