Example usage for java.nio.file WatchKey isValid

List of usage examples for java.nio.file WatchKey isValid

Introduction

In this page you can find the example usage for java.nio.file WatchKey isValid.

Prototype

boolean isValid();

Source Link

Document

Tells whether or not this watch key is valid.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("/home/docs");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();
        System.out.println("Path being watched: " + watchKey.watchable());
        if (watchKey.isValid() == false) {
            return;
        }//from  www . j  ava 2 s. co  m
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            System.out.println("Kind: " + event.kind());
            System.out.println("Context: " + event.context());
            System.out.println("Count: " + event.count());
            System.out.println();
        }
        boolean valid = watchKey.reset();
        System.out.println(valid);

    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("c:/");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();//from w w  w .  ja v a  2s .c om

        if (watchKey.isValid()) {
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                System.out.println("Kind: " + event.kind());
                System.out.println("Context: " + event.context());
                System.out.println("Count: " + event.count());
                System.out.println();
            }

            boolean valid = watchKey.reset();
            if (!valid) {
                // The watchKey is not longer registered
            }
        }
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {

    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("c:/");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();/*from   w ww .  jav  a  2s.  c  o m*/

        if (watchKey.isValid()) {
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                System.out.println("Kind: " + event.kind());
                System.out.println("Context: " + event.context());
                System.out.println("Count: " + event.count());
                System.out.println();
            }

            boolean valid = watchKey.reset();
            if (!valid) {
                // The watchKey is not longer registered
            }
        }
    }

}

From source file:com.reactive.hzdfs.dll.JarModuleLoader.java

private Set<File> filesFromEvents() throws InterruptedException {
    WatchKey key = watcher.take();
    Set<File> files = new LinkedHashSet<File>();
    if (key != null && key.isValid()) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
                    || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": " + file);
                }// w  w w .j  a  va 2 s.c  o  m
                if (isJarFile(file)) {
                    files.add(file);
                } else
                    log.warn("[JAR Loader] Ignoring file:- " + file);
            }

        }
        key.reset();

    }
    return files;
}

From source file:com.reactivetechnologies.platform.rest.dll.JarModuleLoader.java

private Set<File> filesFromEvents() throws InterruptedException {
    WatchKey key = watcher.take();
    Set<File> files = new LinkedHashSet<File>();
    if (key != null && key.isValid()) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
                    || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": " + file);
                }//from   w  w w .j  a  v a 2 s .co m
                if (isJarFile(file)) {
                    files.add(file);
                } else
                    log.warn("[JAR Loader] Ignoring file " + file);
            }

        }
        key.reset();

    }
    return files;
}

From source file:ch.cyberduck.core.local.FileWatcher.java

public CountDownLatch register(final Local file, final FileWatcherListener listener) throws IOException {
    // Make sure to canonicalize the watched folder
    final Path folder = new File(file.getParent().getAbsolute()).getCanonicalFile().toPath();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Register folder %s watching for file %s", folder, file));
    }//from   w  w w. j  av  a  2 s.c o  m
    final WatchKey key = monitor.register(folder,
            new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY });
    if (!key.isValid()) {
        throw new IOException(String.format("Failure registering for events in %s", file));
    }
    final CountDownLatch lock = new CountDownLatch(1);
    pool.execute(new Callable<Boolean>() {
        @Override
        public Boolean call() throws IOException {
            while (true) {
                // wait for key to be signaled
                final WatchKey key;
                try {
                    lock.countDown();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Wait for key from watch service %s", monitor));
                    }
                    key = monitor.take();
                } catch (ClosedWatchServiceException e) {
                    // If this watch service is closed
                    return true;
                } catch (InterruptedException e) {
                    return false;
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Retrieved key %s from watch service %s", key, monitor));
                }
                for (WatchEvent<?> event : key.pollEvents()) {
                    final WatchEvent.Kind<?> kind = event.kind();
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Detected file system event %s", kind.name()));
                    }
                    if (kind == OVERFLOW) {
                        log.error(String.format("Overflow event for %s", folder));
                        break;
                    }
                    // The filename is the context of the event. May be absolute or relative path name.
                    if (matches(normalize(LocalFactory.get(folder.toString()), event.context().toString()),
                            LocalFactory.get(folder.toString(), file.getName()))) {
                        callback(LocalFactory.get(folder.toString()), event, listener);
                    } else {
                        log.warn(String.format("Ignored file system event for unknown file %s",
                                event.context()));
                    }
                }
                // Reset the key -- this step is critical to receive further watch events.
                boolean valid = key.reset();
                if (!valid) {
                    // The key is no longer valid and the loop can exit.
                    return true;
                }
            }
        }
    });
    return lock;
}

From source file:org.wso2.carbon.inbound.localfile.LocalFileOneTimePolling.java

@SuppressWarnings("unchecked")
private Object watchDirectory() throws IOException {
    Path newPath = Paths.get(watchedDir);
    WatchService watchService = FileSystems.getDefault().newWatchService();
    try {//  w  ww .  j a v  a  2 s . co m
        newPath.register(watchService, ENTRY_MODIFY);
        while (true) {
            WatchKey key = watchService.take();
            if (key != null) {
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = watchEvent.kind();
                    WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    Path entry = watchEventPath.context();

                    Path filePath = Paths.get(watchedDir, entry.toString());
                    if (kind == ENTRY_MODIFY) {
                        processFile(filePath, contentType);
                    } else if (kind == OVERFLOW) {
                        continue;
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file is : " + entry);
                    }
                }
                key.reset();
                if (!key.isValid()) {
                    break;
                }
            }
        }
    } catch (IOException e) {
        log.error("Error while watching directory: " + e.getMessage(), e);
    } catch (InterruptedException ie) {
        log.error("Error while get the WatchKey : " + ie.getMessage(), ie);
    } finally {
        watchService.close();
    }
    return null;
}