Search in sources :

Example 1 with ClosedWatchServiceException

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

the class FileSystemWatcher method take.

// take is blocking
public File take() throws IOException {
    File next = poll();
    if (next != null) {
        return next;
    }
    if (done || !isFeed) {
        return null;
    }
    // No file was found, wait for the filesystem to push events
    WatchKey key;
    while (!it.hasNext()) {
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            if (LOGGER.isEnabledFor(Level.WARN)) {
                LOGGER.warn("Feed Closed");
            }
            if (watcher == null) {
                return null;
            }
            continue;
        } catch (ClosedWatchServiceException e) {
            if (LOGGER.isEnabledFor(Level.WARN)) {
                LOGGER.warn("The watcher has exited");
            }
            if (watcher == null) {
                return null;
            }
            continue;
        }
        handleEvents(key);
        if (endOfEvents(key)) {
            return null;
        }
    }
    // files were found, re-create the iterator and move it one step
    return it.next();
}
Also used : WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) File(java.io.File)

Example 2 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project curiostack by curioswitch.

the class FileWatcher method listenForFileEvents.

private void listenForFileEvents() {
    for (; ; ) {
        final WatchKey key;
        try {
            key = watchService.take();
        } catch (ClosedWatchServiceException | InterruptedException ex) {
            return;
        }
        key.pollEvents().stream().filter(e -> e.kind() != StandardWatchEventKinds.OVERFLOW).map(e -> {
            // Only support Path
            @SuppressWarnings("unchecked") WatchEvent<Path> cast = (WatchEvent<Path>) e;
            return cast.context();
        }).forEach(path -> {
            final Path resolved;
            try {
                resolved = watchedDirs.get(key).resolve(path).toRealPath();
            } catch (IOException e) {
                logger.warn("Unexpected exception resolving path: {}", path, e);
                return;
            }
            Optional<Consumer<Path>> callback = registeredPaths.entrySet().stream().filter(e -> {
                try {
                    return e.getKey().toRealPath().equals(resolved);
                } catch (IOException ex) {
                    logger.warn("Unexpected exception resolving path: {}", e.getKey(), ex);
                    return false;
                }
            }).map(Entry::getValue).findFirst();
            if (callback.isPresent()) {
                logger.info("Processing update to path: " + resolved);
                try {
                    callback.get().accept(resolved);
                } catch (Exception e) {
                    logger.warn("Unexpected exception processing update to path: {}", resolved, e);
                }
            } else {
                logger.info("Could not find callback for path: {}", resolved);
            }
        });
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : ImmutableMap(com.google.common.collect.ImmutableMap) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) HashMap(java.util.HashMap) Executors(java.util.concurrent.Executors) UncheckedIOException(java.io.UncheckedIOException) WatchKey(java.nio.file.WatchKey) Consumer(java.util.function.Consumer) Inject(javax.inject.Inject) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) WatchService(java.nio.file.WatchService) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) Logger(org.apache.logging.log4j.Logger) Map(java.util.Map) Entry(java.util.Map.Entry) Optional(java.util.Optional) Path(java.nio.file.Path) LogManager(org.apache.logging.log4j.LogManager) FileSystems(java.nio.file.FileSystems) ExecutorService(java.util.concurrent.ExecutorService) Path(java.nio.file.Path) Consumer(java.util.function.Consumer) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 3 with ClosedWatchServiceException

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

the class PollingWatchService method doPrivilegedRegister.

