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:com.gwac.job.FileTransferServiceImpl.java

public void transFile() {
    System.out.println("123");
    try {//from   ww w .  j  a v  a  2s .com
        System.out.println("123");
        watcher = FileSystems.getDefault().newWatchService();
        Path dir = Paths.get("E:/TestData/gwacTest");
        dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
        System.out.println("Watch Service registered for dir: " + dir.getFileName());
        isSuccess = true;
    } catch (IOException ex) {
        isSuccess = false;
        ex.printStackTrace();
    }

    if (isBeiJingServer || !isSuccess) {
        return;
    }

    if (running == true) {
        log.debug("start job fileTransferJob...");
        running = false;
    } else {
        log.warn("job fileTransferJob is running, jump this scheduler.");
        return;
    }
    try {
        WatchKey key = watcher.poll();
        if (key != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path fileName = ev.context();
                System.out.println(kind.name() + ": " + fileName);

                if (kind == ENTRY_MODIFY) {
                    System.out.println("My source file has changed!!!");
                }
            }
        }

        boolean valid = key.reset();
        if (!valid) {
            return;
        }
    } catch (Exception ex) {
    }

    if (running == false) {
        running = true;
        log.debug("job fileTransferJob is done.");
    }
}

From source file:org.apache.nifi.minifi.bootstrap.configuration.ingestors.FileChangeIngestor.java

protected boolean targetChanged() {
    boolean targetChanged = false;

    final WatchKey watchKey = this.watchService.poll();

    if (watchKey == null) {
        return targetChanged;
    }/*w  w w  .java 2  s .  c  om*/

    for (WatchEvent<?> watchEvt : watchKey.pollEvents()) {
        final WatchEvent.Kind<?> evtKind = watchEvt.kind();

        final WatchEvent<Path> pathEvent = (WatchEvent<Path>) watchEvt;
        final Path changedFile = pathEvent.context();

        // determine target change by verifying if the changed file corresponds to the config file monitored for this path
        targetChanged = (evtKind == ENTRY_MODIFY
                && changedFile.equals(configFilePath.getName(configFilePath.getNameCount() - 1)));
    }

    // After completing inspection, reset for detection of subsequent change events
    boolean valid = watchKey.reset();
    if (!valid) {
        throw new IllegalStateException("Unable to reinitialize file system watcher.");
    }

    return targetChanged;
}

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

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

/**
 * Process all events for keys queued to the watcher
 *///from w ww  .  j  a  va  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:org.wso2.carbon.inbound.localfile.LocalFileOneTimePolling.java

@SuppressWarnings("unchecked")
private Object watchDirectory() throws IOException {
    Path newPath = Paths.get(watchedDir);
    WatchService watchService = FileSystems.getDefault().newWatchService();
    try {/*from  w  w w.ja  v  a 2 s. com*/
        newPath.register(watchService, ENTRY_MODIFY);
        while (true) {
            WatchKey key = watchService.take();
            if (key != null) {
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = watchEvent.kind();
                    WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    Path entry = watchEventPath.context();

                    Path filePath = Paths.get(watchedDir, entry.toString());
                    if (kind == ENTRY_MODIFY) {
                        processFile(filePath, contentType);
                    } else if (kind == OVERFLOW) {
                        continue;
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file is : " + entry);
                    }
                }
                key.reset();
                if (!key.isValid()) {
                    break;
                }
            }
        }
    } catch (IOException e) {
        log.error("Error while watching directory: " + e.getMessage(), e);
    } catch (InterruptedException ie) {
        log.error("Error while get the WatchKey : " + ie.getMessage(), ie);
    } finally {
        watchService.close();
    }
    return null;
}

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

