Search in sources :

Example 91 with WatchKey

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

the class WatchQueueReader method stopWatchService.

public synchronized void stopWatchService(AbstractWatchService service) {
    if (watchService != null) {
        List<WatchKey> keys = new LinkedList<>();
        for (WatchKey key : keyToService.keySet()) {
            if (keyToService.get(key) == service) {
                keys.add(key);
            }
        }
        if (keys.size() == keyToService.size()) {
            try {
                watchService.close();
            } catch (IOException e) {
                logger.warn("Cannot deactivate folder watcher", e);
            }
            watchService = null;
            keyToService.clear();
            registeredKeys.clear();
            hashes.clear();
            futures.values().forEach(keyFutures -> keyFutures.values().forEach(future -> future.cancel(true)));
            futures.clear();
        } else {
            for (WatchKey key : keys) {
                key.cancel();
                keyToService.remove(key);
                registeredKeys.remove(key);
                hashes.remove(service);
                Map<Path, @Nullable ScheduledFuture<?>> keyFutures = futures.remove(key);
                if (keyFutures != null) {
                    keyFutures.values().forEach(future -> future.cancel(true));
                }
            }
        }
    }
}
Also used : NoSuchFileException(java.nio.file.NoSuchFileException) Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) MessageDigest(java.security.MessageDigest) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) WatchKey(java.nio.file.WatchKey) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) Kind(java.nio.file.WatchEvent.Kind) Nullable(org.eclipse.jdt.annotation.Nullable) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LinkedList(java.util.LinkedList) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) ThreadPoolManager(org.eclipse.smarthome.core.common.ThreadPoolManager) Logger(org.slf4j.Logger) Files(java.nio.file.Files) WatchEvent(java.nio.file.WatchEvent) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) FileVisitResult(java.nio.file.FileVisitResult) WatchService(java.nio.file.WatchService) List(java.util.List) FileVisitOption(java.nio.file.FileVisitOption) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AccessDeniedException(java.nio.file.AccessDeniedException) FileSystems(java.nio.file.FileSystems) InputStream(java.io.InputStream) Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) IOException(java.io.IOException) LinkedList(java.util.LinkedList) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Example 92 with WatchKey

use of java.nio.file.WatchKey in project hazelcast by hazelcast.

the class StreamFilesP method drainWatcherEvents.

/**
 * @return false, if the watcher should be closed
 */
private boolean drainWatcherEvents() {
    final ILogger logger = getLogger();
    // poll with blocking only when there is no other work to do
    final WatchKey key;
    try {
        key = (currentFile == null && eventQueue.isEmpty()) ? watcher.poll(1, SECONDS) : watcher.poll();
    } catch (InterruptedException e) {
        return false;
    }
    if (key == null) {
        if (!Files.exists(watchedDirectory)) {
            logger.info("Directory " + watchedDirectory + " does not exist, stopped watching");
            return false;
        }
        return true;
    }
    for (WatchEvent<?> event : key.pollEvents()) {
        final WatchEvent.Kind<?> kind = event.kind();
        final Path fileName = ((WatchEvent<Path>) event).context();
        final Path filePath = watchedDirectory.resolve(fileName);
        if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
            if (glob.matches(fileName) && belongsToThisProcessor(fileName) && !Files.isDirectory(filePath)) {
                logFine(logger, "Will open file to read new content: %s", filePath);
                eventQueue.add(filePath);
            }
        } else if (kind == ENTRY_DELETE) {
            logFinest(logger, "File was deleted: %s", filePath);
            fileOffsets.remove(filePath);
        } else if (kind == OVERFLOW) {
            logger.warning("Detected OVERFLOW in " + watchedDirectory);
        } else {
            throw new JetException("Unknown kind of WatchEvent: " + kind);
        }
    }
    if (!key.reset()) {
        logger.info("Watch key is invalid. Stopping watcher.");
        return false;
    }
    return true;
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ILogger(com.hazelcast.logging.ILogger) WatchEvent(java.nio.file.WatchEvent) JetException(com.hazelcast.jet.JetException)

