Search in sources :

Example 6 with WatchEvent

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

the class WatchMonitor method watch.

/**
 * 开始监听事件,阻塞当前进程
 * @param watcher 监听
 * @throws WatchException 监听异常,如果监听关闭抛出此异常
 */
public void watch(Watcher watcher) throws WatchException {
    if (isClosed) {
        throw new WatchException("Watch Monitor is closed !");
    }
    registerPath();
    while (false == isClosed) {
        WatchKey wk;
        try {
            wk = watchService.take();
        } catch (InterruptedException e) {
            // log.warn(e);
            return;
        }
        final Path currentPath = watchKeyPathMap.get(wk);
        WatchEvent.Kind<?> kind;
        for (WatchEvent<?> event : wk.pollEvents()) {
            kind = event.kind();
            if (null != this.filePath && false == this.filePath.endsWith(event.context().toString())) {
                // log.debug("[{}] is not fit for [{}], pass it.", event.context(), this.filePath.getFileName());
                continue;
            }
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                watcher.onCreate(event, currentPath);
            } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                watcher.onModify(event, currentPath);
            } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                watcher.onDelete(event, currentPath);
            } else if (kind == StandardWatchEventKinds.OVERFLOW) {
                watcher.onOverflow(event, currentPath);
            }
        }
        wk.reset();
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Example 7 with WatchEvent

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

the class PathDependencyImpl method run.

// ---------- other methods -----------
/**
 * Our start method fires a thread and this is our run method, which is watching for a given directory path
 */
public void run() {
    Path myDir = Paths.get(m_path);
    try {
        WatchService watcher = myDir.getFileSystem().newWatchService();
        myDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
        while (!Thread.currentThread().isInterrupted()) {
            WatchKey watckKey = watcher.take();
            List<WatchEvent<?>> events = watckKey.pollEvents();
            for (@SuppressWarnings("rawtypes") WatchEvent event : events) {
                final Kind<?> kind = event.kind();
                if (StandardWatchEventKinds.OVERFLOW == kind) {
                    continue;
                }
                if (StandardWatchEventKinds.ENTRY_CREATE == kind) {
                    // Notify the component implementation context that a file has been created.
                    // Later, the component will call our invokeAdd method in order to inject the file
                    // in the component instance
                    m_component.handleEvent(this, EventType.ADDED, new Event(event.context().toString()));
                } else if (StandardWatchEventKinds.ENTRY_DELETE == kind) {
                    // Notify the component implementation context that a file has been removed.
                    // Later, the component will call our invokeRemove method in order to call our component "remove" callback
                    m_component.handleEvent(this, EventType.REMOVED, new Event(event.context().toString()));
                }
            }
            watckKey.reset();
        }
    } catch (Throwable e) {
        m_component.getLogger().err("path dependency exception", e);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) Event(org.apache.felix.dm.context.Event) WatchEvent(java.nio.file.WatchEvent) WatchEvent(java.nio.file.WatchEvent) WatchService(java.nio.file.WatchService)

Example 8 with WatchEvent

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

the class BasicSetting method autoLoad.

/**
 * 在配置文件变更时自动加载
 *
 * @param autoReload 是否自动加载
 */
public void autoLoad(boolean autoReload) {
    if (autoReload) {
        if (null != this.watchMonitor) {
            this.watchMonitor.close();
        }
        try {
            watchMonitor = WatchMonitor.create(this.settingUrl, StandardWatchEventKinds.ENTRY_MODIFY);
            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.settingUrl);
        }
        StaticLog.debug("Auto load for [{}] listenning...", this.settingUrl);
    } 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) SettingRuntimeException(cn.hutool.setting.SettingRuntimeException) SettingRuntimeException(cn.hutool.setting.SettingRuntimeException)

Example 9 with WatchEvent

use of java.nio.file.WatchEvent in project cas by apereo.

the class PathWatcherService method handleEvent.

/**
 * Handle event.
 *
 * @param key the key
 */
private void handleEvent(final WatchKey key) {
    try {
        key.pollEvents().stream().forEach(event -> {
            final String eventName = event.kind().name();
            // The filename is the context of the event.
            final WatchEvent<Path> ev = (WatchEvent<Path>) event;
            final Path filename = ev.context();
            final Path parent = (Path) key.watchable();
            final Path fullPath = parent.resolve(filename);
            final File file = fullPath.toFile();
            LOGGER.trace("Detected event [{}] on file [{}]", eventName, file);
            if (eventName.equals(ENTRY_CREATE.name()) && file.exists()) {
                onCreate.accept(file);
            } else if (eventName.equals(ENTRY_DELETE.name())) {
                onDelete.accept(file);
            } else if (eventName.equals(ENTRY_MODIFY.name()) && file.exists()) {
                onModify.accept(file);
            }
        });
    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Example 10 with WatchEvent

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

the class WatchServicePoller method handleWatchKey.

private List<FileWatcherEvent> handleWatchKey(WatchKey watchKey) {
    final Path watchedPath = (Path) watchKey.watchable();
    Transformer<FileWatcherEvent, WatchEvent<?>> watchEventTransformer = new Transformer<FileWatcherEvent, WatchEvent<?>>() {

        @Override
        public FileWatcherEvent transform(WatchEvent<?> event) {
            WatchEvent.Kind kind = event.kind();
            File file = null;
            if (kind.type() == Path.class) {
                WatchEvent<Path> ev = Cast.uncheckedCast(event);
                file = watchedPath.resolve(ev.context()).toFile();
            }
            return toEvent(kind, file);
        }
    };
    List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
    watchKey.reset();
    if (watchEvents.isEmpty()) {
        return Collections.singletonList(FileWatcherEvent.delete(watchedPath.toFile()));
    } else {
        return CollectionUtils.collect(watchEvents, watchEventTransformer);
    }
}
Also used : Path(java.nio.file.Path) Transformer(org.gradle.api.Transformer) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) FileWatcherEvent(org.gradle.internal.filewatch.FileWatcherEvent)

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