Search in sources :

Example 11 with ClosedWatchServiceException

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

the class MacOSXPathTest method test_register$WatchService$WatchEvent_Kind_Exception.

@Test
public void test_register$WatchService$WatchEvent_Kind_Exception() throws IOException {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Path directory = Paths.get(filesSetup.getTestDir(), "directory1");
    Files.createFile(directory);
    // When file is not a directory.
    try {
        directory.register(watchService, ENTRY_CREATE);
        fail();
    } catch (NotDirectoryException expected) {
    }
    // When the events are not supported.
    Files.deleteIfExists(directory);
    Files.createDirectories(directory);
    WatchEvent.Kind<?>[] events = { new NonStandardEvent<>() };
    try {
        directory.register(watchService, events);
        fail();
    } catch (UnsupportedOperationException expected) {
    }
    // When the watch service is closed.
    watchService.close();
    try {
        directory.register(watchService, ENTRY_CREATE);
        fail();
    } catch (ClosedWatchServiceException expected) {
    }
}
Also used : Path(java.nio.file.Path) NotDirectoryException(java.nio.file.NotDirectoryException) Kind(java.nio.file.WatchEvent.Kind) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchService(java.nio.file.WatchService) Test(org.junit.Test)

Example 12 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project SSM by Intel-bigdata.

the class InterpreterOutputChangeWatcher method run.

