Example usage for java.nio.file WatchKey reset

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

Introduction

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

Prototype

boolean reset();

Source Link

Document

Resets this watch key.

Usage

From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java

private Set<File> filesFromEvents() {
    WatchKey key = watcher.poll();
    Set<File> files = new LinkedHashSet<File>();
    while (key != null) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": " + file);
                }//from   w w  w .j  a va 2 s.c  om
                if (file.isDirectory()) {
                    files.addAll(walkDirectory(file.toPath()));
                } else {
                    files.add(file);
                }
            } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
                if (event.context() != null && event.context() instanceof Path) {
                    files.addAll(walkDirectory((Path) event.context()));
                } else {
                    files.addAll(walkDirectory(this.directory));
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
            }
        }
        key.reset();
        key = watcher.poll();
    }
    return files;
}

From source file:org.codice.ddf.configuration.admin.ConfigurationFilesPoller.java

@Override
public void run() {
    try {// ww w  .  j  a  va2s  .  com
        try {
            LOGGER.debug("Registering path [{}] with Watch Service.", configurationDirectoryPath.toString());
            configurationDirectoryPath.register(watchService, ENTRY_CREATE);
        } catch (IOException e) {
            LOGGER.error("Unable to register path [{}] with Watch Service",
                    configurationDirectoryPath.toString(), e);
            return;
        }

        WatchKey key;

        while (!Thread.currentThread().isInterrupted()) {
            key = watchService.take(); // blocking
            LOGGER.debug("Key has been signalled.  Looping over events.");

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

                if (kind == OVERFLOW || kind == ENTRY_MODIFY || kind == ENTRY_DELETE) {
                    LOGGER.debug("Skipping event [{}]", kind);
                    continue;
                }

                Path filename = (Path) genericEvent.context();

                if (!filename.toString().endsWith(fileExtension)) {
                    LOGGER.debug("Skipping event for [{}] due to unsupported file extension of [{}].", filename,
                            fileExtension);
                    continue; // just skip to the next event
                }

                if (changeListener != null) {
                    // Sleeping before notifying the listener to make sure file is
                    // done writing, otherwise the listener may read the file too soon.
                    TimeUnit.SECONDS.sleep(1);
                    LOGGER.debug("Notifying [{}] of event [{}] for file [{}].",
                            changeListener.getClass().getName(), kind,
                            configurationDirectoryPath.resolve(filename));
                    changeListener.notify(configurationDirectoryPath.resolve(filename));
                }
            }

            // Reset key, shutdown watcher if directory not able to be observed
            // (possibly deleted)
            if (!key.reset()) {
                LOGGER.warn("Configurations in [{}] are no longer able to be observed.",
                        configurationDirectoryPath.toString());
                break;
            }
        }
    } catch (InterruptedException | RuntimeException e) {
        LOGGER.error("The [{}] was interrupted.", this.getClass().getName(), e);
        Thread.currentThread().interrupt();
    }
}

From source file:desktopsearch.WatchDir.java

/**
 * Process all events for keys queued to the watcher
 *//*  w w  w  . jav a 2  s .  c o  m*/
void processEvents() {
    for (;;) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

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

            // TBD - provide example of how OVERFLOW event is handled
            if (kind == OVERFLOW) {
                continue;
            }

            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (recursive && (kind == ENTRY_CREATE)) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (Exception x) {
                    // ignore to keep sample readbale
                }
            }

            // print out event
            //System.out.format("%s: %s\n", event.kind().name(), child);
            try {
                UpdateDB(event.kind().name(), child);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}

From source file:nz.co.fortytwo.signalk.server.SignalKServer.java

