Search in sources :

Example 31 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 32 with WatchService

use of java.nio.file.WatchService in project Gargoyle by callakrsos.

the class FileUtilTest method watchTest.

@Test
public void watchTest() throws IOException {
    File file = new File("c:\\someDir");
    file.mkdirs();
    WatchService newWatchService = FileSystems.getDefault().newWatchService();
    WatchKey register = file.toPath().register(newWatchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    System.out.println("Watch Service Registered ..");
    while (true) {
        try {
            System.out.println("start");
            WatchKey key = newWatchService.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path fileName = ev.context();
                System.out.println(kind.name() + ": " + fileName);
                if (key == ENTRY_MODIFY && fileName.toString().equals("DirectoryWatchDemo.java")) {
                    System.out.println("My source file has changed!!!");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        } catch (InterruptedException e) {
            break;
        }
    }
    System.out.println("end ");
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 33 with WatchService

use of java.nio.file.WatchService in project opennms by OpenNMS.

the class DirectoryWatcher method run.

/* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
@Override
@SuppressWarnings("unchecked")
public void run() {
    LOG.info("starting run loop");
    try (WatchService watcher = m_path.getFileSystem().newWatchService()) {
        LOG.debug("registering create watcher on {}", m_path.toAbsolutePath().toString());
        m_path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        LOG.debug("watcher registration complete for {}", m_path.toAbsolutePath().toString());
        synchronized (this) {
            this.notifyAll();
        }
        while (true) {
            if (m_thread.isInterrupted()) {
                break;
            }
            WatchKey key = null;
            try {
                LOG.debug("waiting for create event");
                key = watcher.take();
                LOG.debug("got an event, process it");
            } catch (InterruptedException ie) {
                LOG.info("interruped, must be time to shut down...");
                break;
            }
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                WatchEvent.Kind<?> kind = watchEvent.kind();
                Path pathChanged = ((WatchEvent<Path>) watchEvent).context();
                final String fileName = pathChanged.toString();
                final File file = new File(m_directory, fileName);
                if (file.isDirectory()) {
                    // Ignoring changes on directories.
                    LOG.debug("{} is a directory, ignoring.", file);
                    continue;
                }
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    LOG.debug("overflow receiving, ignoring changes.");
                    continue;
                } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                    LOG.info("file '{}' created. Ignoring...", fileName);
                } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                    LOG.info("file '{}' modified. Removing entry from cache.", fileName);
                    m_contents.remove(fileName);
                } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                    LOG.info("file '{}' deleted. Removing entry from cache.", fileName);
                    m_contents.remove(fileName);
                }
                // IMPORTANT: The key must be reset after processed
                if (!key.reset()) {
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe);
    }
    LOG.info("existing run loop");
}
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) File(java.io.File)

Example 34 with WatchService

use of java.nio.file.WatchService in project spf4j by zolyfarkas.

the class TSDBReader method watch.

// CHECKSTYLE:OFF
@SuppressFBWarnings("NOS_NON_OWNED_SYNCHRONIZATION")
public <E extends Exception> void watch(final Handler<Either<TableDef, DataBlock>, E> handler, final EventSensitivity es) throws IOException, InterruptedException, E {
    // CHECKSTYLE:ON
    synchronized (this) {
        if (watch) {
            throw new IllegalStateException("File is already watched " + file);
        }
        watch = true;
    }
    SensitivityWatchEventModifier sensitivity;
    switch(es) {
        case LOW:
            sensitivity = SensitivityWatchEventModifier.LOW;
            break;
        case MEDIUM:
            sensitivity = SensitivityWatchEventModifier.MEDIUM;
            break;
        case HIGH:
            sensitivity = SensitivityWatchEventModifier.HIGH;
            break;
        default:
            throw new UnsupportedOperationException("Unsupported sensitivity " + es);
    }
    final Path path = file.getParentFile().toPath();
    try (WatchService watchService = path.getFileSystem().newWatchService()) {
        path.register(watchService, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW }, sensitivity);
        readAll(handler);
        do {
            WatchKey key = watchService.poll(1000, TimeUnit.MILLISECONDS);
            if (key == null) {
                if (reReadSize()) {
                    readAll(handler);
                }
                continue;
            }
            if (!key.isValid()) {
                key.cancel();
                break;
            }
            if (!key.pollEvents().isEmpty()) {
                if (reReadSize()) {
                    readAll(handler);
                }
            }
            if (!key.reset()) {
                key.cancel();
                break;
            }
        } while (watch);
    } finally {
        watch = false;
    }
}
Also used : Path(java.nio.file.Path) SensitivityWatchEventModifier(com.sun.nio.file.SensitivityWatchEventModifier) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) WatchService(java.nio.file.WatchService) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 35 with WatchService

use of java.nio.file.WatchService in project cryptofs by cryptomator.

the class CryptoPathTest method testRegisterWithThreeParamsThrowsUnsupportedOperationException.

@Test
public void testRegisterWithThreeParamsThrowsUnsupportedOperationException() throws IOException {
    WatchService irrelevantWatcher = null;
    WatchEvent.Kind<?>[] irrelevantWatchEvents = null;
    WatchEvent.Modifier[] irrelevantModifiers = null;
    thrown.expect(UnsupportedOperationException.class);
    rootPath.register(irrelevantWatcher, irrelevantWatchEvents, irrelevantModifiers);
}
Also used : WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Aggregations

WatchService (java.nio.file.WatchService)56 Path (java.nio.file.Path)40 WatchKey (java.nio.file.WatchKey)32 WatchEvent (java.nio.file.WatchEvent)23 IOException (java.io.IOException)21 Test (org.junit.Test)18 File (java.io.File)16 FileSystem (java.nio.file.FileSystem)6 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)5 Kind (java.nio.file.WatchEvent.Kind)5 FileSystems (java.nio.file.FileSystems)4 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)4 SensitivityWatchEventModifier (com.sun.nio.file.SensitivityWatchEventModifier)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 TimeUnit (java.util.concurrent.TimeUnit)3 BufferedReader (java.io.BufferedReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2