Search in sources :

Example 16 with ClosedWatchServiceException

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

the class LotsOfCancels method poll.

/**
     * Polls the given WatchService in a tight loop. This keeps the event
     * queue drained, it also hogs a CPU core which seems necessary to
     * tickle the original bug.
     */
static void poll(WatchService watcher) {
    try {
        for (; ; ) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
    // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
Also used : WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 17 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project OpenGrok by OpenGrok.

the class RuntimeEnvironment method startWatchDogService.

/**
 * Starts a watch dog service for a directory. It automatically reloads the
 * AuthorizationFramework if there was a change in <b>real-time</b>.
 * Suitable for plugin development.
 *
 * You can control start of this service by a configuration parameter
 * {@link Configuration#authorizationWatchdogEnabled}
 *
 * @param directory root directory for plugins
 */
public void startWatchDogService(File directory) {
    stopWatchDogService();
    if (directory == null || !directory.isDirectory() || !directory.canRead()) {
        LOGGER.log(Level.INFO, "Watch dog cannot be started - invalid directory: {0}", directory);
        return;
    }
    LOGGER.log(Level.INFO, "Starting watchdog in: {0}", directory);
    watchDogThread = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                watchDogWatcher = FileSystems.getDefault().newWatchService();
                Path dir = Paths.get(directory.getAbsolutePath());
                Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException {
                        // attach monitor
                        LOGGER.log(Level.FINEST, "Watchdog registering {0}", d);
                        d.register(watchDogWatcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
                        return CONTINUE;
                    }
                });
                LOGGER.log(Level.INFO, "Watch dog started {0}", directory);
                while (!Thread.currentThread().isInterrupted()) {
                    final WatchKey key;
                    try {
                        key = watchDogWatcher.take();
                    } catch (ClosedWatchServiceException x) {
                        break;
                    }
                    boolean reload = false;
                    for (WatchEvent<?> event : key.pollEvents()) {
                        final WatchEvent.Kind<?> kind = event.kind();
                        if (kind == ENTRY_CREATE) {
                            reload = true;
                        } else if (kind == ENTRY_DELETE) {
                            reload = true;
                        } else if (kind == ENTRY_MODIFY) {
                            reload = true;
                        }
                    }
                    if (reload) {
                        // experimental wait if file is being written right now
                        Thread.sleep(THREAD_SLEEP_TIME);
                        getAuthorizationFramework().reload();
                    }
                    if (!key.reset()) {
                        break;
                    }
                }
            } catch (InterruptedException | IOException ex) {
                LOGGER.log(Level.FINEST, "Watchdog finishing (exiting)", ex);
                Thread.currentThread().interrupt();
            }
            LOGGER.log(Level.FINER, "Watchdog finishing (exiting)");
        }
    }, "watchDogService");
    watchDogThread.start();
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent)

Example 18 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project Bytecoder by mirkosertic.

the class PollingWatchService method register.

/**
 * Register the given file with this watch service
 */
