Search in sources :

Example 6 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project streamline by hortonworks.

the class FileWatcher method processEvents.

/**
 * Blocking method to check and dispatch file events.
 * @return Returns false if file watcher will not receive any more events to indicate caller to break out of loop
 */
public boolean processEvents() {
    if (watchKeyPathMap.isEmpty()) {
        return false;
    }
    // wait for key to be signalled
    WatchKey key;
    try {
        key = watchService.take();
    } catch (ClosedWatchServiceException | InterruptedException ex) {
        LOG.info("Watch service interrupted or closed while waiting to get next watch key. Exiting!", ex);
        return false;
    }
    Path dir = watchKeyPathMap.get(key);
    if (dir == null) {
        LOG.info("Unrecognized watch key: " + key + ". Skipping the key without reseting it.");
        return true;
    }
    for (WatchEvent<?> event : key.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        if (kind == StandardWatchEventKinds.OVERFLOW) {
            LOG.warn("Overflow event received for key: " + key + ". This means events have been missed or discarded. Please verify.");
            return true;
        }
        // Context for directory entry event is the file name of entry
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path name = ev.context();
        Path child = dir.resolve(name);
        LOG.info("{}: {}", event.kind().name(), child);
        try {
            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                watchKeyFileEventHandlerMap.get(key).created(child);
            } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                watchKeyFileEventHandlerMap.get(key).modified(child);
            } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                watchKeyFileEventHandlerMap.get(key).deleted(child);
            }
        } catch (RuntimeException ex) {
            LOG.warn("Exception thrown by handler {} while processing event {}", watchKeyFileEventHandlerMap.get(key), event.kind().name(), ex);
        }
    }
    // reset key and remove from set if directory no longer accessible
    boolean valid = key.reset();
    if (!valid) {
        LOG.info("Key " + key + " not being watched any more as it could not be reset.");
        watchKeyPathMap.remove(key);
        watchKeyFileEventHandlerMap.remove(key);
    }
    return true;
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent)

Example 7 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project javaee7-samples by javaee-samples.

the class WatchingThread method run.

public void run() {
    while (true) {
        try {
            WatchKey watchKey = watchService.take();
            if (watchKey != null) {
                dispatchEvents(watchKey.pollEvents(), resourceAdapter.getListener(watchKey));
                watchKey.reset();
            }
        } catch (ClosedWatchServiceException e) {
            return;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Also used : WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 8 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project moco by dreamhead.

the class WatcherService method loop.

private void loop() {
    try {
        WatchKey key = service.take();
        Collection<Path> paths = keys.get(key);
        List<WatchEvent<?>> events = key.pollEvents().stream().filter(e -> e.kind().equals(ENTRY_MODIFY)).collect(Collectors.toList());
        for (WatchEvent<?> event : events) {
            final Path context = (Path) event.context();
            List<Path> contextPaths = paths.stream().filter(p -> p.endsWith(context)).collect(Collectors.toList());
            for (Path path : contextPaths) {
                for (Function<File, Void> listener : this.listeners.get(path)) {
                    listener.apply(path.toFile());
                }
                break;
            }
        }
        key.reset();
    } catch (ClosedWatchServiceException ignored) {
    } catch (InterruptedException e) {
        logger.error("Error happens", e);
    }
}
Also used : Path(java.nio.file.Path) LoggerFactory(org.slf4j.LoggerFactory) HIGH(com.sun.nio.file.SensitivityWatchEventModifier.HIGH) MocoException(com.github.dreamhead.moco.MocoException) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) WatchKey(java.nio.file.WatchKey) Future(java.util.concurrent.Future) MocoExecutors(com.github.dreamhead.moco.util.MocoExecutors) HashMultimap(com.google.common.collect.HashMultimap) Map(java.util.Map) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) Files(com.github.dreamhead.moco.util.Files) ENTRY_MODIFY(java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) Logger(org.slf4j.Logger) Idles.idle(com.github.dreamhead.moco.util.Idles.idle) Maps.newHashMap(com.google.common.collect.Maps.newHashMap) WatchEvent(java.nio.file.WatchEvent) Collection(java.util.Collection) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) WatchService(java.nio.file.WatchService) List(java.util.List) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) FileSystems(java.nio.file.FileSystems) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Example 9 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project jimfs by google.

the class JimfsFileSystemCloseTest method testPathMethodsThrow.

@Test
public void testPathMethodsThrow() throws IOException {
    Path p = fs.getPath("/foo");
    Files.createDirectory(p);
    WatchService ws = fs.newWatchService();
    fs.close();
    try {
        p.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        fail();
    } catch (ClosedWatchServiceException expected) {
    }
    try {
        p = p.toRealPath();
        fail();
    } catch (ClosedFileSystemException expected) {
    }
// While technically (according to the FileSystem.close() spec) all methods on Path should
// probably throw, we only throw for methods that access the file system itself in some way...
// path manipulation methods seem totally harmless to keep working, and I don't see any need to
// add the overhead of checking that the file system is open for each of those method calls.
}
Also used : Path(java.nio.file.Path) ClosedFileSystemException(java.nio.file.ClosedFileSystemException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 10 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project jimfs by google.

the class JimfsFileSystemCloseTest method testOpenWatchServicesClosed.

@Test
public void testOpenWatchServicesClosed() throws IOException {
    WatchService ws1 = fs.newWatchService();
    WatchService ws2 = fs.newWatchService();
    assertNull(ws1.poll());
    assertNull(ws2.poll());
    fs.close();
    try {
        ws1.poll();
        fail();
    } catch (ClosedWatchServiceException expected) {
    }
    try {
        ws2.poll();
        fail();
    } catch (ClosedWatchServiceException expected) {
    }
}
Also used : ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

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