Example usage for java.nio.file WatchKey cancel

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

Introduction

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

Prototype

void cancel();

Source Link

Document

Cancels the registration with the watch service.

Usage

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

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

    try {//www  . j  a  v a  2  s .com
        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();
    }

}

From source file:org.dishevelled.thumbnail.examples.ThumbnailDrop.java

/**
 * Process file system watcher events./*from  ww w.ja v  a  2s.  c o  m*/
 */
void processEvents() {
    for (;;) {
        WatchKey key = null;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            return;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }

            WatchEvent<Path> pathEvent = cast(event);
            Path name = pathEvent.context();
            Path path = watchDirectory.resolve(name);
            if (kind == ENTRY_CREATE) {
                created(path);
            } else if (kind == ENTRY_MODIFY) {
                modified(path);
            }
        }
        if (!key.reset()) {
            key.cancel();
            try {
                watcher.close();
            } catch (IOException e) {
                // ignore
            }
            break;
        }
    }
}

From source file:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java

private Thread buildThreadAndStart() {
    Thread ret = new Thread("FilesWatcher-" + watcherName) {
        @Override//from  w  w w .ja  v  a2  s . c  o m
        public void run() {
            log.debug("FileWatcher thread started " + watcherName);
            boolean continueWatching = true;
            while (continueWatching) {
                WatchKey key;
                try {
                    idleIfNoKeysRegistered();
                    key = watcher.take();
                    // NOTE: Since we're watching only one folder we assume
                    // that there will be only one key for our folder
                } catch (ClosedWatchServiceException cwe) {
                    log.error("ClosedWatchServiceException fired, stoppign thread.", cwe);
                    return;
                } catch (InterruptedException x) {
                    log.debug("FileWatcher thread stopped by InterruptedException", x);
                    return;
                } catch (Throwable t) {
                    log.error("Unexpected exception while checking for updates on watched file", t);
                    return;
                }

                BaseFolder baseFolder = null;
                synchronized (watcherName) {
                    baseFolder = keys.get(key);
                }
                if (baseFolder == null) {
                    key.cancel();
                    continue;
                }

                for (WatchEvent<?> event : key.pollEvents()) {
                    // Context for directory entry event is the file name of
                    // entry
                    WatchEvent<Path> ev = cast(event);
                    Path name = ev.context();
                    Path child = baseFolder.path.resolve(name);
                    String relativeFilename = FilenameUtils.getName(child.toString());
                    if (!baseFolder.interestedFiles.contains(relativeFilename)
                            && !event.kind().equals(ENTRY_CREATE)) {
                        continue;
                    }

                    // print out event
                    log.debug("Watcher event: " + event.kind().name() + ", file " + child);
                    dirWatcherHandler.handleFileChanged(event.kind(), child.toString());
                }

                // reset key and remove from set if directory no longer
                // accessible
                boolean valid = key.reset();
                if (!valid) {
                    synchronized (watcherName) {
                        keys.remove(key);
                        baseFolders.remove(baseFolder.folder);
                    }
                }
            }
            log.debug("FileWatcher thread stopped " + watcherName);
        }

        private void idleIfNoKeysRegistered() throws InterruptedException {
            while (true) {
                synchronized (watcherName) {
                    if (!keys.isEmpty()) {
                        break;
                    }
                }
                Thread.sleep(500);
            }
        };
    };
    ret.start();
    return ret;
}