protected SignalKServer(String configDir) throws Exception {
    // init config
    Properties props = System.getProperties();
    props.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperties(props);//from w  ww  .java 2  s.  c  om

    Util.getConfig();
    // make sure we have all the correct dirs and files now
    ensureInstall();

    logger.info("SignalKServer starting....");

    // do we have a USB drive connected?
    //logger.info("USB drive " + Util.getUSBFile());

    // create a new Camel Main so we can easily start Camel
    Main main = new Main();
    //main.setApplicationContextUri("classpath:META-INF/spring/camel-context.xml");
    // enable hangup support which mean we detect when the JVM terminates,
    // and stop Camel graceful
    main.enableHangupSupport();

    // Start activemq broker
    BrokerService broker = ActiveMqBrokerFactory.newInstance();

    broker.start();
    //DNS-SD, zeroconf mDNS
    startMdns();
    configureRouteManager(main);
    // and run, which keeps blocking until we terminate the JVM (or stop
    // CamelContext)
    main.start();

    WatchService service = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("./conf");
    dir.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
    WatchKey key = null;
    while (true) {
        key = service.take();
        // Dequeueing events
        Kind<?> kind = null;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
            // Get the type of the event
            kind = watchEvent.kind();
            logger.debug(
                    "SignalKServer conf/ event:" + watchEvent.kind() + " : " + watchEvent.context().toString());
            if (StandardWatchEventKinds.OVERFLOW == kind) {
                continue; //loop
            } else if (StandardWatchEventKinds.ENTRY_MODIFY == kind) {
                // A new Path was created 
                @SuppressWarnings("unchecked")
                Path newPath = ((WatchEvent<Path>) watchEvent).context();
                // Output
                if (newPath.endsWith("signalk-restart")) {
                    logger.info("SignalKServer conf/signalk-restart changed, stopping..");
                    main.stop();
                    main.getCamelContexts().clear();
                    main.getRouteBuilders().clear();
                    main.getRouteDefinitions().clear();

                    // so now shutdown serial reader and server
                    RouteManager routeManager = RouteManagerFactory.getInstance();
                    routeManager.stopNettyServers();
                    routeManager.stopSerial();
                    if (server != null) {
                        server.stop();
                        server = null;
                    }
                    RouteManagerFactory.clear();
                    configureRouteManager(main);
                    main.start();
                }

            }
        }

        if (!key.reset()) {
            break; //loop
        }
    }

    stopMdns();
    broker.stop();
    // write out the signalk model
    SignalKModelFactory.save(SignalKModelFactory.getInstance());
    System.exit(0);
}

From source file:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java

private Set<File> filesFromEvents() {
    Set<File> files = new LinkedHashSet<File>();
    if (this.watcher == null) {
        return files;
    }/* w w w. j a  v a2 s  .  c  o  m*/
    WatchKey key = this.watcher.poll();
    while (key != null) {
        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 (file.isDirectory()) {
                    files.addAll(walkDirectory(file.toPath()));
                } else {
                    if (!file.getPath().contains(".git")
                            && !PatternMatchUtils.simpleMatch(this.excludes, file.getName())) {
                        if (log.isDebugEnabled()) {
                            log.debug("Watch Event: " + event.kind() + ": " + file);
                        }
                        files.add(file);
                    }
                }
            } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
                if (event.context() != null && event.context() instanceof Path) {
                    files.addAll(walkDirectory((Path) event.context()));
                } else {
                    for (Path path : this.directory) {
                        files.addAll(walkDirectory(path));
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
            }
        }
        key.reset();
        key = this.watcher.poll();
    }
    return files;
}

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   www .j  a  v  a 2s. c  o  m
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.garyclayburg.filesystem.WatchDir.java

@Override
public void run() {
    try {/*  w  w w  .j av  a  2  s. c o m*/
        init(watchDir, recursive);
        for (;;) {

            log.debug("Listening for File Events...");
            // wait for key to be signalled
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            Path dir = keys.get(key);
            if (dir == null) {
                log.warn("WatchKey not recognized!! " + key);
                continue;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind kind = event.kind();

                // TBD - provide example of how OVERFLOW event is handled
                if (kind == OVERFLOW) {
                    continue;
                }

                // Context for directory entry event is the file name of entry
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);

                // print out event
                log.info("{}: {}", event.kind().name(), child);
                if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
                    attributeService.reloadGroovyClass(child);
                } else if (kind == ENTRY_DELETE) {
                    attributeService.removeGroovyClass(child);
                }

                // if directory is created, and watching recursively, then
                // register it and its sub-directories
                if (recursive && (kind == ENTRY_CREATE)) {
                    try {
                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                            registerAll(child);
                        }
                    } catch (IOException x) {
                        log.warn("Cannot register possible new directory for groovy changes: {}", child);
                    }
                }
            }

            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid) {
                keys.remove(key);

                // all directories are inaccessible
                if (keys.isEmpty()) {
                    break;
                }
            }
        }
        log.info("Stopped listening for file events");
    } catch (IOException e) {
        log.warn("Could not start File Watch service", e);
    }
}

