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: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);
                }// ww  w .j  av  a  2s  . co  m
                if (isJarFile(file)) {
                    files.add(file);
                } else
                    log.warn("[JAR Loader] Ignoring file " + file);
            }

        }
        key.reset();

    }
    return files;
}

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

@Override
public void run() {
    try {//from   w w  w  . j a  v a  2  s. co  m
        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 (configurationDirectory != null) {
                    LOGGER.debug("Notifying [{}] of event [{}] for file [{}].",
                            configurationDirectory.getClass().getName(), kind,
                            configurationDirectoryPath.resolve(filename));
                    configurationDirectory.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:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java

private Set<File> filesFromEvents() {
    Set<File> files = new LinkedHashSet<File>();
    if (this.watcher == null) {
        return files;
    }/*from  ww  w. ja  v  a2  s. co  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.codice.ddf.configuration.admin.ConfigurationFilesPoller.java

@Override
public void run() {
    try {//www.j  a  v  a  2  s  .  c  o  m
        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: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 w  w .  j  a v a2 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.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java

/**
 * Starts up monitoring of the configuration for changes.
 *//*from   ww  w.j av a 2s.  c o  m*/
private void monitorForChanges() {
    if (monitorRunning) {
        return;
    }

    final Path path = Paths.get(configPath);
    if (!path.toFile().exists()) {
        LOGGER.debug("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("Configuration {} has been updated, reloading.", path);
                                try {
                                    loadConfiguration();
                                } catch (final IOException e) {
                                    LOGGER.error("Failed to reload configuration {}", configPath, 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:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

@Override
public void run() {
    try {//from w w w . jav  a2  s.  c o m
        log.info("Watcher started.");

        initialize();

        while (true) {
            checkInterrupted();

            WatchKey watchKey = watcher.poll(CHECK_TIMEOUT, TimeUnit.MILLISECONDS);

            if (watchKey != null) {
                try {
                    log.debug("Received watchKey: {} - {}", watchKey, watchKey.watchable());

                    Path parentPath = (Path) watchKey.watchable();

                    for (WatchEvent<?> event : watchKey.pollEvents()) {
                        checkInterrupted();

                        log.debug("Received event: {} - {}", event.kind(), event.context());

                        if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                            log.warn("Performing a full scan due loss of native FileSystem tracking data.");

                            // Canceling the old watcher.
                            IOUtils.closeQuietly(watcher);

                            // Clean any pending unaccessible path.
                            unaccessiblePaths.clear();
                            creatingPaths.clear();
                            modifyingPaths.clear();

                            // Re-initialize the monitoring.
                            initialize();

                        } else {
                            Path eventPath = parentPath.resolve((Path) event.context());

                            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                                checkNewPath(eventPath);

                            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                                if (!unaccessiblePaths.contains(eventPath)) {
                                    if (isPathFullyAccessible(eventPath)) {
                                        handlePathChanged(eventPath);

                                    } else {
                                        unaccessiblePaths.add(eventPath);
                                        modifyingPaths.add(eventPath);

                                        log.debug(
                                                "File unacessible upon modification. Starting monitoring for '{}'.",
                                                eventPath);
                                    }
                                }
                            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                                if (unaccessiblePaths.contains(eventPath)) {
                                    unaccessiblePaths.remove(eventPath);

                                    log.debug("Monitored file removed. Canceling monitoring for '{}'.",
                                            eventPath);

                                    if (modifyingPaths.contains(eventPath)) {
                                        modifyingPaths.remove(eventPath);
                                        handlePathRemoved(eventPath);
                                    } else {
                                        creatingPaths.remove(eventPath);
                                    }
                                } else {
                                    handlePathRemoved(eventPath);
                                }
                            }
                        }
                    }

                } finally {
                    watchKey.reset();
                }
            }

            if (!unaccessiblePaths.isEmpty()) {
                checkAccessiblePaths();

            } else if ((updateNotificationTimestamp != -1)
                    && ((System.currentTimeMillis() - updateNotificationTimestamp) > CHECK_TIMEOUT)) {
                // Nothing happened since last update. Resetting the updateTimestamp and requesting a library update on
                // Serviio.
                updateNotificationTimestamp = -1;
                updateServiioReposotories();

            } else if (updateNotificationTimestamp == -1) {
                // No pending path to checks and no pending updates to notify. Check external configuration changes.

                Object newFlagValue = getFieldValue(LibraryManager.getInstance(),
                        "libraryAdditionsCheckerThread");
                if ((configChangeFlag != null) && (newFlagValue != configChangeFlag)) {
                    log.info("Detected configuration change. Restart monitoring.");
                    configChangeFlag = newFlagValue;

                    // Canceling the old watcher.
                    IOUtils.closeQuietly(watcher);

                    // Clean any pending unaccessible path.
                    unaccessiblePaths.clear();
                    creatingPaths.clear();
                    modifyingPaths.clear();

                    // Re-initialize the monitoring.
                    initialize();
                }
            }
        }
    } catch (InterruptedException e) {
        // This thread has been interrupted. Just exit.
        return;

    } finally {
        // Release any bounded resource.
        unaccessiblePaths.clear();
        creatingPaths.clear();
        modifyingPaths.clear();

        IOUtils.closeQuietly(watcher);

        log.info("Watcher stopped.");
    }
}

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

/**
 * Starts up monitoring of the allowed list configuration for changes.
 *//*from w  ww. java 2  s.  com*/
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:MonitorSaurausRex.MainMenu.java

public boolean MonitorDirectory() {

    Path directory = Paths.get("C:/Users/" + user + "/Documents/");
    try {/*from ww w . jav a2s .com*/
        WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        testTimer = new TimerTask() {

            @Override
            public void run() {
                checkPause = true;
                test = changeCheck();

                if (test) {
                    testTimer.cancel();
                    System.out.println("Quaritnen sucsessfully activates");
                }
            }

        };

        Timer timer = new Timer();
        timer.schedule(testTimer, 0, 1000);
        while (true) {
            WatchKey watchKeyActual = fileSystemWatchService.take();
            for (WatchEvent<?> event : watchKeyActual.pollEvents()) {

                WatchEvent.Kind<?> eventKind = event.kind();

                if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }

                WatchEvent<Path> eventPath = (WatchEvent<Path>) event;
                Path fileName = eventPath.context();

                //timerCheck(); ????? 
                //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java
                //  boolean test = false;
                if (checkPause == false) {
                    checkPause = true;
                } else {
                    ChangeCounter++;
                    System.out.println("Event " + eventKind + " occurred on " + fileName);
                }
                if (test)
                    break;
            }
            boolean isReset = watchKeyActual.reset();
            if (!isReset || test) {
                break;
            }
        }

    } catch (IOException | InterruptedException ioe) {
    }

    return true; /// EXIT METHOD
}

From source file:org.flowerplatform.web.git.GitUtils.java

public void listenForChanges(File file) throws IOException {
    Path path = file.toPath();/*from w  w w . j av  a 2 s  . c  om*/
    if (file.isDirectory()) {
        WatchService ws = path.getFileSystem().newWatchService();
        path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);
        WatchKey watch = null;
        while (true) {
            System.out.println("Watching directory: " + file.getPath());
            try {
                watch = ws.take();
            } catch (InterruptedException ex) {
                System.err.println("Interrupted");
            }
            List<WatchEvent<?>> events = watch.pollEvents();
            if (!watch.reset()) {
                break;
            }
            for (WatchEvent<?> event : events) {
                Kind<Path> kind = (Kind<Path>) event.kind();
                Path context = (Path) event.context();
                if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
                    System.out.println("OVERFLOW");
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
                    System.out.println("Created: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) {
                    System.out.println("Deleted: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                    System.out.println("Modified: " + context.getFileName());
                }
            }
        }
    } else {
        System.err.println("Not a directory. Will exit.");
    }
}