Example usage for java.nio.file WatchKey pollEvents

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

Introduction

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

Prototype

List<WatchEvent<?>> pollEvents();

Source Link

Document

Retrieves and removes all pending events for this watch key, returning a List of the events that were retrieved.

Usage

From source file:org.fcrepo.kernel.api.utils.AutoReloadingConfiguration.java

/**
 * Starts up monitoring of the configuration for changes.
 *///from   w w  w  .j  a v a  2 s .co 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:desktopsearch.WatchDir.java

/**
 * Process all events for keys queued to the watcher
 *//*from  w  w  w  .j  a v a2s . 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:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.HbsRenderableUpdater.java

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

        for (WatchEvent<?> event : watchKey.pollEvents()) {
            if (event.kind() != StandardWatchEventKinds.ENTRY_MODIFY) {
                continue; // We only watch file modify events.
            }

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

                    MutableHbsRenderable mutableRenderable = watchingRenderables.get(entry);
                    if (mutableRenderable != null) {
                        // Updated file is a MutableHbsRenderable
                        try {
                            mutableRenderable.reload(new StringTemplateSource(
                                    mutableRenderable.getComponentPath(), readFileContent(entry)));
                            log.info("Handlebars template '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading Handlebars template '" + entry + "'.",
                                    e);
                        }
                        continue;
                    }

                    MutableExecutable mutableExecutable = watchingExecutables.get(entry);
                    if (mutableExecutable != null) {
                        // Updated file is a MutableExecutable
                        try {
                            mutableExecutable.reload(readFileContent(entry));
                            log.info("JavaScript file '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading JavaScript file '" + entry + "'.", e);
                        }
                    }
                }
            } catch (IOException e) {
                log.error("An error occurred while reloading modified files '" + updatedFileAbsolutePath + "'.",
                        e);
            }
        }

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

From source file:com.dm.estore.common.config.Cfg.java

private void startWatcher(final String configDirPath) throws IOException {
    Path path = Paths.get(configDirPath);
    path.register(watchService, ENTRY_MODIFY);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*  w  ww  .j  a  v a  2s  .c o m*/
        public void run() {
            try {
                keepWatching = false;
                watchService.close();
            } catch (IOException e) {
                LOG.error("Unable to stop configuration watch service", e);
            }
        }
    });

    FutureTask<Integer> watchTask = new FutureTask<>(new Callable<Integer>() {
        private int totalEventCount;

        @Override
        public Integer call() throws Exception {
            while (keepWatching) {
                try {
                    WatchKey watchKey = watchService.poll(5, TimeUnit.SECONDS);
                    if (watchKey != null) {
                        boolean updateConfiguration = false;
                        for (WatchEvent<?> event : watchKey.pollEvents()) {
                            LOG.debug("Configuration changed: " + event.kind());
                            updateConfiguration = true;
                            totalEventCount++;
                        }
                        if (!watchKey.reset()) {
                            // handle situation no longer valid
                            keepWatching = false;
                        } else {
                            if (updateConfiguration) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(1000);
                                            getConfig().getString(CommonConstants.Cfg.CFG_UPDATE_TRIGGER);
                                        } catch (InterruptedException ex) {
                                            // do nothing
                                        }
                                    }
                                }).start();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            return totalEventCount;
        }
    });
    new Thread(watchTask).start();
}

From source file:com.garyclayburg.filesystem.WatchDir.java

