Example usage for java.nio.file WatchService take

List of usage examples for java.nio.file WatchService take

Introduction

In this page you can find the example usage for java.nio.file WatchService take.

Prototype

WatchKey take() throws InterruptedException;

Source Link

Document

Retrieves and removes next watch key, waiting if none are yet present.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    Path dir = FileSystems.getDefault().getPath("/usr/a");

    WatchKey key = dir.register(watcher, ENTRY_MODIFY);

    while (true) {
        key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == ENTRY_MODIFY) {
                System.out.println("Home dir changed!");
            }/*from w  w  w. ja  v  a2  s . c  o m*/
        }
        key.reset();
    }
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("/home/docs");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();
        System.out.println("Path being watched: " + watchKey.watchable());
        if (watchKey.isValid() == false) {
            return;
        }// w w w .  j  a v a 2  s.  c  o m
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            System.out.println("Kind: " + event.kind());
            System.out.println("Context: " + event.context());
            System.out.println("Count: " + event.count());
            System.out.println();
        }
        boolean valid = watchKey.reset();
        System.out.println(valid);

    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("c:/");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();//from   ww w  .j a  v a 2 s  .  c  o  m

        if (watchKey.isValid()) {
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                System.out.println("Kind: " + event.kind());
                System.out.println("Context: " + event.context());
                System.out.println("Count: " + event.count());
                System.out.println();
            }

            boolean valid = watchKey.reset();
            if (!valid) {
                // The watchKey is not longer registered
            }
        }
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {

    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("c:/");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();//from   w  w w . j  a  va 2s  .  c  om

        if (watchKey.isValid()) {
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                System.out.println("Kind: " + event.kind());
                System.out.println("Context: " + event.context());
                System.out.println("Count: " + event.count());
                System.out.println();
            }

            boolean valid = watchKey.reset();
            if (!valid) {
                // The watchKey is not longer registered
            }
        }
    }

}

From source file:request.processing.ServletLoader.java

/**
 * Watch dir monitors the current directory for any new files and calls
 * loadJar on them./* ww  w  .  jav  a 2  s. c o  m*/
 */
