Search in sources :

Example 11 with WatchService

use of java.nio.file.WatchService in project opennms by OpenNMS.

the class DirectoryWatcher method run.

/* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
@Override
@SuppressWarnings("unchecked")
public void run() {
    LOG.info("starting run loop");
    try (WatchService watcher = m_path.getFileSystem().newWatchService()) {
        LOG.debug("registering create watcher on {}", m_path.toAbsolutePath().toString());
        m_path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
        LOG.debug("watcher registration complete for {}", m_path.toAbsolutePath().toString());
        synchronized (this) {
            this.notifyAll();
        }
        while (true) {
            if (m_thread.isInterrupted()) {
                break;
            }
            WatchKey key = null;
            try {
                LOG.debug("waiting for create event");
                key = watcher.take();
                LOG.debug("got an event, process it");
            } catch (InterruptedException ie) {
                LOG.info("interruped, must be time to shut down...");
                break;
            }
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                WatchEvent.Kind<?> kind = watchEvent.kind();
                Path pathChanged = ((WatchEvent<Path>) watchEvent).context();
                final String fileName = pathChanged.toString();
                final File file = new File(m_directory, fileName);
                if (file.isDirectory()) {
                    // Ignoring changes on directories.
                    LOG.debug("{} is a directory, ignoring.", file);
                    continue;
                }
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    LOG.debug("overflow receiving, ignoring changes.");
                    continue;
                } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                    LOG.info("file '{}' created. Ignoring...", fileName);
                } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                    LOG.info("file '{}' modified. Removing entry from cache.", fileName);
                    m_contents.remove(fileName);
                } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                    LOG.info("file '{}' deleted. Removing entry from cache.", fileName);
                    m_contents.remove(fileName);
                }
                // IMPORTANT: The key must be reset after processed
                if (!key.reset()) {
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage(), ioe);
    }
    LOG.info("existing run loop");
}
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) File(java.io.File)

Example 12 with WatchService

use of java.nio.file.WatchService in project streamsx.topology by IBMStreams.

the class DirectoryWatcher method process.

@SuppressWarnings("unchecked")
@Override
protected void process() throws Exception {
    Path dir = dirFile.toPath();
    WatchService watcher = FileSystems.getDefault().newWatchService();
    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
    sortAndSubmit(Arrays.asList(dirFile.listFiles(this)));
    for (; !Thread.interrupted(); ) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            // shutdown has been requested
            return;
        }
        List<File> newFiles = new ArrayList<>();
        boolean needFullScan = false;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
            if (ENTRY_CREATE == watchEvent.kind()) {
                Path newPath = ((WatchEvent<Path>) watchEvent).context();
                File newFile = toFile(newPath);
                if (accept(newFile))
                    newFiles.add(newFile);
            } else if (ENTRY_DELETE == watchEvent.kind()) {
                Path deletedPath = ((WatchEvent<Path>) watchEvent).context();
                File deletedFile = toFile(deletedPath);
                seenFiles.remove(deletedFile.getName());
            } else if (OVERFLOW == watchEvent.kind()) {
                needFullScan = true;
            }
        }
        key.reset();
        if (needFullScan) {
            Collections.addAll(newFiles, dirFile.listFiles(this));
        }
        sortAndSubmit(newFiles);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ArrayList(java.util.ArrayList) WatchEvent(java.nio.file.WatchEvent) WatchService(java.nio.file.WatchService) File(java.io.File)

Example 13 with WatchService

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

the class AutoEncryptionSupport method run.

@Override
public void run() {
    WatchService watchService = null;
    try {
        watchService = FileSystems.getDefault().newWatchService();
        Path dir = Paths.get(System.getProperty("karaf.etc"));
        dir.register(watchService, ENTRY_MODIFY);
        Path file = dir.resolve("users.properties");
        encryptedPassword(new Properties(file.toFile()));
        while (running) {
            try {
                WatchKey key = watchService.poll(1, TimeUnit.SECONDS);
                if (key == null) {
                    continue;
                }
                for (WatchEvent<?> event : key.pollEvents()) {
                    @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    // Context for directory entry event is the file name of entry
                    Path name = dir.resolve(ev.context());
                    if (file.equals(name)) {
                        encryptedPassword(new Properties(file.toFile()));
                    }
                }
                key.reset();
            } catch (IOException e) {
                LOGGER.warn(e.getMessage(), e);
            } catch (InterruptedException e) {
            // Ignore as this happens on shutdown
            }
        }
    } catch (IOException e) {
        LOGGER.warn(e.getMessage(), e);
    } finally {
        StreamUtils.close(watchService);
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) IOException(java.io.IOException) Properties(org.apache.felix.utils.properties.Properties) WatchService(java.nio.file.WatchService)

Example 14 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 15 with WatchService

use of java.nio.file.WatchService in project Gargoyle by callakrsos.

the class FileUtilTest method watchTest.

@Test
public void watchTest() throws IOException {
    File file = new File("c:\\someDir");
    file.mkdirs();
    WatchService newWatchService = FileSystems.getDefault().newWatchService();
    WatchKey register = file.toPath().register(newWatchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    System.out.println("Watch Service Registered ..");
    while (true) {
        try {
            System.out.println("start");
            WatchKey key = newWatchService.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path fileName = ev.context();
                System.out.println(kind.name() + ": " + fileName);
                if (key == ENTRY_MODIFY && fileName.toString().equals("DirectoryWatchDemo.java")) {
                    System.out.println("My source file has changed!!!");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        } catch (InterruptedException e) {
            break;
        }
    }
    System.out.println("end ");
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) WatchEvent(java.nio.file.WatchEvent) File(java.io.File) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Aggregations

WatchService (java.nio.file.WatchService)15 Path (java.nio.file.Path)9 WatchEvent (java.nio.file.WatchEvent)7 Test (org.junit.Test)7 IOException (java.io.IOException)6 WatchKey (java.nio.file.WatchKey)6 File (java.io.File)5 ClosedWatchServiceException (java.nio.file.ClosedWatchServiceException)3 FileSystem (java.nio.file.FileSystem)2 Closeable (java.io.Closeable)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 ClosedFileSystemException (java.nio.file.ClosedFileSystemException)1 ArrayList (java.util.ArrayList)1 ExecutorService (java.util.concurrent.ExecutorService)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 InstanceAlreadyExistsException (javax.management.InstanceAlreadyExistsException)1 ListenerNotFoundException (javax.management.ListenerNotFoundException)1 MBeanRegistrationException (javax.management.MBeanRegistrationException)1 MalformedObjectNameException (javax.management.MalformedObjectNameException)1