Search in sources :

Example 66 with WatchEvent

use of java.nio.file.WatchEvent in project rxjava-file by davidmoten.

the class FileObservableTest method testNoEventsThrownIfFileDoesNotExist.

@Test
public void testNoEventsThrownIfFileDoesNotExist() throws InterruptedException {
    File file = new File("target/does-not-exist");
    Observable<WatchEvent<?>> events = FileObservable.from(file, ENTRY_MODIFY);
    final CountDownLatch latch = new CountDownLatch(1);
    Subscription sub = events.subscribeOn(Schedulers.io()).subscribe(new Observer<WatchEvent<?>>() {

        @Override
        public void onCompleted() {
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            latch.countDown();
            e.printStackTrace();
        }

        @Override
        public void onNext(WatchEvent<?> arg0) {
            latch.countDown();
        }
    });
    assertFalse(latch.await(100, TimeUnit.MILLISECONDS));
    sub.unsubscribe();
}
Also used : WatchEvent(java.nio.file.WatchEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Subscription(rx.Subscription) File(java.io.File) Test(org.junit.Test)

Example 67 with WatchEvent

use of java.nio.file.WatchEvent in project wicket by apache.

the class Nio2ModificationWatcher method checkCreated.

/**
 * Checks for newly created files and folders.
 * New folders are registered to be watched.
 * New files are removed from the MarkupCache because there could be
 * {@link org.apache.wicket.markup.Markup#NO_MARKUP} (Not Found) entries for them already.
 * @param log
 *              a logger that can be used to log the events
 */
protected void checkCreated(Logger log) {
    WatchKey watchKey = watchService.poll();
    if (watchKey != null) {
        List<WatchEvent<?>> events = watchKey.pollEvents();
        for (WatchEvent<?> event : events) {
            WatchEvent.Kind<?> eventKind = event.kind();
            Path eventPath = (Path) event.context();
            if (eventKind == ENTRY_CREATE) {
                entryCreated(eventPath, log);
            } else if (eventKind == ENTRY_DELETE) {
                entryDeleted(eventPath, log);
            } else if (eventKind == ENTRY_MODIFY) {
                entryModified(eventPath, log);
            }
        }
        watchKey.reset();
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Example 68 with WatchEvent

use of java.nio.file.WatchEvent in project hutool by looly.

the class Props method autoLoad.

/**
 * 在配置文件变更时自动加载
 *
 * @param autoReload 是否自动加载
 */
public void autoLoad(boolean autoReload) {
    if (autoReload) {
        if (null != this.watchMonitor) {
            this.watchMonitor.close();
            try {
                watchMonitor = WatchMonitor.create(Paths.get(this.propertiesFileUrl.toURI()));
                watchMonitor.setWatcher(new SimpleWatcher() {

                    @Override
                    public void onModify(WatchEvent<?> event, Path currentPath) {
                        load();
                    }
                }).start();
            } catch (Exception e) {
                throw new SettingRuntimeException(e, "Setting auto load not support url: [{}]", this.propertiesFileUrl);
            }
        }
    } else {
        IoUtil.close(this.watchMonitor);
        this.watchMonitor = null;
    }
}
Also used : Path(java.nio.file.Path) WatchEvent(java.nio.file.WatchEvent) SimpleWatcher(cn.hutool.core.io.watch.SimpleWatcher) IORuntimeException(cn.hutool.core.io.IORuntimeException) IOException(java.io.IOException) SettingRuntimeException(cn.hutool.setting.SettingRuntimeException) SettingRuntimeException(cn.hutool.setting.SettingRuntimeException)

Example 69 with WatchEvent

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

the class StreamFilesP method drainWatcherEvents.

/**
 * @return false, if the watcher should be closed
 */
private boolean drainWatcherEvents() {
    final ILogger logger = getLogger();
    // poll with blocking only when there is no other work to do
    final WatchKey key;
    try {
        key = (currentFile == null && eventQueue.isEmpty()) ? watcher.poll(1, SECONDS) : watcher.poll();
    } catch (InterruptedException e) {
        return false;
    }
    if (key == null) {
        if (!Files.exists(watchedDirectory)) {
            logger.info("Directory " + watchedDirectory + " does not exist, stopped watching");
            return false;
        }
        return true;
    }
    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.");
        return false;
    }
    return true;
}
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 70 with WatchEvent

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

the class FileModificationEventWatcher method run.

@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
    WatchKey watchKey = null;
    WatchService watchService = null;
    try {
        watchService = FileSystems.getDefault().newWatchService();
        log.debug("Done creating watch service for watching file at path: {}", this.watchedFilePath);
        String fileName = getWatchedFileName();
        Path directoryPath = getWatchedDirectory();
        log.debug("Directory being watched is {}", directoryPath);
        assert directoryPath != null;
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
        log.debug("Registered the watch for the file: {}", this.watchedFilePath);
        isWatchRegistered = true;
        while (!Thread.currentThread().isInterrupted()) {
            try {
                watchKey = retrieveWatchKeyFrom(watchService);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logException(e);
            // Allow thread to exit.
            }
            if (watchKey != null) {
                Optional<WatchEvent<?>> modificationDetectionEvent = watchKey.pollEvents().stream().filter(event -> event.context().toString().contains(fileName)).findAny();
                if (modificationDetectionEvent.isPresent()) {
                    log.info("Detected that the file [{}] has modified", this.watchedFilePath);
                    callback.accept(modificationDetectionEvent.get());
                }
                boolean isKeyValid = watchKey.reset();
                log.debug("Done resetting watch key.");
                if (!isKeyValid) {
                    log.info("No longer watching file [{}]", this.watchedFilePath);
                    break;
                }
            }
            if (!loopContinuously) {
                break;
            }
        }
    } catch (IOException e) {
        logException(e);
        throw new RuntimeException(e);
    } finally {
        if (watchKey != null) {
            watchKey.cancel();
        }
        if (watchService != null) {
            try {
                watchService.close();
            } catch (IOException e) {
                log.warn("Error closing watch service", e);
            }
        }
    }
    log.info("Thread [{}], watching for modifications in file [{}] exiting,", getName(), this.watchedFilePath);
}
Also used : Path(java.nio.file.Path) NonNull(lombok.NonNull) WatchEvent(java.nio.file.WatchEvent) Exceptions(io.pravega.common.Exceptions) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) WatchKey(java.nio.file.WatchKey) Consumer(java.util.function.Consumer) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) WatchService(java.nio.file.WatchService) Slf4j(lombok.extern.slf4j.Slf4j) InvalidPathException(java.nio.file.InvalidPathException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Path(java.nio.file.Path) FileSystems(java.nio.file.FileSystems) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) WatchService(java.nio.file.WatchService)

Aggregations

WatchEvent (java.nio.file.WatchEvent)92 Path (java.nio.file.Path)68 WatchKey (java.nio.file.WatchKey)58 IOException (java.io.IOException)33 File (java.io.File)27 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