Example usage for java.nio.file StandardWatchEventKinds OVERFLOW

List of usage examples for java.nio.file StandardWatchEventKinds OVERFLOW

Introduction

In this page you can find the example usage for java.nio.file StandardWatchEventKinds OVERFLOW.

Prototype

WatchEvent.Kind OVERFLOW

To view the source code for java.nio.file StandardWatchEventKinds OVERFLOW.

Click Source Link

Document

A special event to indicate that events may have been lost or discarded.

Usage

From source file:Main.java

public static void main(String[] args) {
    try (WatchService ws = FileSystems.getDefault().newWatchService()) {
        Path dirToWatch = Paths.get("C:\\myName");
        dirToWatch.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);
        while (true) {
            WatchKey key = ws.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                Kind<?> eventKind = event.kind();
                if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                    System.out.println("Event  overflow occurred");
                    continue;
                }//from ww  w  .  j av  a 2s .c  om
                WatchEvent<Path> currEvent = (WatchEvent<Path>) event;
                Path dirEntry = currEvent.context();
                System.out.println(eventKind + "  occurred on  " + dirEntry);
            }
            boolean isKeyValid = key.reset();
            if (!isKeyValid) {
                System.out.println("No  longer  watching " + dirToWatch);
                break;
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:MyWatch.java

public void watchRNDir(Path path) throws IOException, InterruptedException {
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);

        while (true) {
            // retrieve and remove the next watch key
            final WatchKey key = watchService.take();

            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                final Kind<?> kind = watchEvent.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }// w  ww .j  ava  2 s. com
                final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                final Path filename = watchEventPath.context();
                System.out.println(kind + " -> " + filename);
            }

            boolean valid = key.reset();

            if (!valid) {
                break;
            }
        }
    }
}

From source file:SecurityWatch.java

public void watchVideoCamera(Path path) throws IOException, InterruptedException {

    watchService = FileSystems.getDefault().newWatchService();
    register(path, StandardWatchEventKinds.ENTRY_CREATE);

    OUTERMOST: while (true) {

        final WatchKey key = watchService.poll();

        if (key == null) {
            System.out.println("The video camera is jammed - security watch system is canceled!");
            break;
        } else {//from  w w  w .j  ava 2s. c o  m

            for (WatchEvent<?> watchEvent : key.pollEvents()) {

                final Kind<?> kind = watchEvent.kind();

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

                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();
                    final Path child = path.resolve(filename);

                    if (Files.probeContentType(child).equals("image/jpeg")) {

                        //print it out the video capture time
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
                        System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
                    } else {
                        System.out.println("The video camera capture format failed! This could be a virus!");
                        break OUTERMOST;
                    }
                }
            }

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

    watchService.close();
}

From source file:SecurityWatch.java

public void watchVideoCamera(Path path) throws IOException, InterruptedException {

    watchService = FileSystems.getDefault().newWatchService();
    register(path, StandardWatchEventKinds.ENTRY_CREATE);

    OUTERMOST: while (true) {

        final WatchKey key = watchService.poll(11, TimeUnit.SECONDS);

        if (key == null) {
            System.out.println("The video camera is jammed - security watch system is canceled!");
            break;
        } else {//from  w w w .java  2 s.  c  o  m

            for (WatchEvent<?> watchEvent : key.pollEvents()) {

                final Kind<?> kind = watchEvent.kind();

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

                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();
                    final Path child = path.resolve(filename);

                    if (Files.probeContentType(child).equals("image/jpeg")) {

                        //print it out the video capture time
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
                        System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
                    } else {
                        System.out.println("The video camera capture format failed! This could be a virus!");
                        break OUTERMOST;
                    }
                }
            }

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

    watchService.close();
}

From source file:org.codelibs.empros.agent.watcher.file.FileWatcher.java

@Override
@SuppressWarnings("restriction")
public void start() {
    if (started.getAndSet(true)) {
        return;//from   w w w.  j  a  v  a 2  s .co m
    }

    int count = 0;
    while (true) {
        count++;

        final String key = "watchPath" + count;
        final String value = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES, key, null);
        if (StringUtils.isEmpty(value)) {
            break;
        }

        final File file = new File(value);
        if (!file.isDirectory()) {
            continue;
        }

        final String kindStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".kinds", key,
                "create,modify,delete,overflow");
        final String[] kinds = kindStr.split(",");
        final List<Kind<?>> kindList = new ArrayList<Kind<?>>(4);
        for (final String kind : kinds) {
            if (StringUtils.isNotBlank(kind)) {
                switch (kind.trim()) {
                case "create":
                    kindList.add(StandardWatchEventKinds.ENTRY_CREATE);
                    break;
                case "modify":
                    kindList.add(StandardWatchEventKinds.ENTRY_MODIFY);
                    break;
                case "delete":
                    kindList.add(StandardWatchEventKinds.ENTRY_DELETE);
                    break;
                case "overflow":
                    kindList.add(StandardWatchEventKinds.OVERFLOW);
                    break;
                default:
                    logger.warn("unknown kind: {}", kind);
                    break;
                }
            }
        }

        final String modifierStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".modifiers", key, "");
        final String[] modifiers = modifierStr.split(",");
        final List<WatchEvent.Modifier> modifierList = new ArrayList<WatchEvent.Modifier>(4);
        for (final String modifier : modifiers) {
            if (StringUtils.isNotBlank(modifier)) {
                switch (modifier.trim()) {
                case "fileTree":
                    modifierList.add(com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE);
                    break;
                default:
                    logger.warn("unknown modifier: {}", modifier);
                    break;
                }
            }
        }

        fileWatcherList
                .add(new FileWatchTask(eventManager, file.toPath(), kindList.toArray(new Kind[kindList.size()]),
                        modifierList.toArray(new WatchEvent.Modifier[modifierList.size()])));

    }

    if (fileWatcherList.isEmpty()) {
        logger.info("Cannot find path setting.");
        // TODO shutdown fook
        return;
    }

    for (final FileWatchTask fileWatchTask : fileWatcherList) {
        fileWatchTask.start();
    }

}

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