@Override
WatchKey register(final Path path, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
    // check events - CCE will be thrown if there are invalid elements
    final Set<WatchEvent.Kind<?>> eventSet = new HashSet<>(events.length);
    for (WatchEvent.Kind<?> event : events) {
        // standard events
        if (event == StandardWatchEventKinds.ENTRY_CREATE || event == StandardWatchEventKinds.ENTRY_MODIFY || event == StandardWatchEventKinds.ENTRY_DELETE) {
            eventSet.add(event);
            continue;
        }
        // OVERFLOW is ignored
        if (event == StandardWatchEventKinds.OVERFLOW) {
            continue;
        }
        // null/unsupported
        if (event == null)
            throw new NullPointerException("An element in event set is 'null'");
        throw new UnsupportedOperationException(event.name());
    }
    if (eventSet.isEmpty())
        throw new IllegalArgumentException("No events to register");
    // Extended modifiers may be used to specify the sensitivity level
    int sensitivity = 10;
    if (modifiers.length > 0) {
        for (WatchEvent.Modifier modifier : modifiers) {
            if (modifier == null)
                throw new NullPointerException();
            if (ExtendedOptions.SENSITIVITY_HIGH.matches(modifier)) {
                sensitivity = ExtendedOptions.SENSITIVITY_HIGH.parameter();
            } else if (ExtendedOptions.SENSITIVITY_MEDIUM.matches(modifier)) {
                sensitivity = ExtendedOptions.SENSITIVITY_MEDIUM.parameter();
            } else if (ExtendedOptions.SENSITIVITY_LOW.matches(modifier)) {
                sensitivity = ExtendedOptions.SENSITIVITY_LOW.parameter();
            } else {
                throw new UnsupportedOperationException("Modifier not supported");
            }
        }
    }
    // check if watch service is closed
    if (!isOpen())
        throw new ClosedWatchServiceException();
    // attributes of the entries in the directory.
    try {
        int value = sensitivity;
        return AccessController.doPrivileged(new PrivilegedExceptionAction<PollingWatchKey>() {

            @Override
            public PollingWatchKey run() throws IOException {
                return doPrivilegedRegister(path, eventSet, value);
            }
        });
    } catch (PrivilegedActionException pae) {
        Throwable cause = pae.getCause();
        if (cause != null && cause instanceof IOException)
            throw (IOException) cause;
        throw new AssertionError(pae);
    }
}
Also used : PrivilegedActionException(java.security.PrivilegedActionException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) IOException(java.io.IOException) WatchEvent(java.nio.file.WatchEvent) HashSet(java.util.HashSet)

Example 19 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project zeppelin by apache.

the class InterpreterOutputChangeWatcher method run.

public void run() {
    while (!stop) {
        WatchKey key = null;
        try {
            key = watcher.poll(1, TimeUnit.SECONDS);
        } catch (InterruptedException | ClosedWatchServiceException e) {
            break;
        }
        if (key == null) {
            continue;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();
            // search for filename
            synchronized (watchKeys) {
                for (File f : watchFiles) {
                    if (f.getName().compareTo(filename.toString()) == 0) {
                        File changedFile;
                        if (filename.isAbsolute()) {
                            changedFile = new File(filename.toString());
                        } else {
                            changedFile = new File(watchKeys.get(key), filename.toString());
                        }
                        logger.info("File change detected " + changedFile.getAbsolutePath());
                        if (listener != null) {
                            listener.fileChanged(changedFile);
                        }
                    }
                }
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Example 20 with ClosedWatchServiceException

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

the class PathWatcherService method run.

@Override
public void run() {
    try {
        var key = (WatchKey) null;
        while ((key = watcher.take()) != null) {
            handleEvent(key);
            val valid = key.reset();
            if (!valid) {
                LOGGER.info("Directory key is no longer valid. Quitting watcher service");
            }
        }
    } catch (final InterruptedException | ClosedWatchServiceException e) {
        LOGGER.trace(e.getMessage(), e);
        Thread.currentThread().interrupt();
    }
}
Also used : lombok.val(lombok.val) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Aggregations

ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)21 WatchKey (java.nio.file.WatchKey)16 Path (java.nio.file.Path)14 WatchEvent (java.nio.file.WatchEvent)11 IOException (java.io.IOException)8 WatchService (java.nio.file.WatchService)7 File (java.io.File)6 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 Test (org.junit.Test)3 FileSystems (java.nio.file.FileSystems)2 NotDirectoryException (java.nio.file.NotDirectoryException)2 ENTRY_MODIFY (java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY)2 Kind (java.nio.file.WatchEvent.Kind)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ExecutorService (java.util.concurrent.ExecutorService)2 TimeUnit (java.util.concurrent.TimeUnit)2 MocoException (com.github.dreamhead.moco.MocoException)1 Files (com.github.dreamhead.moco.util.Files)1