Search in sources :

Example 66 with WatchKey

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

the class ConfigurationDirectoryPathWatchService method watch.

/**
     * Watch the directory for changes.
     */
public void watch() {
    long lastModified = System.currentTimeMillis();
    while (true) {
        final WatchKey key;
        try {
            key = watcher.take();
        } catch (final InterruptedException e) {
            LOGGER.warn(e.getMessage(), e);
            return;
        }
        for (final WatchEvent<?> event : key.pollEvents()) {
            final WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                LOGGER.warn("An overflow event occurred. File system events may be lost or discarded.");
                continue;
            }
            final WatchEvent<Path> ev = (WatchEvent<Path>) event;
            final Path filename = ev.context();
            try {
                final Path child = this.directory.resolve(filename);
                if (System.currentTimeMillis() - lastModified >= MONITOR_INTERVAL) {
                    LOGGER.debug("Detected configuration change [{}]", kind.name());
                    if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_CREATE.name(), kind.name())) {
                        this.eventPublisher.publishEvent(new CasConfigurationCreatedEvent(this, child));
                    }
                    if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_DELETE.name(), kind.name())) {
                        this.eventPublisher.publishEvent(new CasConfigurationDeletedEvent(this, child));
                    }
                    if (StringUtils.equalsIgnoreCase(StandardWatchEventKinds.ENTRY_MODIFY.name(), kind.name())) {
                        this.eventPublisher.publishEvent(new CasConfigurationModifiedEvent(this, child));
                    }
                    lastModified = System.currentTimeMillis();
                }
            } catch (final Exception e) {
                LOGGER.warn(e.getMessage(), e);
                continue;
            }
        }
        final boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) CasConfigurationCreatedEvent(org.apereo.cas.support.events.config.CasConfigurationCreatedEvent) WatchKey(java.nio.file.WatchKey) CasConfigurationModifiedEvent(org.apereo.cas.support.events.config.CasConfigurationModifiedEvent) WatchEvent(java.nio.file.WatchEvent) CasConfigurationDeletedEvent(org.apereo.cas.support.events.config.CasConfigurationDeletedEvent)

Example 67 with WatchKey

use of java.nio.file.WatchKey in project che by eclipse.

the class FileWatcherService method run.