Example 93 with WatchKey

use of java.nio.file.WatchKey in project pravega by pravega.

the class FileModificationEventWatcher method run.

@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
    WatchKey watchKey = null;
    WatchService watchService = null;
    try {
        watchService = FileSystems.getDefault().newWatchService();
        log.debug("Done creating watch service for watching file at path: {}", this.watchedFilePath);
        String fileName = getWatchedFileName();
        Path directoryPath = getWatchedDirectory();
        log.debug("Directory being watched is {}", directoryPath);
        assert directoryPath != null;
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
        log.debug("Registered the watch for the file: {}", this.watchedFilePath);
        isWatchRegistered = true;
        while (!Thread.currentThread().isInterrupted()) {
            try {
                watchKey = retrieveWatchKeyFrom(watchService);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logException(e);
            // Allow thread to exit.
            }
            if (watchKey != null) {
                Optional<WatchEvent<?>> modificationDetectionEvent = watchKey.pollEvents().stream().filter(event -> event.context().toString().contains(fileName)).findAny();
                if (modificationDetectionEvent.isPresent()) {
                    log.info("Detected that the file [{}] has modified", this.watchedFilePath);
                    callback.accept(modificationDetectionEvent.get());
                }
                boolean isKeyValid = watchKey.reset();
                log.debug("Done resetting watch key.");
                if (!isKeyValid) {
                    log.info("No longer watching file [{}]", this.watchedFilePath);
                    break;
                }
            }
            if (!loopContinuously) {
                break;
            }
        }
    } catch (IOException e) {
        logException(e);
        throw new RuntimeException(e);
    } finally {
        if (watchKey != null) {
            watchKey.cancel();
        }
        if (watchService != null) {
            try {
                watchService.close();
            } catch (IOException e) {
                log.warn("Error closing watch service", e);
            }
        }
    }
    log.info("Thread [{}], watching for modifications in file [{}] exiting,", getName(), this.watchedFilePath);
}
Also used : Path(java.nio.file.Path) NonNull(lombok.NonNull) WatchEvent(java.nio.file.WatchEvent) Exceptions(io.pravega.common.Exceptions) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) WatchKey(java.nio.file.WatchKey) Consumer(java.util.function.Consumer) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) WatchService(java.nio.file.WatchService) Slf4j(lombok.extern.slf4j.Slf4j) InvalidPathException(java.nio.file.InvalidPathException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Path(java.nio.file.Path) FileSystems(java.nio.file.FileSystems) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) WatchService(java.nio.file.WatchService)

Example 94 with WatchKey

use of java.nio.file.WatchKey in project tutorials by eugenp.

the class DirectoryWatcherExample method main.

public static void main(String[] args) throws IOException, InterruptedException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Path path = Paths.get(System.getProperty("user.home"));
    path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
    WatchKey key;
    while ((key = watchService.take()) != null) {
        for (WatchEvent<?> event : key.pollEvents()) {
            System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
        }
        key.reset();
    }
    watchService.close();
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchService(java.nio.file.WatchService)

Example 95 with WatchKey

use of java.nio.file.WatchKey in project chatty by chatty.

the class FileWatcher method run.

@Override
public void run() {
    for (; ; ) {
        WatchKey key;
        /**
         * Wait for a modification to occur.
         */
        try {
            key = watcher.take();
        } catch (InterruptedException ex) {
            return;
        }
        /**
         * Wait a bit for events to accumulate. This prevents several
         * consecutive modifications (e.g. several writes or change of file
         * modification date) from all triggering the listener.
         */
        try {
            Thread.sleep(4000);
        } catch (InterruptedException ex) {
            return;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();
            Path changedFile = directory.resolve(fileName);
            if (changedFile.equals(file)) {
                listener.fileChanged();
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent)

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