Search in sources :

Example 21 with WatchEvent

use of java.nio.file.WatchEvent in project openscoring by openscoring.

the class DirectoryDeployer method processKey.

private void processKey(WatchKey key, Path root) throws Exception {
    List<WatchEvent<?>> events = key.pollEvents();
    for (WatchEvent<?> event : events) {
        Path child = root.resolve((Path) event.context());
        process((WatchEvent.Kind<Path>) event.kind(), child);
    }
}
Also used : Path(java.nio.file.Path) WatchEvent(java.nio.file.WatchEvent)

Example 22 with WatchEvent

use of java.nio.file.WatchEvent in project HotswapAgent by HotswapProjects.

the class AbstractNIO2Watcher method processEvents.

/**
 * Process all events for keys queued to the watcher
 *
 * @return true if should continue
 * @throws InterruptedException
 */
private boolean processEvents() throws InterruptedException {
    // wait for key to be signalled
    WatchKey key = watcher.poll(10, TimeUnit.MILLISECONDS);
    if (key == null) {
        return true;
    }
    PathPair dir = keys.get(key);
    if (dir == null) {
        LOGGER.warning("WatchKey '{}' not recognized", key);
        return true;
    }
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind<?> kind = event.kind();
        if (kind == OVERFLOW) {
            LOGGER.warning("WatchKey '{}' overflowed", key);
            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);
        LOGGER.debug("Watch event '{}' on '{}' --> {}", event.kind().name(), child, name);
        dispatcher.add(ev, child);
        // register it and its sub-directories
        if (kind == ENTRY_CREATE) {
            try {
                if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                    registerAll(dir.getWatched(), child);
                }
            } catch (IOException x) {
                LOGGER.warning("Unable to register events for directory {}", x, child);
            }
        }
    }
    // reset key and remove from set if directory no longer accessible
    boolean valid = key.reset();
    if (!valid) {
        LOGGER.warning("Watcher on {} not valid, removing...", keys.get(key).getShortDescription());
        keys.remove(key);
        // all directories are inaccessible
        if (keys.isEmpty()) {
            return false;
        }
        if (classLoaderListeners.isEmpty()) {
            for (WatchKey k : keys.keySet()) {
                k.cancel();
            }
            return false;
        }
    }
    return true;
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException)

Example 23 with WatchEvent

use of java.nio.file.WatchEvent in project hazelcast-jet by hazelcast.

the class StreamFilesP method drainWatcherEvents.

private void drainWatcherEvents() throws InterruptedException {
    final ILogger logger = getLogger();
    // poll with blocking only when there is no other work to do
    final WatchKey key = (currentFile == null && eventQueue.isEmpty()) ? watcher.poll(1, SECONDS) : watcher.poll();
    if (key == null) {
        if (!Files.exists(watchedDirectory)) {
            logger.info("Directory " + watchedDirectory + " does not exist, stopped watching");
            close(null);
        }
        return;
    }
    for (WatchEvent<?> event : key.pollEvents()) {
        final WatchEvent.Kind<?> kind = event.kind();
        final Path fileName = ((WatchEvent<Path>) event).context();
        final Path filePath = watchedDirectory.resolve(fileName);
        if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
            if (glob.matches(fileName) && belongsToThisProcessor(fileName) && !Files.isDirectory(filePath)) {
                logFine(logger, "Will open file to read new content: %s", filePath);
                eventQueue.add(filePath);
            }
        } else if (kind == ENTRY_DELETE) {
            logFinest(logger, "File was deleted: %s", filePath);
            fileOffsets.remove(filePath);
        } else if (kind == OVERFLOW) {
            logger.warning("Detected OVERFLOW in " + watchedDirectory);
        } else {
            throw new JetException("Unknown kind of WatchEvent: " + kind);
        }
    }
    if (!key.reset()) {
        logger.info("Watch key is invalid. Stopping watcher.");
        close(null);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ILogger(com.hazelcast.logging.ILogger) WatchEvent(java.nio.file.WatchEvent) JetException(com.hazelcast.jet.JetException)

Example 24 with WatchEvent

use of java.nio.file.WatchEvent in project stagen by wiztools.

the class MonitorChangesBuild method run.

@Override
public void run() {
    while (true) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException ex) {
            return;
        }
        key.pollEvents().stream().forEach((event) -> {
            WatchEvent.Kind<?> kind = event.kind();
            if (!(kind == OVERFLOW)) {
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filename = ev.context();
                LOG.info(MessageFormat.format("Detected change: {0}", filename));
                // Generate site:
                RunnerGen gen = new RunnerGen();
                RunnerClean clean = new RunnerClean();
                try {
                    clean.run(baseDir);
                    gen.run(baseDir);
                } catch (ExecutorException | IOException ex) {
                    LOG.log(Level.WARNING, null, ex);
                }
            }
        });
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException)

Example 25 with WatchEvent

use of java.nio.file.WatchEvent in project streamline by hortonworks.

the class FileWatcher method processEvents.

/**
 * Blocking method to check and dispatch file events.
 * @return Returns false if file watcher will not receive any more events to indicate caller to break out of loop
 */
public boolean processEvents() {
    if (watchKeyPathMap.isEmpty()) {
        return false;
    }
    // wait for key to be signalled
    WatchKey key;
    try {
        key = watchService.take();
    } catch (ClosedWatchServiceException | InterruptedException ex) {
        LOG.info("Watch service interrupted or closed while waiting to get next watch key. Exiting!", ex);
        return false;
    }
    Path dir = watchKeyPathMap.get(key);
    if (dir == null) {
        LOG.info("Unrecognized watch key: " + key + ". Skipping the key without reseting it.");
        return true;
    }
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        if (kind == StandardWatchEventKinds.OVERFLOW) {
            LOG.warn("Overflow event received for key: " + key + ". This means events have been missed or discarded. Please verify.");
            return true;
        }
        // Context for directory entry event is the file name of entry
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path name = ev.context();
        Path child = dir.resolve(name);
        LOG.info("{}: {}", event.kind().name(), child);
        try {
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                watchKeyFileEventHandlerMap.get(key).created(child);
            } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                watchKeyFileEventHandlerMap.get(key).modified(child);
            } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                watchKeyFileEventHandlerMap.get(key).deleted(child);
            }
        } catch (RuntimeException ex) {
            LOG.warn("Exception thrown by handler {} while processing event {}", watchKeyFileEventHandlerMap.get(key), event.kind().name(), ex);
        }
    }
    // reset key and remove from set if directory no longer accessible
    boolean valid = key.reset();
    if (!valid) {
        LOG.info("Key " + key + " not being watched any more as it could not be reset.");
        watchKeyPathMap.remove(key);
        watchKeyFileEventHandlerMap.remove(key);
    }
    return true;
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent)

Aggregations

WatchEvent (java.nio.file.WatchEvent)91 Path (java.nio.file.Path)68 WatchKey (java.nio.file.WatchKey)57 IOException (java.io.IOException)33 File (java.io.File)26 Test (org.junit.Test)24 WatchService (java.nio.file.WatchService)20 BuckEventBus (com.facebook.buck.event.BuckEventBus)13 FakeClock (com.facebook.buck.timing.FakeClock)13 EventBus (com.google.common.eventbus.EventBus)12 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)10 EasyMock.anyObject (org.easymock.EasyMock.anyObject)10 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)6 Subscribe (com.google.common.eventbus.Subscribe)5 FakeWatchmanClient (com.facebook.buck.io.FakeWatchmanClient)4 FileSystems (java.nio.file.FileSystems)4 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)4 HashSet (java.util.HashSet)4 List (java.util.List)4