Example usage for java.nio.file WatchEvent kind

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

Introduction

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

Prototype

Kind<T> kind();

Source Link

Document

Returns the event kind.

Usage

From source file:io.gravitee.gateway.services.localregistry.LocalApiDefinitionRegistry.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        this.init();

        executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "registry-monitor"));
        executor.execute(() -> {/*from w  w  w  .  j av  a  2 s.c o  m*/
            Path registry = Paths.get(registryPath);
            LOGGER.info("Start local registry monitor for directory {}", registry);

            try {
                WatchService watcher = registry.getFileSystem().newWatchService();
                registry.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                while (true) {
                    WatchKey key;
                    try {
                        key = watcher.take();
                    } catch (InterruptedException ex) {
                        return;
                    }

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

                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path fileName = registry.resolve(ev.context().getFileName());

                        LOGGER.info("An event occurs for file {}: {}", fileName, kind.name());

                        if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null) {
                                if (apiManager.get(existingDefinition.getId()) != null) {
                                    apiManager.update(loadedDefinition);
                                } else {
                                    apiManager.undeploy(existingDefinition.getId());
                                    definitions.remove(fileName);
                                    apiManager.deploy(loadedDefinition);
                                    definitions.put(fileName, loadedDefinition);
                                }
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = apiManager.get(loadedDefinition.getId());
                            if (existingDefinition != null) {
                                apiManager.update(loadedDefinition);
                            } else {
                                apiManager.deploy(loadedDefinition);
                                definitions.put(fileName, loadedDefinition);
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null
                                    && apiManager.get(existingDefinition.getId()) != null) {
                                apiManager.undeploy(existingDefinition.getId());
                                definitions.remove(fileName);
                            }
                        }

                        boolean valid = key.reset();
                        if (!valid) {
                            break;
                        }
                    }
                }
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while looking for PI definitions from filesystem", ioe);
            }
        });
    }
}

From source file:io.mangoo.build.Watcher.java

@SuppressWarnings("all")
private void handleEvents(WatchKey watchKey, Path path) {
    for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
        WatchEvent.Kind<?> watchEventKind = watchEvent.kind();
        if (OVERFLOW.equals(watchEventKind)) {
            continue;
        }//w ww.ja v a 2s.c om

        WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
        Path name = ev.context();
        Path child = path.resolve(name);

        if (ENTRY_MODIFY.equals(watchEventKind) && !child.toFile().isDirectory()) {
            handleNewOrModifiedFile(child);
        }

        if (ENTRY_CREATE.equals(watchEventKind)) {
            if (!child.toFile().isDirectory()) {
                handleNewOrModifiedFile(child);
            }
            try {
                if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                    registerAll(child);
                }
            } catch (IOException e) {
                LOG.error("Something fishy happened. Unable to register new dir for watching", e);
            }
        }
    }
}

From source file:com.basistech.yca.FlatteningConfigFileManager.java

private void processEvent(WatchEvent<Path> ev) {
    Path filename = ev.context();

    if (ev.kind() == ENTRY_DELETE) {
        processDelete(filename);/*from   ww w.jav a 2s .com*/
        return;
    }
    processAddOrUpdate(filename);

}

From source file:com.aspc.cms.module.SyncResourceApp.java

private void monitorDir() throws Exception {
    // Create a new Watch Service
    WatchService watchService = FileSystems.getDefault().newWatchService();

    registerDir(watchService, syncDirectory);

    while (true) {
        try {//  w  ww. ja v  a 2 s .  com
            // Obtaining watch keys
            final WatchKey key = watchService.take();//poll(5, TimeUnit.SECONDS);

            if (key == null)
                continue;

            long tmpLastModified = lastModify.get();
            long startLastModified = tmpLastModified;
            try {
                // key value can be null if no event was triggered
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    final Kind<?> kind = watchEvent.kind();
                    // Overflow event
                    if (StandardWatchEventKinds.OVERFLOW == kind) {
                        continue; // loop
                    }

                    tmpLastModified = scanChanges(syncDirectory, tmpLastModified);
                }
            } finally {
                key.reset();
            }
            lastModify.compareAndSet(startLastModified, tmpLastModified);
        } catch (Exception e) {
            LOGGER.warn("could not send", e);
            Thread.sleep(60000);
        }
    }
}

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;
    }//from www .  j a v  a  2 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:org.dishevelled.thumbnail.examples.ThumbnailDrop.java

