Search in sources :

Example 36 with WatchService

use of java.nio.file.WatchService 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 37 with WatchService

use of java.nio.file.WatchService in project quasar by puniverse.

the class ActorLoader method monitorFilesystem.

private static void monitorFilesystem(ActorLoader instance, Path moduleDir) {
    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        moduleDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        LOG.info("Filesystem monitor: Watching module directory " + moduleDir + " for changes.");
        for (; ; ) {
            final WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                final WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    // An OVERFLOW event can occur regardless of registration if events are lost or discarded.
                    LOG.warn("Filesystem monitor: filesystem events may have been missed");
                    continue;
                }
                final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                // The filename is the context of the event.
                final Path filename = ev.context();
                // Resolve the filename against the directory.
                final Path child = moduleDir.resolve(filename);
                if (isValidFile(child, kind == ENTRY_DELETE)) {
                    try {
                        final URL jarUrl = child.toUri().toURL();
                        LOG.info("Filesystem monitor: detected module file {} {}", child, kind == ENTRY_CREATE ? "created" : kind == ENTRY_MODIFY ? "modified" : kind == ENTRY_DELETE ? "deleted" : null);
                        if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                            instance.reloadModule(jarUrl);
                        else if (kind == ENTRY_DELETE)
                            instance.unloadModule(jarUrl);
                    } catch (Exception e) {
                        LOG.error("Filesystem monitor: exception while processing " + child, e);
                    }
                } else {
                    if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                        LOG.warn("Filesystem monitor: A non-jar item " + child.getFileName() + " has been placed in the modules directory " + moduleDir);
                }
            }
            if (!key.reset())
                throw new IOException("Directory " + moduleDir + " is no longer accessible");
        }
    } catch (Exception e) {
        LOG.error("Filesystem monitor thread terminated with an exception", e);
        throw Exceptions.rethrow(e);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) WatchService(java.nio.file.WatchService) URL(java.net.URL) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) MBeanRegistrationException(javax.management.MBeanRegistrationException) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ListenerNotFoundException(javax.management.ListenerNotFoundException)

Example 38 with WatchService

use of java.nio.file.WatchService in project tomee by apache.

the class FileWatcher method watch.

