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

public void transFile() {
    System.out.println("123");
    try {//from  w  w w . j  a  v a 2  s. co m
        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:acromusashi.stream.ml.common.spout.WatchTextBatchSpout.java

/**
 * ???????????????????/*from w w w. ja va  2s.  c o m*/
 * 
 * @param collector Collector
 * @throws IOException 
 * @throws InterruptedException ?
 */
@SuppressWarnings({ "rawtypes" })
protected void checkDataFile(TridentCollector collector) throws IOException, InterruptedException {
    // ?????????????????
    if (this.isInitialReaded == false) {
        List<String> fileContents = FileUtils.readLines(this.targetFile);
        emitTuples(fileContents, collector);
        this.isInitialReaded = true;

        // 
        Path dirPath = new File(this.dataFileDir).toPath();
        FileSystem fileSystem = dirPath.getFileSystem();
        this.watcherService = fileSystem.newWatchService();
        this.watchKey = dirPath.register(this.watcherService,
                new Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY });

        return;
    }

    // ????????
    WatchKey detectedKey = this.watcherService.poll(1, TimeUnit.SECONDS);

    // ???????????????????????
    if (detectedKey == null || detectedKey.equals(this.watchKey) == false) {
        return;
    }

    try {
        // ???????????????
        for (WatchEvent event : detectedKey.pollEvents()) {

            Path filePath = (Path) event.context();

            // ?????????????
            if (filePath == null
                    || this.targetFile.toPath().getFileName().equals(filePath.getFileName()) == false) {
                continue;
            }

            List<String> fileContents = FileUtils.readLines(this.targetFile);
            emitTuples(fileContents, collector);
        }
    } finally {
        detectedKey.reset();
    }
}

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;
        }//from  www.  j av a  2  s .  c o  m

        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: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;
    }// www . j  a  va2s  . c  o  m

    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:com.basistech.yca.FlatteningConfigFileManager.java

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

    if (ev.kind() == ENTRY_DELETE) {
        processDelete(filename);/*from www. j  a  v  a 2s .  co  m*/
        return;
    }
    processAddOrUpdate(filename);

}

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  .  j  a  v  a  2s.c o  m*/
        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:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;//w w w.  j a va  2 s  . co  m
        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:org.wso2.carbon.identity.adaptive.auth.deployer.SiddhiAppDeployer.java

private void startWatching() {

    if (!Files.exists(rootPath)) {
        return;//from w  w w. j  a  v a  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:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java

private Thread buildThreadAndStart() {
    Thread ret = new Thread("FilesWatcher-" + watcherName) {
        @Override/*from  ww w  . ja  v  a2  s . co m*/
        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;
}

From source file:ch.cyberduck.core.local.FileWatcher.java

private void callback(final Local folder, final WatchEvent<?> event, final FileWatcherListener l) {
    final WatchEvent.Kind<?> kind = event.kind();
    if (log.isInfoEnabled()) {
        log.info(String.format("Process file system event %s for %s", kind.name(), event.context()));
    }/*from   w  w  w .  j  av  a2  s . c  o m*/
    if (ENTRY_MODIFY == kind) {
        l.fileWritten(this.normalize(folder, event.context().toString()));
    } else if (ENTRY_DELETE == kind) {
        l.fileDeleted(this.normalize(folder, event.context().toString()));
    } else if (ENTRY_CREATE == kind) {
        l.fileCreated(this.normalize(folder, event.context().toString()));
    } else {
        log.debug(String.format("Ignored file system event %s for %s", kind.name(), event.context()));
    }
}