/**
 * Process file system watcher events./*from   w w  w .  j  a  va  2 s  .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:com.basistech.yca.FlatteningConfigFileManager.java

private void watchLoop() {
    for (;;) {/*from   ww w  .j av a  2s  .c o m*/

        // wait for key to be signaled
        WatchKey key;
        try {
            key = watchService.take();
        } catch (InterruptedException x) {
            break;
        }

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

            if (kind == OVERFLOW) {
                continue;
            }

            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            processEvent(ev);
        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
    watchKey.cancel();
    try {
        watchService.close();
    } catch (IOException e) {
        LOG.error("Error closing watch service", e);
    }
}

From source file:org.fcrepo.http.api.ExternalContentPathValidator.java

/**
 * Starts up monitoring of the allowed list configuration for changes.
 *///from www . ja v a2 s  .c  om
private void monitorForChanges() {
    if (monitorRunning) {
        return;
    }

    final Path path = Paths.get(configPath);
    if (!path.toFile().exists()) {
        LOGGER.debug("Allow list configuration {} does not exist, disabling monitoring", configPath);
        return;
    }
    final Path directoryPath = path.getParent();

    try {
        final WatchService watchService = FileSystems.getDefault().newWatchService();
        directoryPath.register(watchService, ENTRY_MODIFY);

        monitorThread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (;;) {
                        WatchKey key;
                        try {
                            key = watchService.take();
                        } catch (final InterruptedException e) {
                            LOGGER.debug("Interrupted the configuration monitor thread.");
                            break;
                        }

                        for (final WatchEvent<?> event : key.pollEvents()) {
                            final WatchEvent.Kind<?> kind = event.kind();
                            if (kind == OVERFLOW) {
                                continue;
                            }

                            // If the configuration file triggered this event, reload it
                            final Path changed = (Path) event.context();
                            if (changed.equals(path.getFileName())) {
                                LOGGER.info("External binary configuration {} has been updated, reloading.",
                                        path);
                                try {
                                    loadAllowedPaths();
                                } catch (final IOException e) {
                                    LOGGER.error("Failed to reload external locations configuration", e);
                                }
                            }

                            // reset the key
                            final boolean valid = key.reset();
                            if (!valid) {
                                LOGGER.debug("Monitor of {} is no longer valid", path);
                                break;
                            }
                        }
                    }
                } finally {
                    try {
                        watchService.close();
                    } catch (final IOException e) {
                        LOGGER.error("Failed to stop configuration monitor", e);
                    }
                }
                monitorRunning = false;
            }
        });
    } catch (final IOException e) {
        LOGGER.error("Failed to start configuration monitor", e);
    }

    monitorThread.start();
    monitorRunning = true;
}

From source file:uk.gov.gchq.gaffer.miniaccumulocluster.MiniAccumuloClusterController.java

protected void watchShutdown() {
    LOGGER.info("Watching Shutdown File " + clusterPath + "/" + SHUTDOWN_FILENAME);

    try {//from www .  j  a  v a  2s .  c  o m
        WatchService watcher = FileSystems.getDefault().newWatchService();
        clusterPath.register(watcher, ENTRY_CREATE);

        OUTER: while (true) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (final InterruptedException e) {
                return;
            }

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

                if (kind == OVERFLOW) {
                    continue;
                }

                final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                final Path filename = ev.context();

                LOGGER.debug("Filename changed " + filename);

                if (filename.toString().equals(SHUTDOWN_FILENAME)) {
                    MiniAccumuloClusterController.this.stop();
                    break OUTER;
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }

        LOGGER.info("Finished Watching Shutdown");
    } catch (final IOException e) {
        LOGGER.error("Failed to watch shutdown", e);
    }
}

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  ww  w  .j  a va2  s .  c  o  m*/

    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);
}