@Override
public void run() {
    try {//from ww  w  .j a  v a  2 s  .c  om
        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.dia.kafka.isatools.producer.DirWatcher.java

/**
 * Process all events for keys queued to the watcher
 * @param isatProd/*ww w  .j  a va 2s  .  c o  m*/
 */
void processEvents(ISAToolsKafkaProducer isatProd) {
    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;
        }

        List<JSONObject> jsonParsedResults = new ArrayList<JSONObject>();

        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 an inner file has been modify then, recreate the entry
            if (kind == ENTRY_MODIFY || kind == ENTRY_CREATE) {
                File fileCheck = child.getParent().toFile();
                if (child.toFile().isDirectory()) {
                    fileCheck = child.toFile();
                }

                System.out.format("[%s] %s : %s\n", this.getClass().getSimpleName(), kind.toString(),
                        fileCheck.getAbsolutePath());
                List<String> folderFiles = ISAToolsKafkaProducer.getFolderFiles(fileCheck);
                List<JSONObject> jsonObjects = ISAToolsKafkaProducer.doTikaRequest(folderFiles);
                if (!jsonObjects.isEmpty()) {
                    //                        jsonParsedResults.addAll(jsonObjects);
                    isatProd.sendISAToolsUpdates(jsonObjects);
                }
            }

            // TODO this event has still to be specified for documents
            if (kind == ENTRY_DELETE) {
                System.err.println(String.format("Delete event not supported %s", child.toAbsolutePath()));
            }

            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (kind == ENTRY_CREATE) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException x) {
                    // ignore to keep sample readbale
                    System.err.format("IOException when creating %s \n", child.toAbsolutePath());
                }
            }
        }

        // 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:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java

@Override
public boolean hasChanged() {
    if (!watchKey.isValid()) {
        return false;
    }//from  w w w .  jav  a 2  s  .com
    boolean changed = false;
    try {
        WatchKey wKey;
        if (timeout > 0) {
            wKey = watchService.poll(timeout, TimeUnit.MILLISECONDS);
        } else {
            // Indefinite blocking
            wKey = watchService.take();
        }
        if (wKey != null) {
            if (wKey != this.watchKey) {
                throw new IllegalStateException("WatchKey does not match that registered with the service");
            }
            List<WatchEvent<?>> pollEvents = wKey.pollEvents();
            if (log.isDebugEnabled()) {
                log.debug(String.format("Found %d events", pollEvents.size()));
            }
            for (WatchEvent<?> watchEvent : pollEvents) {
                Path name = (Path) watchEvent.context();
                if (resourceFile.getFileName().equals(name)) {
                    changed = true;
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Found change to file '%s'", name));
                    }
                    break;
                }
            }
            wKey.reset();
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return changed;
}

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 {/*from w  w  w  .j  ava2s .  c o  m*/
            // 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.wso2.carbon.identity.adaptive.auth.deployer.SiddhiAppDeployer.java

private void startWatching() {

    if (!Files.exists(rootPath)) {
        return;//from  w  ww.  j av a  2s  .com
    }

    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.mail.bridge.FolderMonitor.java

@SuppressWarnings("unchecked")
@Override//w w  w  .  java2  s . c o m
public void run() {
    Path outboxPath = outboxFolder.toPath();
    WatchService watcher;
    try {
        watcher = FileSystems.getDefault().newWatchService();
        outboxPath.register(watcher, ENTRY_CREATE);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new IllegalStateException(e);
    }
    while (true) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            LOG.error(e.getMessage(), e);
            throw new IllegalStateException(e);
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        LOG.info("Folder '{}' content changed", outboxFolder.getAbsolutePath());
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == OVERFLOW)
                continue;
            File patch = outboxPath.resolve(((WatchEvent<Path>) event).context()).toFile();
            if (fileFilter.accept(patch))
                files.add(patch);
        }
        if (!files.isEmpty()) {
            timer = new Timer();
            timer.schedule(new ProcessFilesTimerTask(), NEW_FILES_PROCESS_DELAY);
            LOG.debug("File processing timer is (re-)scheduled");
        }
        boolean valid = key.reset();
        if (!valid) {
            LOG.error("Path '{}' isn't valid anymore", outboxPath);
            postMessage(new Main.StopMessage(
                    String.format("Please verify validity of folder '%s' and re-run application", outboxPath)));
            break;
        }
    }
    monitorThread = null;
}