private void run() {
    suspended.compareAndSet(true, false);
    running.compareAndSet(false, true);
    while (running.get()) {
        try {
            WatchKey watchKey = service.take();
            Path dir = keys.get(watchKey);
            if (suspended.get()) {
                resetAndRemove(watchKey, dir);
                LOG.debug("File watchers are running in suspended mode - skipping.");
                continue;
            }
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    LOG.warn("Detected file system events overflowing");
                    continue;
                }
                WatchEvent<Path> ev = cast(event);
                Path item = ev.context();
                Path path = dir.resolve(item).toAbsolutePath();
                if (isExcluded(excludes, path)) {
                    LOG.debug("Path is within exclude list, skipping...");
                    continue;
                }
                handler.handle(path, kind);
            }
            resetAndRemove(watchKey, dir);
        } catch (InterruptedException e) {
            running.compareAndSet(true, false);
            LOG.debug("Interruption error when running file watcher, most likely caused by stopping it", e);
        } catch (ClosedWatchServiceException e) {
            running.compareAndSet(true, false);
            LOG.debug("Closing watch service while some of keys may be processing", e);
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 68 with WatchKey

use of java.nio.file.WatchKey in project che by eclipse.

the class FileTreeWatcher method setupDirectoryWatcher.

private void setupDirectoryWatcher(Path directory) throws IOException {
    if (watchedDirectories.get(directory) == null) {
        WatchKey watchKey = directory.register(watchService, new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW }, watchEventModifiers);
        WatchedDirectory watchedDirectory = new WatchedDirectory(directory, watchKey);
        try (DirectoryStream<Path> entries = Files.newDirectoryStream(directory)) {
            for (Path entry : entries) {
                watchedDirectory.addItem(new DirectoryItem(entry.getFileName(), Files.isDirectory(entry), getLastModifiedInMillis(entry)));
                if (Files.isDirectory(entry)) {
                    setupDirectoryWatcher(entry);
                }
            }
        }
        watchedDirectories.put(directory, watchedDirectory);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

Example 69 with WatchKey

use of java.nio.file.WatchKey in project jetty.project by eclipse.

the class PathWatcher method run.

/** 
     * Forever loop.
     * 
     * Wait for the WatchService to report some filesystem events for the
     * watched paths.
     * 
     * When an event for a path first occurs, it is subjected to a quiet time.
     * Subsequent events that arrive for the same path during this quiet time are
     * accumulated and the timer reset. Only when the quiet time has expired are
     * the accumulated events sent. MODIFY events are handled slightly differently -
     * multiple MODIFY events arriving within a quiet time are coalesced into a
     * single MODIFY event. Both the accumulation of events and coalescing of MODIFY
     * events reduce the number and frequency of event reporting for "noisy" files (ie
     * those that are undergoing rapid change).
     * 
     * @see java.lang.Runnable#run()
     */
@Override
public void run() {
    List<PathWatchEvent> notifiableEvents = new ArrayList<PathWatchEvent>();
    // Start the java.nio watching
    if (LOG.isDebugEnabled()) {
        LOG.debug("Starting java.nio file watching with {}", watchService);
    }
    while (watchService != null && thread == Thread.currentThread()) {
        WatchKey key = null;
        try {
            //If no pending events, wait forever for new events
            if (pendingEvents.isEmpty()) {
                if (NOISY_LOG.isDebugEnabled())
                    NOISY_LOG.debug("Waiting for take()");
                key = watchService.take();
            } else {
                //only wait as long as the quiet time for any new events
                if (NOISY_LOG.isDebugEnabled())
                    NOISY_LOG.debug("Waiting for poll({}, {})", updateQuietTimeDuration, updateQuietTimeUnit);
                key = watchService.poll(updateQuietTimeDuration, updateQuietTimeUnit);
                //If no new events its safe to process the pendings
                if (key == null) {
                    long now = System.currentTimeMillis();
                    // no new event encountered.
                    for (Path path : new HashSet<Path>(pendingEvents.keySet())) {
                        PathPendingEvents pending = pendingEvents.get(path);
                        if (pending.isQuiet(now, updateQuietTimeDuration, updateQuietTimeUnit)) {
                            //so generate the events that were pent up
                            for (PathWatchEvent p : pending.getEvents()) {
                                notifiableEvents.add(p);
                            }
                            // remove from pending list
                            pendingEvents.remove(path);
                        }
                    }
                }
            }
        } catch (ClosedWatchServiceException e) {
            // Normal shutdown of watcher
            return;
        } catch (InterruptedException e) {
            if (isRunning()) {
                LOG.warn(e);
            } else {
                LOG.ignore(e);
            }
            return;
        }
        //If there was some new events to process
        if (key != null) {
            Config config = keys.get(key);
            if (config == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("WatchKey not recognized: {}", key);
                }
                continue;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                @SuppressWarnings("unchecked") WatchEvent.Kind<Path> kind = (Kind<Path>) event.kind();
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = config.dir.resolve(name);
                if (kind == ENTRY_CREATE) {
                    // recursively
                    if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
                        try {
                            prepareConfig(config.asSubConfig(child));
                        } catch (IOException e) {
                            LOG.warn(e);
                        }
                    } else if (config.matches(child)) {
                        addToPendingList(child, new PathWatchEvent(child, ev));
                    }
                } else if (config.matches(child)) {
                    addToPendingList(child, new PathWatchEvent(child, ev));
                }
            }
        }
        //Send any notifications generated this pass
        notifyOnPathWatchEvents(notifiableEvents);
        notifiableEvents.clear();
        if (key != null && !key.reset()) {
            keys.remove(key);
            if (keys.isEmpty()) {
                // all done, no longer monitoring anything
                return;
            }
        }
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) IOException(java.io.IOException) Kind(java.nio.file.WatchEvent.Kind) WatchEvent(java.nio.file.WatchEvent) HashSet(java.util.HashSet)

Example 70 with WatchKey

use of java.nio.file.WatchKey in project Orchid by JavaEden.

the class FileWatcher method processEvents.

private void processEvents() {
    while (true) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }
        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            Path child = dir.resolve(name);
            context.broadcast(Orchid.Events.FILES_CHANGED);
            if (kind == ENTRY_CREATE) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException)

Aggregations

WatchKey (java.nio.file.WatchKey)134 Path (java.nio.file.Path)88 WatchEvent (java.nio.file.WatchEvent)65 IOException (java.io.IOException)49 WatchService (java.nio.file.WatchService)30 File (java.io.File)27 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)18 ArrayList (java.util.ArrayList)10 Test (org.junit.Test)10 HashMap (java.util.HashMap)7 Map (java.util.Map)7 FileSystems (java.nio.file.FileSystems)6 FileVisitResult (java.nio.file.FileVisitResult)6 HashSet (java.util.HashSet)6 List (java.util.List)6 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)5 InputStream (java.io.InputStream)4 AccessDeniedException (java.nio.file.AccessDeniedException)4 Kind (java.nio.file.WatchEvent.Kind)4 Logger (org.slf4j.Logger)4