// registers directory returning a new key if not already registered or
// existing key if already registered
private PollingWatchKey doPrivilegedRegister(Path path, Set<? extends WatchEvent.Kind<?>> events, int sensitivityInSeconds) throws IOException {
    // check file is a directory and get its file key if possible
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    if (!attrs.isDirectory()) {
        throw new NotDirectoryException(path.toString());
    }
    Object fileKey = attrs.fileKey();
    if (fileKey == null)
        throw new AssertionError("File keys must be supported");
    // grab close lock to ensure that watch service cannot be closed
    synchronized (closeLock()) {
        if (!isOpen())
            throw new ClosedWatchServiceException();
        PollingWatchKey watchKey;
        synchronized (map) {
            watchKey = map.get(fileKey);
            if (watchKey == null) {
                // new registration
                watchKey = new PollingWatchKey(path, this, fileKey);
                map.put(fileKey, watchKey);
            } else {
                // update to existing registration
                watchKey.disable();
            }
        }
        watchKey.enable(events, sensitivityInSeconds);
        return watchKey;
    }
}
Also used : NotDirectoryException(java.nio.file.NotDirectoryException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 4 with ClosedWatchServiceException

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

the class WatchServiceFileSystemWatcher method run.

@Override
public void run() {
    while (!stopped) {
        try {
            final WatchKey key = watchService.take();
            if (key != null) {
                try {
                    PathData pathData = pathDataByKey.get(key);
                    if (pathData != null) {
                        List<WatchEvent<?>> events = new ArrayList<>(key.pollEvents());
                        final List<FileChangeEvent> results = new ArrayList<>();
                        List<WatchEvent<?>> latest;
                        do {
                            // we need to wait till nothing has changed in 500ms to make sure we have picked up all the changes
                            Thread.sleep(WAIT_TIME);
                            latest = key.pollEvents();
                            events.addAll(latest);
                        } while (!latest.isEmpty());
                        final Set<Path> addedFiles = new HashSet<>();
                        final Set<Path> deletedFiles = new HashSet<>();
                        for (WatchEvent<?> event : events) {
                            Path eventPath = (Path) event.context();
                            Path targetFile = ((Path) key.watchable()).resolve(eventPath);
                            FileChangeEvent.Type type;
                            if (event.kind() == ENTRY_CREATE) {
                                type = FileChangeEvent.Type.ADDED;
                                addedFiles.add(targetFile);
                                if (Files.isDirectory(targetFile)) {
                                    try {
                                        addWatchedDirectory(pathData, targetFile);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else if (event.kind() == ENTRY_MODIFY) {
                                type = FileChangeEvent.Type.MODIFIED;
                            } else if (event.kind() == ENTRY_DELETE) {
                                type = FileChangeEvent.Type.REMOVED;
                                deletedFiles.add(targetFile);
                            } else {
                                continue;
                            }
                            results.add(new FileChangeEvent(targetFile, type));
                        }
                        key.pollEvents().clear();
                        // now we need to prune the results, to remove duplicates
                        // e.g. if the file is modified after creation we only want to
                        // show the create event
                        final List<FileChangeEvent> newEvents = new ArrayList<>();
                        Iterator<FileChangeEvent> it = results.iterator();
                        while (it.hasNext()) {
                            FileChangeEvent event = it.next();
                            boolean added = addedFiles.contains(event.getFile());
                            boolean deleted = deletedFiles.contains(event.getFile());
                            if (event.getType() == FileChangeEvent.Type.MODIFIED) {
                                if (added || deleted) {
                                    it.remove();
                                }
                            } else if (event.getType() == FileChangeEvent.Type.ADDED) {
                                if (deleted) {
                                    it.remove();
                                    // if it was both deleted and added it was modified
                                    newEvents.add(new FileChangeEvent(event.getFile(), FileChangeEvent.Type.MODIFIED));
                                }
                            } else if (event.getType() == FileChangeEvent.Type.REMOVED) {
                                if (added) {
                                    it.remove();
                                }
                            }
                        }
                        results.addAll(newEvents);
                        if (!results.isEmpty()) {
                            for (FileChangeCallback callback : pathData.callbacks) {
                                invokeCallback(callback, results);
                            }
                        }
                    }
                } finally {
                    // if the key is no longer valid remove it from the files list
                    if (!key.reset()) {
                        files.remove(key.watchable());
                    }
                }
            }
        } catch (InterruptedException e) {
        // ignore
        } catch (ClosedWatchServiceException cwse) {
            // @see https://developer.jboss.org/message/911519
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) HashSet(java.util.HashSet)

Example 5 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project divolte-collector by divolte.

the class ExternalDatabaseLookupService method processWatchEvents.

private void processWatchEvents() {
    final Thread thisThread = Thread.currentThread();
    try {
        logger.debug("Starting to wait for watch events");
        while (!thisThread.isInterrupted()) {
            // Block for the key to be signaled.
            logger.debug("Awaiting next file notification...");
            final WatchKey key = watcher.take();
            try {
                final Path parentDirectory = (Path) key.watchable();
                for (final WatchEvent<?> event : key.pollEvents()) {
                    processWatchEvent(parentDirectory, event);
                }
            } finally {
                // Ensure that no matter what happens we will receive subsequent notifications.
                key.reset();
            }
        }
        logger.debug("Stopped processing watch events due to interruption.");
    } catch (final InterruptedException e) {
        logger.debug("Interrupted while waiting for a watch event; stopping.");
        // Preserve the interrupt flag.
        thisThread.interrupt();
    } catch (final ClosedWatchServiceException e) {
        logger.debug("Stopped processing watch events; watcher has been closed.");
    }
}
Also used : Path(java.nio.file.Path) 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