From source file:org.wso2.carbon.identity.adaptive.auth.deployer.SiddhiAppDeployer.java

private void startWatching() {

    if (!Files.exists(rootPath)) {
        return;/* w  w w .j  a v  a 2 s . c  om*/
    }

    Thread serviceWatcherThread = new Thread(() -> {
        WatchService watcher;
        try {
            watcher = FileSystems.getDefault().newWatchService();
            rootPath.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException e) {
            log.error("Error registering watcher for path: " + rootPath.toAbsolutePath());
            return;
        }
        isFileWatcherRunning = true;
        while (isFileWatcherRunning) {
            // Wait for key to be signaled
            WatchKey fileWatcherKey;
            try {
                fileWatcherKey = watcher.take();
            } catch (InterruptedException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Watching for siddhi apps deployment folder interrupted.", e);
                }
                return;
            }
            try {
                for (WatchEvent<?> event : fileWatcherKey.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    if (kind == ENTRY_CREATE) {
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path appPath = getResolvedPathRelativeToRoot(ev.context());
                        if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) {
                            deploySiddhiApp(appPath);
                        }
                    } else if (kind == ENTRY_DELETE) {
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path appPath = getResolvedPathRelativeToRoot(ev.context());
                        if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) {
                            undeploySiddhiApp(appPath);
                        }
                    } else if (kind == ENTRY_MODIFY) {
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path appPath = getResolvedPathRelativeToRoot(ev.context());
                        if (appPath.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX)) {
                            updateSiddhiApp(appPath);
                        }
                    }
                }
                //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 = fileWatcherKey.reset();
                if (!valid) {
                    break;
                }
            } catch (Exception ex) {
                log.error("Error while watching deployment folder for siddhiApps.", ex);
            }
        }
    });

    serviceWatcherThread.start();
}

From source file:org.wso2.carbon.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java

private void run() {
    while (!isWatchServiceStopped) {
        WatchKey watchKey;
        try {//from   w w  w. j a v  a  2 s. co  m
            watchKey = watchService.take();
        } catch (ClosedWatchServiceException e) {
            log.debug("File watch service is closed.");
            return;
        } catch (InterruptedException e) {
            log.debug("File watch service interrupted.");
            return;
        }

        for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
            if (watchEvent.kind() != StandardWatchEventKinds.ENTRY_MODIFY) {
                continue;
            }

            Path updatedDirectory = (Path) watchKey.watchable();
            @SuppressWarnings("unchecked")
            Path updatedFileName = ((WatchEvent<Path>) watchEvent).context();
            // Updating the changed html file
            Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName);
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) {
                for (Path entry : stream) {
                    if (Files.isDirectory(entry)) {
                        continue;
                    }

                    MutableHtmlRenderable mutableHtmlRenderable = watchingRenderables.get(entry);
                    if (mutableHtmlRenderable != null) {
                        try {
                            String content = new String(Files.readAllBytes(entry), StandardCharsets.UTF_8);
                            mutableHtmlRenderable.setHtml(content);
                            log.info("HTML template '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading HTML template '" + entry + "'.", e);
                        }
                    }
                }
            } catch (IOException e) {
                log.error("An error occurred while reloading HTML template '" + updatedFileAbsolutePath + "'.",
                        e);
            }
        }

        boolean valid = watchKey.reset();
        if (!valid) {
            // Watch key cannot not be reset because watch service is already closed.
            break;
        }
    }
}

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

private Thread buildThreadAndStart() {
    Thread ret = new Thread("FilesWatcher-" + watcherName) {
        @Override//from  w ww  .j  a  v a2s  .  c om
        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;
}