public static void watchDir() {

    WatchService watcher = null;
    try {
        watcher = FileSystems.getDefault().newWatchService();
        WatchKey key = servletDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        servletDir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    } catch (IOException x) {
        System.err.println(x);
    }

    while (true) {
        WatchKey key = null;
        try {
            key = watcher.take();

        } catch (InterruptedException x) {
            System.err.println("Interrupted Exception");
            x.printStackTrace();
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();

            if (kind == StandardWatchEventKinds.OVERFLOW) {
                continue;
            }

            try {
                System.out.println("Directory Changed!");
                Thread.sleep(1000);
                loadServletsAndConfig();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    }

}

From source file:org.balloon_project.overflight.task.importer.ImporterFileListener.java

@Override
public void run() {
    // TODO initial import start
    // initial import of existing file
    logger.info("Scanning for files to import");
    File importDir = new File(configuration.getDatabaseImportDirectory());
    if (importDir.exists() && importDir.isDirectory()) {
        for (File file : importDir.listFiles()) {
            if (file.isFile() && file.getPath().endsWith(IndexingTask.N_TRIPLES_EXTENSION)) {
                logger.info("File event: Adding " + file.toString() + " to importer queue");
                importer.startImporting(file);
            }//from  w ww  .  j  a v a 2s. c o m
        }
    }

    // starting file watch service for future files
    try {
        String path = configuration.getDatabaseImportDirectory();
        logger.info("Starting import file listener for path " + path);
        Path tmpPath = Paths.get(path);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        for (;;) {
            WatchKey key = watchService.take();

            for (WatchEvent event : key.pollEvents()) {
                if (event.kind().name() == "OVERFLOW") {
                    continue;
                } else {
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    logger.info("File event: Adding " + filename.toString() + " to importer queue");
                    importer.startImporting(tmpPath.resolve(filename).toFile());
                }
            }

            // Reset the key -- this step is critical if you want to
            // receive further watch events.  If the key is no longer valid,
            // the directory is inaccessible so exit the loop.
            boolean valid = key.reset();
            if (!valid) {
                break;
            }

        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        logger.debug("Stopping import file listener");
    }
}

From source file:org.wso2.carbon.inbound.localfile.LocalFileOneTimePolling.java

@SuppressWarnings("unchecked")
private Object watchDirectory() throws IOException {
    Path newPath = Paths.get(watchedDir);
    WatchService watchService = FileSystems.getDefault().newWatchService();
    try {//from w  ww .j  a v  a 2  s .c  om
        newPath.register(watchService, ENTRY_MODIFY);
        while (true) {
            WatchKey key = watchService.take();
            if (key != null) {
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = watchEvent.kind();
                    WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    Path entry = watchEventPath.context();

                    Path filePath = Paths.get(watchedDir, entry.toString());
                    if (kind == ENTRY_MODIFY) {
                        processFile(filePath, contentType);
                    } else if (kind == OVERFLOW) {
                        continue;
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file is : " + entry);
                    }
                }
                key.reset();
                if (!key.isValid()) {
                    break;
                }
            }
        }
    } catch (IOException e) {
        log.error("Error while watching directory: " + e.getMessage(), e);
    } catch (InterruptedException ie) {
        log.error("Error while get the WatchKey : " + ie.getMessage(), ie);
    } finally {
        watchService.close();
    }
    return null;
}

From source file:com.aspc.cms.module.SyncResourceApp.java

private void monitorDir() throws Exception {
    // Create a new Watch Service
    WatchService watchService = FileSystems.getDefault().newWatchService();

    registerDir(watchService, syncDirectory);

    while (true) {
        try {//from w w  w  .ja v  a2s. c  o  m
            // Obtaining watch keys
            final WatchKey key = watchService.take();//poll(5, TimeUnit.SECONDS);

            if (key == null)
                continue;

            long tmpLastModified = lastModify.get();
            long startLastModified = tmpLastModified;
            try {
                // key value can be null if no event was triggered
                for (WatchEvent<?> watchEvent : key.pollEvents()) {
                    final Kind<?> kind = watchEvent.kind();
                    // Overflow event
                    if (StandardWatchEventKinds.OVERFLOW == kind) {
                        continue; // loop
                    }

                    tmpLastModified = scanChanges(syncDirectory, tmpLastModified);
                }
            } finally {
                key.reset();
            }
            lastModify.compareAndSet(startLastModified, tmpLastModified);
        } catch (Exception e) {
            LOGGER.warn("could not send", e);
            Thread.sleep(60000);
        }
    }
}

From source file:uk.gov.gchq.gaffer.miniaccumulocluster.MiniAccumuloClusterController.java

protected void watchShutdown() {
    LOGGER.info("Watching Shutdown File " + clusterPath + "/" + SHUTDOWN_FILENAME);

    try {//from  www .j  a v a 2 s  . c om
        WatchService watcher = FileSystems.getDefault().newWatchService();
        clusterPath.register(watcher, ENTRY_CREATE);

        OUTER: while (true) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (final InterruptedException e) {
                return;
            }

            for (final WatchEvent<?> event : key.pollEvents()) {
                final WatchEvent.Kind<?> kind = event.kind();

                if (kind == OVERFLOW) {
                    continue;
                }

                final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                final Path filename = ev.context();

                LOGGER.debug("Filename changed " + filename);

                if (filename.toString().equals(SHUTDOWN_FILENAME)) {
                    MiniAccumuloClusterController.this.stop();
                    break OUTER;
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }

        LOGGER.info("Finished Watching Shutdown");
    } catch (final IOException e) {
        LOGGER.error("Failed to watch shutdown", e);
    }
}

From source file:nz.co.fortytwo.signalk.server.SignalKServer.java

protected SignalKServer(String configDir) throws Exception {
    // init config
    Properties props = System.getProperties();
    props.setProperty("java.net.preferIPv4Stack", "true");
    System.setProperties(props);/* www  . j  a va2  s . c  o m*/

    Util.getConfig();
    // make sure we have all the correct dirs and files now
    ensureInstall();

    logger.info("SignalKServer starting....");

    // do we have a USB drive connected?
    //logger.info("USB drive " + Util.getUSBFile());

    // create a new Camel Main so we can easily start Camel
    Main main = new Main();
    //main.setApplicationContextUri("classpath:META-INF/spring/camel-context.xml");
    // enable hangup support which mean we detect when the JVM terminates,
    // and stop Camel graceful
    main.enableHangupSupport();

    // Start activemq broker
    BrokerService broker = ActiveMqBrokerFactory.newInstance();

    broker.start();
    //DNS-SD, zeroconf mDNS
    startMdns();
    configureRouteManager(main);
    // and run, which keeps blocking until we terminate the JVM (or stop
    // CamelContext)
    main.start();

    WatchService service = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("./conf");
    dir.register(service, StandardWatchEventKinds.ENTRY_MODIFY);
    WatchKey key = null;
    while (true) {
        key = service.take();
        // Dequeueing events
        Kind<?> kind = null;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
            // Get the type of the event
            kind = watchEvent.kind();
            logger.debug(
                    "SignalKServer conf/ event:" + watchEvent.kind() + " : " + watchEvent.context().toString());
            if (StandardWatchEventKinds.OVERFLOW == kind) {
                continue; //loop
            } else if (StandardWatchEventKinds.ENTRY_MODIFY == kind) {
                // A new Path was created 
                @SuppressWarnings("unchecked")
                Path newPath = ((WatchEvent<Path>) watchEvent).context();
                // Output
                if (newPath.endsWith("signalk-restart")) {
                    logger.info("SignalKServer conf/signalk-restart changed, stopping..");
                    main.stop();
                    main.getCamelContexts().clear();
                    main.getRouteBuilders().clear();
                    main.getRouteDefinitions().clear();

                    // so now shutdown serial reader and server
                    RouteManager routeManager = RouteManagerFactory.getInstance();
                    routeManager.stopNettyServers();
                    routeManager.stopSerial();
                    if (server != null) {
                        server.stop();
                        server = null;
                    }
                    RouteManagerFactory.clear();
                    configureRouteManager(main);
                    main.start();
                }

            }
        }

        if (!key.reset()) {
            break; //loop
        }
    }

    stopMdns();
    broker.stop();
    // write out the signalk model
    SignalKModelFactory.save(SignalKModelFactory.getInstance());
    System.exit(0);
}