public void run() {
    while (!stop) {
        WatchKey key = null;
        try {
            key = watcher.poll(1, TimeUnit.SECONDS);
        } catch (InterruptedException | ClosedWatchServiceException e) {
            break;
        }
        if (key == null) {
            continue;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();
            // search for filename
            synchronized (watchKeys) {
                for (File f : watchFiles) {
                    if (f.getName().compareTo(filename.toString()) == 0) {
                        File changedFile;
                        if (filename.isAbsolute()) {
                            changedFile = new File(filename.toString());
                        } else {
                            changedFile = new File(watchKeys.get(key), filename.toString());
                        }
                        logger.info("File change detected " + changedFile.getAbsolutePath());
                        if (listener != null) {
                            listener.fileChanged(changedFile);
                        }
                    }
                }
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) WatchEvent(java.nio.file.WatchEvent) File(java.io.File)

Example 13 with ClosedWatchServiceException

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

the class JBake method main.

// if you want to switch off PDF generation use as arguments: src/main/jbake target/site-tmp true false
public static void main(final String[] args) throws Exception {
    // try to have parallelStream better than default
    System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "64");
    final File source = args == null || args.length < 1 ? new File("src/main/jbake") : new File(args[0]);
    final File pdfSource = new File(source, "content");
    final File destination = args == null || args.length < 2 ? new File("target/site-tmp") : new File(args[1]);
    // by default we dev
    final boolean startHttp = args == null || args.length < 2 || Boolean.parseBoolean(args[2]);
    // by default...too slow sorry
    final boolean skipPdf = args != null && args.length > 3 && !Boolean.parseBoolean(args[3]);
    // grabs central
    final boolean updateDownloads = args != null && args.length > 4 && Boolean.parseBoolean(args[4]);
    // generation of dynamic content
    new Configuration().run();
    new CliConfiguration().run();
    new ArquillianConfiguration().run();
    new MavenConfiguration().run();
    new OAuth2Configuration().run();
    new LetsEncryptConfiguration().run();
    new GradleConfiguration().run();
    new ProxyConfiguration().run();
    if (updateDownloads) {
        final ByteArrayOutputStream tableContent = new ByteArrayOutputStream();
        try (final PrintStream stream = new PrintStream(tableContent)) {
            Downloads.doMain(stream);
        }
        try (final Writer writer = new FileWriter(new File(source, "content/download.adoc"))) {
            writer.write("= Downloads\n" + ":jbake-generated: true\n" + ":jbake-date: 2017-07-24\n" + ":jbake-type: page\n" + ":jbake-status: published\n" + ":jbake-meecrowavepdf:\n" + ":jbake-meecrowavecolor: body-blue\n" + ":icons: font\n" + "\n" + "License under Apache License v2 (ALv2).\n" + "\n" + "[.table.table-bordered,options=\"header\"]\n" + "|===\n" + "|Name|Version|Date|Size|Type|Links\n");
            writer.write(new String(tableContent.toByteArray(), StandardCharsets.UTF_8));
            writer.write("\n|===\n");
        }
    }
    final Runnable build = () -> {
        System.out.println("Building Meecrowave website in " + destination);
        final Orient orient = Orient.instance();
        try {
            final Oven oven = new Oven(new JBakeConfigurationFactory().createDefaultJbakeConfiguration(source, destination, new CompositeConfiguration() {

                {
                    final CompositeConfiguration config = new CompositeConfiguration();
                    config.addConfiguration(new MapConfiguration(new HashMap<String, Object>() {

                        {
                            put("asciidoctor.attributes", new ArrayList<String>() {

                                {
                                    add("source-highlighter=highlightjs");
                                    add("highlightjs-theme=idea");
                                    add("context_rootpath=/meecrowave");
                                    add("icons=font");
                                }
                            });
                        }
                    }));
                    config.addConfiguration(DefaultJBakeConfiguration.class.cast(new ConfigUtil().loadConfig(source)).getCompositeConfiguration());
                    addConfiguration(config);
                }
            }, true));
            System.out.println("  > baking");
            oven.bake();
            if (!skipPdf) {
                System.out.println("  > pdfifying");
                PDFify.generatePdf(pdfSource, destination);
            }
            System.out.println("  > done :)");
        } catch (final Exception e) {
            e.printStackTrace();
        } finally {
            orient.shutdown();
        }
    };
    build.run();
    if (startHttp) {
        final Path watched = source.toPath();
        final WatchService watchService = watched.getFileSystem().newWatchService();
        watched.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        final AtomicBoolean run = new AtomicBoolean(true);
        final AtomicLong render = new AtomicLong(-1);
        final Thread renderingThread = new Thread() {

            {
                setName("jbake-renderer");
            }

            @Override
            public void run() {
                long last = System.currentTimeMillis();
                while (run.get()) {
                    if (render.get() > last) {
                        last = System.currentTimeMillis();
                        try {
                            build.run();
                        } catch (final Throwable oops) {
                            oops.printStackTrace();
                        }
                    }
                    try {
                        sleep(TimeUnit.SECONDS.toMillis(1));
                    } catch (final InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
                System.out.println("Exiting renderer");
            }
        };
        final Thread watcherThread = new Thread() {

            {
                setName("jbake-file-watcher");
            }

            @Override
            public void run() {
                while (run.get()) {
                    try {
                        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 != ENTRY_CREATE && kind != ENTRY_DELETE && kind != ENTRY_MODIFY) {
                                // unlikely but better to protect ourself
                                continue;
                            }
                            final Path updatedPath = Path.class.cast(event.context());
                            if (kind == ENTRY_DELETE || updatedPath.toFile().isFile()) {
                                final String path = updatedPath.toString();
                                if (!path.contains("___jb") && !path.endsWith("~")) {
                                    render.set(System.currentTimeMillis());
                                }
                            }
                        }
                        key.reset();
                    } catch (final InterruptedException e) {
                        Thread.currentThread().interrupt();
                        run.compareAndSet(true, false);
                    } catch (final ClosedWatchServiceException cwse) {
                        if (!run.get()) {
                            throw new IllegalStateException(cwse);
                        }
                    }
                }
                System.out.println("Exiting file watcher");
            }
        };
        renderingThread.start();
        watcherThread.start();
        final Runnable onQuit = () -> {
            run.compareAndSet(true, false);
            Stream.of(watcherThread, renderingThread).forEach(thread -> {
                try {
                    thread.join();
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            try {
                watchService.close();
            } catch (final IOException ioe) {
            // not important
            }
        };
        try (final Meecrowave container = new Meecrowave(new Meecrowave.Builder() {

            {
                setWebResourceCached(false);
                property("proxy-skip", "true");
            }
        }) {

            {
                start();
                getTomcat().getServer().setParentClassLoader(Thread.currentThread().getContextClassLoader());
                deployWebapp("/meecrowave", destination);
            }
        }) {
            System.out.println("Started on http://localhost:" + container.getConfiguration().getHttpPort() + "/meecrowave");
            final Scanner console = new Scanner(System.in);
            String cmd;
            while (((cmd = console.nextLine())) != null) {
                if ("quit".equals(cmd)) {
                    break;
                } else if ("r".equals(cmd) || "rebuild".equals(cmd) || "build".equals(cmd) || "b".equals(cmd)) {
                    render.set(System.currentTimeMillis());
                } else {
                    System.err.println("Ignoring " + cmd + ", please use 'build' or 'quit'");
                }
            }
        }
        onQuit.run();
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) DefaultJBakeConfiguration(org.jbake.app.configuration.DefaultJBakeConfiguration) OAuth2Configuration(org.apache.meecrowave.doc.generator.OAuth2Configuration) ProxyServletSetup(org.apache.meecrowave.proxy.servlet.meecrowave.ProxyServletSetup) Scanner(java.util.Scanner) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Orient(com.orientechnologies.orient.core.Orient) HashMap(java.util.HashMap) ConfigUtil(org.jbake.app.configuration.ConfigUtil) CompositeConfiguration(org.apache.commons.configuration.CompositeConfiguration) ProxyConfiguration(org.apache.meecrowave.doc.generator.ProxyConfiguration) ENTRY_CREATE(java.nio.file.StandardWatchEventKinds.ENTRY_CREATE) ArrayList(java.util.ArrayList) WatchKey(java.nio.file.WatchKey) MapConfiguration(org.apache.commons.configuration.MapConfiguration) GradleConfiguration(org.apache.meecrowave.doc.generator.GradleConfiguration) JBakeConfigurationFactory(org.jbake.app.configuration.JBakeConfigurationFactory) Path(java.nio.file.Path) PrintStream(java.io.PrintStream) ENTRY_MODIFY(java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY) WatchEvent(java.nio.file.WatchEvent) FileWriter(java.io.FileWriter) LetsEncryptConfiguration(org.apache.meecrowave.doc.generator.LetsEncryptConfiguration) IOException(java.io.IOException) Downloads(org.apache.meecrowave.doc.generator.Downloads) CliConfiguration(org.apache.meecrowave.doc.generator.CliConfiguration) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) TimeUnit(java.util.concurrent.TimeUnit) MavenConfiguration(org.apache.meecrowave.doc.generator.MavenConfiguration) AtomicLong(java.util.concurrent.atomic.AtomicLong) WatchService(java.nio.file.WatchService) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) Stream(java.util.stream.Stream) Oven(org.jbake.app.Oven) ENTRY_DELETE(java.nio.file.StandardWatchEventKinds.ENTRY_DELETE) Writer(java.io.Writer) Meecrowave(org.apache.meecrowave.Meecrowave) ArquillianConfiguration(org.apache.meecrowave.doc.generator.ArquillianConfiguration) Configuration(org.apache.meecrowave.doc.generator.Configuration) Scanner(java.util.Scanner) DefaultJBakeConfiguration(org.jbake.app.configuration.DefaultJBakeConfiguration) OAuth2Configuration(org.apache.meecrowave.doc.generator.OAuth2Configuration) CompositeConfiguration(org.apache.commons.configuration.CompositeConfiguration) ProxyConfiguration(org.apache.meecrowave.doc.generator.ProxyConfiguration) MapConfiguration(org.apache.commons.configuration.MapConfiguration) GradleConfiguration(org.apache.meecrowave.doc.generator.GradleConfiguration) LetsEncryptConfiguration(org.apache.meecrowave.doc.generator.LetsEncryptConfiguration) CliConfiguration(org.apache.meecrowave.doc.generator.CliConfiguration) MavenConfiguration(org.apache.meecrowave.doc.generator.MavenConfiguration) ArquillianConfiguration(org.apache.meecrowave.doc.generator.ArquillianConfiguration) Configuration(org.apache.meecrowave.doc.generator.Configuration) FileWriter(java.io.FileWriter) MapConfiguration(org.apache.commons.configuration.MapConfiguration) ArrayList(java.util.ArrayList) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) DefaultJBakeConfiguration(org.jbake.app.configuration.DefaultJBakeConfiguration) Oven(org.jbake.app.Oven) ArquillianConfiguration(org.apache.meecrowave.doc.generator.ArquillianConfiguration) OAuth2Configuration(org.apache.meecrowave.doc.generator.OAuth2Configuration) WatchEvent(java.nio.file.WatchEvent) CliConfiguration(org.apache.meecrowave.doc.generator.CliConfiguration) Meecrowave(org.apache.meecrowave.Meecrowave) Path(java.nio.file.Path) MavenConfiguration(org.apache.meecrowave.doc.generator.MavenConfiguration) PrintStream(java.io.PrintStream) Orient(com.orientechnologies.orient.core.Orient) JBakeConfigurationFactory(org.jbake.app.configuration.JBakeConfigurationFactory) ConfigUtil(org.jbake.app.configuration.ConfigUtil) CompositeConfiguration(org.apache.commons.configuration.CompositeConfiguration) WatchKey(java.nio.file.WatchKey) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IOException(java.io.IOException) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) ProxyConfiguration(org.apache.meecrowave.doc.generator.ProxyConfiguration) LetsEncryptConfiguration(org.apache.meecrowave.doc.generator.LetsEncryptConfiguration) GradleConfiguration(org.apache.meecrowave.doc.generator.GradleConfiguration) File(java.io.File) WatchService(java.nio.file.WatchService) FileWriter(java.io.FileWriter) Writer(java.io.Writer)

Example 14 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project che by eclipse.

the class FileWatcherService method run.

private void run() {
    suspended.compareAndSet(true, false);
    running.compareAndSet(false, true);
    while (running.get()) {
        try {
            WatchKey watchKey = service.take();
            Path dir = keys.get(watchKey);
            if (suspended.get()) {
                resetAndRemove(watchKey, dir);
                LOG.debug("File watchers are running in suspended mode - skipping.");
                continue;
            }
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    LOG.warn("Detected file system events overflowing");
                    continue;
                }
                WatchEvent<Path> ev = cast(event);
                Path item = ev.context();
                Path path = dir.resolve(item).toAbsolutePath();
                if (isExcluded(excludes, path)) {
                    LOG.debug("Path is within exclude list, skipping...");
                    continue;
                }
                handler.handle(path, kind);
            }
            resetAndRemove(watchKey, dir);
        } catch (InterruptedException e) {
            running.compareAndSet(true, false);
            LOG.debug("Interruption error when running file watcher, most likely caused by stopping it", e);
        } catch (ClosedWatchServiceException e) {
            running.compareAndSet(true, false);
            LOG.debug("Closing watch service while some of keys may be processing", e);
        }
    }
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException)