@Override
public void run() {
    try {//from w w  w  .  j  a v a 2s.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:de.elomagic.carafile.client.CaraCloud.java

/**
 * Starts synchronization of the given base path with the registry.
 * <p/>//from w w w  . j a  v a2  s  . co m
 * This method will block till call method {@link CaraCloud#stop() }
 *
 * @throws IOException Thrown when an I/O error occurs
 * @throws InterruptedException Thrown when method stop was called or application will terminate
 * @throws GeneralSecurityException
 */
public void start() throws IOException, InterruptedException, GeneralSecurityException {
    if (client == null) {
        throw new IllegalStateException("Attribute \"client\" must be set.");
    }

    if (basePath == null) {
        throw new IllegalStateException("Attribute \"basePath\" must be set.");
    }

    if (!Files.exists(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must exists.");
    }

    if (!Files.isDirectory(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must be a directory/folder.");
    }

    watcher = FileSystems.getDefault().newWatchService();
    registerDefaultWatch(basePath);

    while (!Thread.interrupted()) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path path = basePath.resolve(event.context().toString());
                createFile(path);
            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {

            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                Path path = basePath.resolve(event.context().toString());
                deleteFile(path);
            } else {
                LOG.error("Unsupported kind: " + event.kind() + ", path: " + event.context());
            }
        }

        key.reset();
    }
}

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

private void startWatching() {

    if (!Files.exists(rootPath)) {
        return;/* www  .  ja  va 2 s .c o m*/
    }

    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:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;//  w w w.ja  va2  s.  c  om
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            Log.warn("Interuppted the watcher!!!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.info("Exit watcher run method.");
                return;
            }
            continue;
        }
        Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode());

        for (WatchEvent<?> event : key.pollEvents()) {

            WatchEvent.Kind<?> kind = event.kind();
            Log.fine("Event is " + kind);
            // This key is registered only
            // for ENTRY_CREATE events,
            // but an OVERFLOW event can
            // occur regardless if events
            // are lost or discarded.
            if (kind == OVERFLOW) {
                continue;
            }

            // The filename is the
            // context of the event.
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();

            // Ignore emacs autosave files
            if (filename.toString().contains(".#")) {
                continue;
            }
            Log.finer("Changed file is {0}", filename);
            Path directory = (Path) key.watchable();
            Log.finer("Changed directory is {0}", directory);
            Path fullPath = directory.resolve(filename);
            Log.fine("Changed path is {0}", fullPath);
            Boolean handlerFound = false;
            for (IWatchEventHandler handler : watchedByPath.values()) {
                Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(),
                        handler.getWatchedFolder());
                // Ignore private files
                if (filename.getFileName().startsWith(".")) {
                    continue;
                }
                if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString())
                        || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder())))
                        && (StringUtils.isEmpty(handler.getExtension())
                                || fullPath.toString().endsWith(handler.getExtension()))) {
                    String relativePath = filename.getFileName().toString();
                    Log.info("Handling {0} with watcher {1} for folder {2}", filename,
                            handler.getClass().getName(), handler.getWatchedFolder());
                    try {
                        handler.handle(relativePath, fullPath.toString(), kind, event);
                        handlerFound = true;
                    } catch (Exception e) {
                        Log.exception(e, "Exception processing path={0} handler={1}", relativePath,
                                handler.getClass().getName());
                    }
                }
            }
            if (!handlerFound) {
                Log.info("No handler found for {0}", fullPath);
            }
        }
        // Reset the key -- this step is critical if you want to
        // receive further watch events.  If the key is no longer valid,
        // the directory is inaccessible so exit the loop.
        boolean valid = key.reset();
        if (!valid) {
            Log.warn("Key invalid! Exit watch.");
            break;
        }
    }
}

From source file:ddf.camel.component.catalog.content.ContentProducerDataAccessObject.java

public WatchEvent.Kind<Path> getEventType(boolean storeRefKey, Message in) {
    if (storeRefKey) {
        WatchEvent<Path> pathWatchEvent = (WatchEvent<Path>) ((GenericFileMessage) in).getGenericFile()
                .getFile();/*from  w  w w.ja  v a 2s  .c  om*/
        return pathWatchEvent.kind();
    } else {
        return ENTRY_CREATE;
    }
}