Search in sources :

Example 6 with WatchService

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

the class Jdk7FileWatcherFactory method watch.

@Override
public FileWatcher watch(Action<? super Throwable> onError, FileWatcherListener listener) {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        WatchServiceFileWatcherBacking backing = new WatchServiceFileWatcherBacking(onError, listener, watchService, fileSystem);
        return backing.start(executor);
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
Also used : IOException(java.io.IOException) WatchService(java.nio.file.WatchService)

Example 7 with WatchService

use of java.nio.file.WatchService in project jdk8u_jdk by JetBrains.

the class LotsOfCancels method main.

public static void main(String[] args) throws Exception {
    // create a bunch of directories. Create two tasks for each directory,
    // one to bash on cancel, the other to poll the events
    ExecutorService pool = Executors.newCachedThreadPool();
    try {
        Path top = Files.createTempDirectory("work");
        top.toFile().deleteOnExit();
        for (int i = 1; i <= 16; i++) {
            Path dir = Files.createDirectory(top.resolve("dir-" + i));
            WatchService watcher = FileSystems.getDefault().newWatchService();
            pool.submit(() -> handle(dir, watcher));
            pool.submit(() -> poll(watcher));
        }
    } finally {
        pool.shutdown();
    }
    // give thread pool lots of time to terminate
    if (!pool.awaitTermination(5L, TimeUnit.MINUTES))
        throw new RuntimeException("Thread pool did not terminate");
    if (failed)
        throw new RuntimeException("Test failed, see log for details");
}
Also used : Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) WatchService(java.nio.file.WatchService)

Example 8 with WatchService

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

the class WatchServiceConfigurationTest method testPollingConfig.

@Test
public void testPollingConfig() {
    WatchServiceConfiguration polling = WatchServiceConfiguration.polling(50, MILLISECONDS);
    WatchService watchService = polling.newWatchService(fs.getDefaultView(), fs.getPathService());
    assertThat(watchService).isInstanceOf(PollingWatchService.class);
    PollingWatchService pollingWatchService = (PollingWatchService) watchService;
    assertThat(pollingWatchService.interval).isEqualTo(50);
    assertThat(pollingWatchService.timeUnit).isEqualTo(MILLISECONDS);
}
Also used : WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 9 with WatchService

use of java.nio.file.WatchService in project camel by apache.

the class FileWatcherReloadStrategy method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    if (folder == null) {
        // no folder configured
        return;
    }
    File dir = new File(folder);
    if (dir.exists() && dir.isDirectory()) {
        log.info("Starting ReloadStrategy to watch directory: {}", dir);
        WatchEvent.Modifier modifier = null;
        // if its mac OSX then attempt to apply workaround or warn its slower
        String os = ObjectHelper.getSystemProperty("os.name", "");
        if (os.toLowerCase(Locale.US).startsWith("mac")) {
            // this modifier can speedup the scanner on mac osx (as java on mac has no native file notification integration)
            Class<WatchEvent.Modifier> clazz = getCamelContext().getClassResolver().resolveClass("com.sun.nio.file.SensitivityWatchEventModifier", WatchEvent.Modifier.class);
            if (clazz != null) {
                WatchEvent.Modifier[] modifiers = clazz.getEnumConstants();
                for (WatchEvent.Modifier mod : modifiers) {
                    if ("HIGH".equals(mod.name())) {
                        modifier = mod;
                        break;
                    }
                }
            }
            if (modifier != null) {
                log.info("On Mac OS X the JDK WatchService is slow by default so enabling SensitivityWatchEventModifier.HIGH as workaround");
            } else {
                log.warn("On Mac OS X the JDK WatchService is slow and it may take up till 10 seconds to notice file changes");
            }
        }
        try {
            Path path = dir.toPath();
            WatchService watcher = path.getFileSystem().newWatchService();
            // we cannot support deleting files as we don't know which routes that would be
            if (modifier != null) {
                path.register(watcher, new WatchEvent.Kind<?>[] { ENTRY_CREATE, ENTRY_MODIFY }, modifier);
            } else {
                path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
            }
            task = new WatchFileChangesTask(watcher, path);
            executorService = getCamelContext().getExecutorServiceManager().newSingleThreadExecutor(this, "FileWatcherReloadStrategy");
            executorService.submit(task);
        } catch (IOException e) {
            throw ObjectHelper.wrapRuntimeCamelException(e);
        }
    }
}
Also used : Path(java.nio.file.Path) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) File(java.io.File) WatchService(java.nio.file.WatchService)

Example 10 with WatchService

use of java.nio.file.WatchService in project quasar by puniverse.

the class ActorLoader method monitorFilesystem.

private static void monitorFilesystem(ActorLoader instance, Path moduleDir) {
    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        moduleDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        LOG.info("Filesystem monitor: Watching module directory " + moduleDir + " for changes.");
        for (; ; ) {
            final WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                final WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    // An OVERFLOW event can occur regardless of registration if events are lost or discarded.
                    LOG.warn("Filesystem monitor: filesystem events may have been missed");
                    continue;
                }
                final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                // The filename is the context of the event.
                final Path filename = ev.context();
                // Resolve the filename against the directory.
                final Path child = moduleDir.resolve(filename);
                if (isValidFile(child, kind == ENTRY_DELETE)) {
                    try {
                        final URL jarUrl = child.toUri().toURL();
                        LOG.info("Filesystem monitor: detected module file {} {}", child, kind == ENTRY_CREATE ? "created" : kind == ENTRY_MODIFY ? "modified" : kind == ENTRY_DELETE ? "deleted" : null);
                        if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                            instance.reloadModule(jarUrl);
                        else if (kind == ENTRY_DELETE)
                            instance.unloadModule(jarUrl);
                    } catch (Exception e) {
                        LOG.error("Filesystem monitor: exception while processing " + child, e);
                    }
                } else {
                    if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                        LOG.warn("Filesystem monitor: A non-jar item " + child.getFileName() + " has been placed in the modules directory " + moduleDir);
                }
            }
            if (!key.reset())
                throw new IOException("Directory " + moduleDir + " is no longer accessible");
        }
    } catch (Exception e) {
        LOG.error("Filesystem monitor thread terminated with an exception", e);
        throw Exceptions.rethrow(e);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) WatchService(java.nio.file.WatchService) URL(java.net.URL) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanRegistrationException(javax.management.MBeanRegistrationException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ListenerNotFoundException(javax.management.ListenerNotFoundException)

Aggregations

WatchService (java.nio.file.WatchService)15 Path (java.nio.file.Path)9 WatchEvent (java.nio.file.WatchEvent)7 Test (org.junit.Test)7 IOException (java.io.IOException)6 WatchKey (java.nio.file.WatchKey)6 File (java.io.File)5 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)3 FileSystem (java.nio.file.FileSystem)2 Closeable (java.io.Closeable)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 ClosedFileSystemException (java.nio.file.ClosedFileSystemException)1 ArrayList (java.util.ArrayList)1 ExecutorService (java.util.concurrent.ExecutorService)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 InstanceAlreadyExistsException (javax.management.InstanceAlreadyExistsException)1 ListenerNotFoundException (javax.management.ListenerNotFoundException)1 MBeanRegistrationException (javax.management.MBeanRegistrationException)1 MalformedObjectNameException (javax.management.MalformedObjectNameException)1