Search in sources :

Example 31 with WatchEvent

use of java.nio.file.WatchEvent in project moco by dreamhead.

the class WatcherService method loop.

private void loop() {
    try {
        WatchKey key = service.take();
        Collection<Path> paths = keys.get(key);
        List<WatchEvent<?>> events = key.pollEvents().stream().filter(e -> e.kind().equals(ENTRY_MODIFY)).collect(Collectors.toList());
        for (WatchEvent<?> event : events) {
            final Path context = (Path) event.context();
            List<Path> contextPaths = paths.stream().filter(p -> p.endsWith(context)).collect(Collectors.toList());
            for (Path path : contextPaths) {
                for (Function<File, Void> listener : this.listeners.get(path)) {
                    listener.apply(path.toFile());
                }
                break;
            }
        }
        key.reset();
    } catch (ClosedWatchServiceException ignored) {
    } catch (InterruptedException e) {
        logger.error("Error happens", e);
    }
}
Also used : Path(java.nio.file.Path) LoggerFactory(org.slf4j.LoggerFactory) HIGH(com.sun.nio.file.SensitivityWatchEventModifier.HIGH) MocoException(com.github.dreamhead.moco.MocoException) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) WatchKey(java.nio.file.WatchKey) Future(java.util.concurrent.Future) MocoExecutors(com.github.dreamhead.moco.util.MocoExecutors) HashMultimap(com.google.common.collect.HashMultimap) Map(java.util.Map) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) Files(com.github.dreamhead.moco.util.Files) ENTRY_MODIFY(java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) Logger(org.slf4j.Logger) Idles.idle(com.github.dreamhead.moco.util.Idles.idle) Maps.newHashMap(com.google.common.collect.Maps.newHashMap) WatchEvent(java.nio.file.WatchEvent) Collection(java.util.Collection) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) WatchService(java.nio.file.WatchService) List(java.util.List) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) FileSystems(java.nio.file.FileSystems) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Example 32 with WatchEvent

use of java.nio.file.WatchEvent in project jimfs by google.

the class AbstractWatchServiceTest method testPostEvent.

@Test
public void testPostEvent() throws IOException {
    AbstractWatchService.Key key = watcher.register(new StubWatchable(), ImmutableSet.of(ENTRY_CREATE));
    AbstractWatchService.Event<Path> event = new AbstractWatchService.Event<>(ENTRY_CREATE, 1, null);
    key.post(event);
    key.signal();
    assertThat(watcher.queuedKeys()).containsExactly(key);
    WatchKey retrievedKey = watcher.poll();
    assertThat(retrievedKey).isEqualTo(key);
    List<WatchEvent<?>> events = retrievedKey.pollEvents();
    assertThat(events).hasSize(1);
    assertThat(events.get(0)).isEqualTo(event);
    // polling should have removed all events
    assertThat(retrievedKey.pollEvents()).isEmpty();
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) WatchEvent(java.nio.file.WatchEvent) Test(org.junit.Test)

Example 33 with WatchEvent

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

the class PutHeadChunkRunnable method waitUntilFileHasGrown.

private void waitUntilFileHasGrown(File pendingFile) {
    try {
        if (watcher == null) {
            initWatcher(pendingFile.getParent());
        }
        watchKey = watcher.poll(5, TimeUnit.SECONDS);
        if (watchKey == null) {
            return;
        }
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == StandardWatchEventKinds.OVERFLOW) {
                continue;
            }
            @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();
            if (filename.toString().equals(pendingFile.getName())) {
                break;
            }
        }
    } catch (IOException | InterruptedException ex) {
        LOGGER.warn(ex.getMessage(), ex);
    }
}
Also used : Path(java.nio.file.Path) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException)

Example 34 with WatchEvent

use of java.nio.file.WatchEvent in project dubbo by alibaba.

the class FileSystemDynamicConfiguration method processWatchEvents.

/**
 * Process the {@link WatchEvent WatchEvents} loop in async execution
 *
 * @param watchService {@link WatchService}
 */
private void processWatchEvents(WatchService watchService) {
    getWatchEventsLoopThreadPool().execute(() -> {
        // WatchEvents Loop
        while (true) {
            WatchKey watchKey = null;
            try {
                watchKey = watchService.take();
                if (watchKey.isValid()) {
                    for (WatchEvent event : watchKey.pollEvents()) {
                        WatchEvent.Kind kind = event.kind();
                        // configChangeType's key to match WatchEvent's Kind
                        ConfigChangeType configChangeType = CONFIG_CHANGE_TYPES_MAP.get(kind.name());
                        if (configChangeType != null) {
                            Path configDirectoryPath = (Path) watchKey.watchable();
                            Path currentPath = (Path) event.context();
                            Path configFilePath = configDirectoryPath.resolve(currentPath);
                            File configDirectory = configDirectoryPath.toFile();
                            executeMutually(configDirectory, () -> {
                                fireConfigChangeEvent(configDirectory, configFilePath.toFile(), configChangeType);
                                signalConfigDirectory(configDirectory);
                                return null;
                            });
                        }
                    }
                }
            } catch (Exception e) {
                return;
            } finally {
                if (watchKey != null) {
                    // reset
                    watchKey.reset();
                }
            }
        }
    });
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) ConfigChangeType(org.apache.dubbo.common.config.configcenter.ConfigChangeType) File(java.io.File) IOException(java.io.IOException)

Example 35 with WatchEvent

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

the class FileChangeWatcherTest method testCallbackWorksOnFileAdded.

@Test
public void testCallbackWorksOnFileAdded() throws IOException, InterruptedException {
    FileChangeWatcher watcher = null;
    try {
        final List<WatchEvent<?>> events = new ArrayList<>();
        watcher = new FileChangeWatcher(tempDir.toPath(), event -> {
            LOG.info("Got an update: {} {}", event.kind(), event.context());
            synchronized (events) {
                events.add(event);
                events.notifyAll();
            }
        });
        watcher.start();
        watcher.waitForState(FileChangeWatcher.State.RUNNING);
        // TODO hack
        Thread.sleep(1000L);
        File tempFile2 = File.createTempFile("zk_test_", "", tempDir);
        tempFile2.deleteOnExit();
        synchronized (events) {
            if (events.isEmpty()) {
                events.wait(FS_TIMEOUT);
            }
            assertFalse(events.isEmpty());
            WatchEvent<?> event = events.get(0);
            assertEquals(StandardWatchEventKinds.ENTRY_CREATE, event.kind());
            assertEquals(tempFile2.getName(), event.context().toString());
        }
    } finally {
        if (watcher != null) {
            watcher.stop();
            watcher.waitForState(FileChangeWatcher.State.STOPPED);
        }
    }
}
Also used : Logger(org.slf4j.Logger) WatchEvent(java.nio.file.WatchEvent) LoggerFactory(org.slf4j.LoggerFactory) ZKTestCase(org.apache.zookeeper.ZKTestCase) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ArrayList(java.util.ArrayList) AfterAll(org.junit.jupiter.api.AfterAll) Test(org.junit.jupiter.api.Test) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) List(java.util.List) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BeforeAll(org.junit.jupiter.api.BeforeAll) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ClientBase(org.apache.zookeeper.test.ClientBase) ArrayList(java.util.ArrayList) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) Test(org.junit.jupiter.api.Test)

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