Example usage for java.nio.file WatchEvent context

List of usage examples for java.nio.file WatchEvent context

Introduction

In this page you can find the example usage for java.nio.file WatchEvent context.

Prototype

T context();

Source Link

Document

Returns the context for the event.

Usage

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));
    }/* w  w w . j  av a2 s  .com*/
    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:erigo.filewatch.FileWatch.java

/**
 * Process new file events from the Java WatchService; stop when we see a file called "end.txt".
 *
 * This method uses Java WatchService, i.e. this is an event-driven method to get file updates.
 *//*from   w w  w . j  a  v a  2  s  .com*/
void processEvents_watchservice() throws IOException {
    for (;;) {

        // wait for key to be signaled
        WatchKey key;
        try {
            // The ".take()" method is a blocking read; can also use one of
            // the ".poll()" non-blocking methods if desired.
            key = watcher.take();
        } catch (InterruptedException x) {
            System.err.println("processEvents(): got InterruptedException: " + x);
            return;
        }

        // process all events
        // base time for all files currently in the queue
        double eventTime = (double) (System.currentTimeMillis());
        Boolean bDone = false;
        for (WatchEvent<?> event : key.pollEvents()) {
            Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                // Note: even though we've only registered for ENTRY_CREATE
                //       events, we get OVERFLOW events automatically.
                System.err.println("OVERFLOW detected");
                continue;
            }
            // Extract the filename from the event
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            String filenameStr = name.toString();
            bDone = processNewFile(filenameStr, eventTime);
            if (bDone) {
                break;
            }
        }

        boolean valid = key.reset();
        if (!valid || bDone) {
            // Directory must have gone away or we have received the "end.txt" file
            // we're done
            break;
        }

    }
}

From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java

private void watchForConsumption() throws IOException {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    try {/*from   w w w  . j  av a 2s  .c o  m*/
        Path dir = getOutputDir().toPath();
        WatchKey key = dir.register(watcher, ENTRY_DELETE);

        for (;;) {

            if (Thread.interrupted()) {
                key.cancel();
                return;
            }
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                // This key is registered only
                // for ENTRY_CREATE events,
                // but an OVERFLOW event can
                // occur regardless if events
                // are lost or discarded.
                if (kind == OVERFLOW) {
                    continue;
                }

                //                        // The filename is the
                //                        // context of the event.
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filepath = ev.context();
                String filename = filepath.toString();
                System.out.println("the filename was: " + filename);
                System.out.println(kind);
                Optional<String> res = findFile(filename);
                if (res.isPresent()) {
                    System.out.println("BEFORE REMOVAL: " + myfiles.toString());
                    System.out.println("removing: " + res.get());
                    removeFromFiles(res.get());
                    System.out.println("Removed. Now: " + myfiles.toString());
                    int dpi = findThisDP(res.get());
                    if (-1 != dpi) {
                        UI(() -> {
                            datePickers[dpi].setStyle("-fx-background-color: lightgreen");
                            dayLabels[dpi].setStyle("-fx-background-color: lightgreen");
                        });
                    }
                    log("Wide Orbit CONSUMED: " + filename);

                } else {
                    System.out.println("is present was false for: " + filename);
                    System.out.println(myfiles.toString());
                }
                // Reset the key -- this step is critical if you want to
                // receive further watch events.  If the key is no longer valid,
                // the directory is inaccessible so exit the loop.
                boolean valid = key.reset();
                if (!valid) {
                    return;
                }
                if (myfiles.isEmpty()) {
                    key.cancel();
                    log("ALL WRITTEN FILES CONSUMED.");
                    System.out.println("\n\n\n");

                    return;
                }
            } //end of events
        } //end of infinite loop

    } catch (IOException x) {
        System.err.println(x);
    } finally {
        Thread.currentThread().interrupt();
    }

}