@Override
public void run() {
    try {/*w  w w  .  j  a v a2s . c  o m*/
        log.info("Watcher started.");

        initialize();

        while (true) {
            checkInterrupted();

            WatchKey watchKey = watcher.poll(CHECK_TIMEOUT, TimeUnit.MILLISECONDS);

            if (watchKey != null) {
                try {
                    log.debug("Received watchKey: {} - {}", watchKey, watchKey.watchable());

                    Path parentPath = (Path) watchKey.watchable();

                    for (WatchEvent<?> event : watchKey.pollEvents()) {
                        checkInterrupted();

                        log.debug("Received event: {} - {}", event.kind(), event.context());

                        if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                            log.warn("Performing a full scan due loss of native FileSystem tracking data.");

                            // Canceling the old watcher.
                            IOUtils.closeQuietly(watcher);

                            // Clean any pending unaccessible path.
                            unaccessiblePaths.clear();
                            creatingPaths.clear();
                            modifyingPaths.clear();

                            // Re-initialize the monitoring.
                            initialize();

                        } else {
                            Path eventPath = parentPath.resolve((Path) event.context());

                            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                                checkNewPath(eventPath);

                            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                                if (!unaccessiblePaths.contains(eventPath)) {
                                    if (isPathFullyAccessible(eventPath)) {
                                        handlePathChanged(eventPath);

                                    } else {
                                        unaccessiblePaths.add(eventPath);
                                        modifyingPaths.add(eventPath);

                                        log.debug(
                                                "File unacessible upon modification. Starting monitoring for '{}'.",
                                                eventPath);
                                    }
                                }
                            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                                if (unaccessiblePaths.contains(eventPath)) {
                                    unaccessiblePaths.remove(eventPath);

                                    log.debug("Monitored file removed. Canceling monitoring for '{}'.",
                                            eventPath);

                                    if (modifyingPaths.contains(eventPath)) {
                                        modifyingPaths.remove(eventPath);
                                        handlePathRemoved(eventPath);
                                    } else {
                                        creatingPaths.remove(eventPath);
                                    }
                                } else {
                                    handlePathRemoved(eventPath);
                                }
                            }
                        }
                    }

                } finally {
                    watchKey.reset();
                }
            }

            if (!unaccessiblePaths.isEmpty()) {
                checkAccessiblePaths();

            } else if ((updateNotificationTimestamp != -1)
                    && ((System.currentTimeMillis() - updateNotificationTimestamp) > CHECK_TIMEOUT)) {
                // Nothing happened since last update. Resetting the updateTimestamp and requesting a library update on
                // Serviio.
                updateNotificationTimestamp = -1;
                updateServiioReposotories();

            } else if (updateNotificationTimestamp == -1) {
                // No pending path to checks and no pending updates to notify. Check external configuration changes.

                Object newFlagValue = getFieldValue(LibraryManager.getInstance(),
                        "libraryAdditionsCheckerThread");
                if ((configChangeFlag != null) && (newFlagValue != configChangeFlag)) {
                    log.info("Detected configuration change. Restart monitoring.");
                    configChangeFlag = newFlagValue;

                    // Canceling the old watcher.
                    IOUtils.closeQuietly(watcher);

                    // Clean any pending unaccessible path.
                    unaccessiblePaths.clear();
                    creatingPaths.clear();
                    modifyingPaths.clear();

                    // Re-initialize the monitoring.
                    initialize();
                }
            }
        }
    } catch (InterruptedException e) {
        // This thread has been interrupted. Just exit.
        return;

    } finally {
        // Release any bounded resource.
        unaccessiblePaths.clear();
        creatingPaths.clear();
        modifyingPaths.clear();

        IOUtils.closeQuietly(watcher);

        log.info("Watcher stopped.");
    }
}

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);//from  www.  j a  v a2s.  co  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);
}

From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java

private Set<File> filesFromEvents() {
    WatchKey key = watcher.poll();
    Set<File> files = new LinkedHashSet<File>();
    while (key != null) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": " + file);
                }/*from w ww  .j a  va  2 s.c om*/
                if (file.isDirectory()) {
                    files.addAll(walkDirectory(file.toPath()));
                } else {
                    files.add(file);
                }
            } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
                if (event.context() != null && event.context() instanceof Path) {
                    files.addAll(walkDirectory((Path) event.context()));
                } else {
                    files.addAll(walkDirectory(this.directory));
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
            }
        }
        key.reset();
        key = watcher.poll();
    }
    return files;
}

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 {/*  w w  w. ja  v a 2  s  . 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:request.processing.ServletLoader.java

/**
 * Watch dir monitors the current directory for any new files and calls
 * loadJar on them.//from  ww w .  jav  a 2s.co 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;
            }
        }
    }

}