public Closeable watch(final String folder) {
    final File file = new File(folder);
    if (!file.isDirectory()) {
        throw new IllegalArgumentException(folder + " is not a directory");
    }
    try {
        final AtomicBoolean again = new AtomicBoolean(true);
        final Path path = file.getAbsoluteFile().toPath();
        final WatchService watchService = path.getFileSystem().newWatchService();
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        final Thread watcherThread = new Thread(new Runnable() {

            @Override
            public void run() {
                while (again.get()) {
                    try {
                        // don't use take to not block forever
                        final WatchKey key = watchService.poll(1, TimeUnit.SECONDS);
                        if (key == null) {
                            continue;
                        }
                        for (final WatchEvent<?> event : key.pollEvents()) {
                            final WatchEvent.Kind<?> kind = event.kind();
                            if (kind != StandardWatchEventKinds.ENTRY_CREATE && kind != StandardWatchEventKinds.ENTRY_DELETE && kind != StandardWatchEventKinds.ENTRY_MODIFY) {
                                continue;
                            }
                            final Path updatedPath = Path.class.cast(event.context());
                            if (kind == StandardWatchEventKinds.ENTRY_DELETE || updatedPath.toFile().isFile()) {
                                final String path = updatedPath.toString();
                                if (path.endsWith("___jb_tmp___") || path.endsWith("___jb_old___")) {
                                    continue;
                                } else if (path.endsWith("~")) {
                                    onChange(path.replace(File.pathSeparatorChar, '/').substring(0, path.length() - 1));
                                } else {
                                    onChange(path.replace(File.pathSeparatorChar, '/'));
                                }
                            }
                        }
                        key.reset();
                    } catch (final InterruptedException e) {
                        Thread.interrupted();
                        again.set(false);
                    } catch (final ClosedWatchServiceException cwse) {
                    // ok, we finished there
                    }
                }
            }
        });
        watcherThread.setName("livereload-tomee-watcher(" + folder + ")");
        watcherThread.start();
        return new Closeable() {

            @Override
            public void close() throws IOException {
                synchronized (this) {
                    for (final Session s : sessions) {
                        removeSession(s);
                        try {
                            s.close(new CloseReason(CloseReason.CloseCodes.GOING_AWAY, "container shutdowned"));
                        } catch (final Exception e) {
                        // ok: not important there
                        }
                    }
                }
                again.compareAndSet(true, false);
                try {
                    watchService.close();
                } catch (final IOException ioe) {
                    logger.warning("Error closing the watch service for " + folder + "(" + ioe.getMessage() + ")");
                }
                try {
                    watcherThread.join(TimeUnit.MINUTES.toMillis(1));
                } catch (final InterruptedException e) {
                    Thread.interrupted();
                }
            }
        };
    } catch (final IOException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : Path(java.nio.file.Path) Closeable(java.io.Closeable) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) IOException(java.io.IOException) IOException(java.io.IOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CloseReason(javax.websocket.CloseReason) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Session(javax.websocket.Session)

Example 39 with WatchService

use of java.nio.file.WatchService in project tomee by apache.

the class ArchivingTest method logAndRotateAndPurge.

@SuppressWarnings("unchecked")
@Test
public void logAndRotateAndPurge() throws Exception {
    clean("target/ArchivingTestPurge-" + format + "/logs");
    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();
    // initial config
    today.set("2015-09-01");
    config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("purgeOlderThan", "2 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");
    final LocalFileHandler handler = new LocalFileHandler() {

        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };
    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }
    today.set("2015-09-02");
    try {
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    final File logArchive = new File("target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
    final File parentFile = logArchive.getParentFile();
    if (!parentFile.exists() && !parentFile.mkdirs()) {
        Assert.fail("Unable to create: " + parentFile);
    }
    final Path dir = parentFile.toPath();
    final WatchService watcher = FileSystems.getDefault().newWatchService();
    final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
    latch.set(new CountDownLatch(1));
    watch(key);
    // will trigger the archiving
    handler.publish(new LogRecord(Level.INFO, string10chars));
    assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS));
    final WatchEvent<?> watchEvent = lastEvent.get();
    assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind()));
    final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
    final String io = ev.context().toString();
    assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format));
    today.set("2015-09-03");
    try {
        Thread.sleep(2500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }
    // will trigger the purging
    handler.publish(new LogRecord(Level.INFO, string10chars));
    handler.close();
    withRetry(10, 2, new Runnable() {

        @Override
        public void run() {
            assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists());
        }
    });
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) WatchKey(java.nio.file.WatchKey) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) LogRecord(java.util.logging.LogRecord) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 40 with WatchService

use of java.nio.file.WatchService in project yyl_example by Relucent.

the class WatchServiceTest method main.

public static void main(String[] args) throws IOException, InterruptedException {
    String directory = "D:/temp-" + System.currentTimeMillis();
    File folder = new File(directory);
    folder.mkdirs();
    new Thread(() -> {
        for (int i = 0; i < 100; i++) {
            try {
                File file = new File(directory + "/" + i);
                file.createNewFile();
                file.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
            folder.delete();
        }
    }).start();
    Thread watch = new Thread(() -> {
        try {
            WatchService watcher = FileSystems.getDefault().newWatchService();
            FileSystems.getDefault().getPath(directory).register(watcher, StandardWatchEventKinds.ENTRY_DELETE);
            while (true) {
                WatchKey key = watcher.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    Object name = event.context();
                    System.out.println(name);
                }
                key.reset();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    watch.setDaemon(true);
    watch.start();
}
Also used : WatchKey(java.nio.file.WatchKey) IOException(java.io.IOException) File(java.io.File) WatchService(java.nio.file.WatchService)

Aggregations

WatchService (java.nio.file.WatchService)56 Path (java.nio.file.Path)40 WatchKey (java.nio.file.WatchKey)32 WatchEvent (java.nio.file.WatchEvent)23 IOException (java.io.IOException)21 Test (org.junit.Test)18 File (java.io.File)16 FileSystem (java.nio.file.FileSystem)6 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)5 Kind (java.nio.file.WatchEvent.Kind)5 FileSystems (java.nio.file.FileSystems)4 StandardWatchEventKinds (java.nio.file.StandardWatchEventKinds)4 SensitivityWatchEventModifier (com.sun.nio.file.SensitivityWatchEventModifier)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 TimeUnit (java.util.concurrent.TimeUnit)3 BufferedReader (java.io.BufferedReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2