Example 15 with ClosedWatchServiceException

use of java.nio.file.ClosedWatchServiceException in project jetty.project by eclipse.

the class PathWatcher method run.

/** 
     * Forever loop.
     * 
     * Wait for the WatchService to report some filesystem events for the
     * watched paths.
     * 
     * When an event for a path first occurs, it is subjected to a quiet time.
     * Subsequent events that arrive for the same path during this quiet time are
     * accumulated and the timer reset. Only when the quiet time has expired are
     * the accumulated events sent. MODIFY events are handled slightly differently -
     * multiple MODIFY events arriving within a quiet time are coalesced into a
     * single MODIFY event. Both the accumulation of events and coalescing of MODIFY
     * events reduce the number and frequency of event reporting for "noisy" files (ie
     * those that are undergoing rapid change).
     * 
     * @see java.lang.Runnable#run()
     */
@Override
public void run() {
    List<PathWatchEvent> notifiableEvents = new ArrayList<PathWatchEvent>();
    // Start the java.nio watching
    if (LOG.isDebugEnabled()) {
        LOG.debug("Starting java.nio file watching with {}", watchService);
    }
    while (watchService != null && thread == Thread.currentThread()) {
        WatchKey key = null;
        try {
            //If no pending events, wait forever for new events
            if (pendingEvents.isEmpty()) {
                if (NOISY_LOG.isDebugEnabled())
                    NOISY_LOG.debug("Waiting for take()");
                key = watchService.take();
            } else {
                //only wait as long as the quiet time for any new events
                if (NOISY_LOG.isDebugEnabled())
                    NOISY_LOG.debug("Waiting for poll({}, {})", updateQuietTimeDuration, updateQuietTimeUnit);
                key = watchService.poll(updateQuietTimeDuration, updateQuietTimeUnit);
                //If no new events its safe to process the pendings
                if (key == null) {
                    long now = System.currentTimeMillis();
                    // no new event encountered.
                    for (Path path : new HashSet<Path>(pendingEvents.keySet())) {
                        PathPendingEvents pending = pendingEvents.get(path);
                        if (pending.isQuiet(now, updateQuietTimeDuration, updateQuietTimeUnit)) {
                            //so generate the events that were pent up
                            for (PathWatchEvent p : pending.getEvents()) {
                                notifiableEvents.add(p);
                            }
                            // remove from pending list
                            pendingEvents.remove(path);
                        }
                    }
                }
            }
        } catch (ClosedWatchServiceException e) {
            // Normal shutdown of watcher
            return;
        } catch (InterruptedException e) {
            if (isRunning()) {
                LOG.warn(e);
            } else {
                LOG.ignore(e);
            }
            return;
        }
        //If there was some new events to process
        if (key != null) {
            Config config = keys.get(key);
            if (config == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("WatchKey not recognized: {}", key);
                }
                continue;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                @SuppressWarnings("unchecked") WatchEvent.Kind<Path> kind = (Kind<Path>) event.kind();
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = config.dir.resolve(name);
                if (kind == ENTRY_CREATE) {
                    // recursively
                    if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
                        try {
                            prepareConfig(config.asSubConfig(child));
                        } catch (IOException e) {
                            LOG.warn(e);
                        }
                    } else if (config.matches(child)) {
                        addToPendingList(child, new PathWatchEvent(child, ev));
                    }
                } else if (config.matches(child)) {
                    addToPendingList(child, new PathWatchEvent(child, ev));
                }
            }
        }
        //Send any notifications generated this pass
        notifyOnPathWatchEvents(notifiableEvents);
        notifiableEvents.clear();
        if (key != null && !key.reset()) {
            keys.remove(key);
            if (keys.isEmpty()) {
                // all done, no longer monitoring anything
                return;
            }
        }
    }
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) WatchKey(java.nio.file.WatchKey) ClosedWatchServiceException(java.nio.file.ClosedWatchServiceException) IOException(java.io.IOException) Kind(java.nio.file.WatchEvent.Kind) WatchEvent(java.nio.file.WatchEvent) HashSet(java.util.HashSet)

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