Example usage for java.nio.file WatchKey pollEvents

List of usage examples for java.nio.file WatchKey pollEvents

Introduction

In this page you can find the example usage for java.nio.file WatchKey pollEvents.

Prototype

List<WatchEvent<?>> pollEvents();

Source Link

Document

Retrieves and removes all pending events for this watch key, returning a List of the events that were retrieved.

Usage

From source file:acromusashi.kafka.log.producer.WinApacheLogProducer.java

/**
 * tail??//from   w  w w  .  j  a  v a 2  s.c  o  m
 *
 * @param targetPath ?
 */
public void tailRun(File targetPath) {
    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        Path targetDir = targetPath.toPath();
        targetDir.register(watcher, ENTRY_MODIFY);
        targetDir.relativize(targetPath.toPath());
        List<String> targetFileNames = getTargetLogFiles(Lists.newArrayList(targetDir.toFile().list()));
        Collections.sort(targetFileNames);
        int logFileNameSize = targetFileNames.size();
        this.targetFile = new File(targetDir + "/" + targetFileNames.get(logFileNameSize - 1));

        while (true) {
            WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    logger.warn("OVERFLOW");
                    continue;
                }
                byte[] tail = null;
                boolean noRetry = false;
                for (int retryCount = 0; retryCount < this.retryNum; retryCount++) {
                    try {
                        tail = getTail(this.targetFile);
                        break;
                    } catch (IOException ex) {
                        if (retryCount == this.retryNum - 1) {
                            noRetry = true;
                        }
                    }
                }
                // ?????????????????
                if (noRetry) {
                    break;
                }
                List<String> allFileName = getTargetLogFiles(Arrays.asList(targetDir.toFile().list()));
                Collections.sort(allFileName);
                int allFileNameSize = allFileName.size();
                if (tail.length > 0) {
                    String inputStr = new String(tail, this.encoding);
                    if (!allFileName.equals(targetFileNames)) {
                        this.newFileName.add(allFileName.get(allFileNameSize - 1));
                        targetFileNames = allFileName;
                    }

                    List<String> eachStr = Arrays.asList(inputStr.split(System.getProperty("line.separator")));
                    List<KeyedMessage<String, String>> list = getKeyedMessage(eachStr);
                    this.producer.send(list);
                } else {
                    if (!allFileName.equals(targetFileNames)) {
                        this.newFileName.add(allFileName.get(allFileNameSize - 1));
                        targetFileNames = allFileName;
                    }
                    if (this.newFileName.size() > 0) {
                        this.targetFile = new File(targetDir + "/" + this.newFileName.get(0));
                        this.newFileName.remove(0);
                        targetFileNames = allFileName;
                    }
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    } catch (Exception ex) {
        // FindBugs?Java7????????FindBugs?????????
        logger.error("Failed start producer. ", ex);
    }
}

From source file:org.dishevelled.thumbnail.examples.ThumbnailDrop.java

/**
 * Process file system watcher events.//from   ww w .j a  v  a2  s .c o  m
 */
void processEvents() {
    for (;;) {
        WatchKey key = null;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            return;
        }
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            if (kind == OVERFLOW) {
                continue;
            }

            WatchEvent<Path> pathEvent = cast(event);
            Path name = pathEvent.context();
            Path path = watchDirectory.resolve(name);
            if (kind == ENTRY_CREATE) {
                created(path);
            } else if (kind == ENTRY_MODIFY) {
                modified(path);
            }
        }
        if (!key.reset()) {
            key.cancel();
            try {
                watcher.close();
            } catch (IOException e) {
                // ignore
            }
            break;
        }
    }
}

From source file:com.basistech.yca.FlatteningConfigFileManager.java

private void watchLoop() {
    for (;;) {//from   ww w  .  j  a  v  a 2  s  .c  om

        // wait for key to be signaled
        WatchKey key;
        try {
            key = watchService.take();
        } catch (InterruptedException x) {
            break;
        }

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

            if (kind == OVERFLOW) {
                continue;
            }

            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            processEvent(ev);
        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
    watchKey.cancel();
    try {
        watchService.close();
    } catch (IOException e) {
        LOG.error("Error closing watch service", 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);//  ww  w . j  a v  a2s .  c  om

    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:io.gravitee.gateway.services.localregistry.LocalApiDefinitionRegistry.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        this.init();

        executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "registry-monitor"));
        executor.execute(() -> {/*from  w  ww . ja v  a2  s .c  o  m*/
            Path registry = Paths.get(registryPath);
            LOGGER.info("Start local registry monitor for directory {}", registry);

            try {
                WatchService watcher = registry.getFileSystem().newWatchService();
                registry.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                while (true) {
                    WatchKey key;
                    try {
                        key = watcher.take();
                    } catch (InterruptedException ex) {
                        return;
                    }

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

                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path fileName = registry.resolve(ev.context().getFileName());

                        LOGGER.info("An event occurs for file {}: {}", fileName, kind.name());

                        if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null) {
                                if (apiManager.get(existingDefinition.getId()) != null) {
                                    apiManager.update(loadedDefinition);
                                } else {
                                    apiManager.undeploy(existingDefinition.getId());
                                    definitions.remove(fileName);
                                    apiManager.deploy(loadedDefinition);
                                    definitions.put(fileName, loadedDefinition);
                                }
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = apiManager.get(loadedDefinition.getId());
                            if (existingDefinition != null) {
                                apiManager.update(loadedDefinition);
                            } else {
                                apiManager.deploy(loadedDefinition);
                                definitions.put(fileName, loadedDefinition);
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null
                                    && apiManager.get(existingDefinition.getId()) != null) {
                                apiManager.undeploy(existingDefinition.getId());
                                definitions.remove(fileName);
                            }
                        }

                        boolean valid = key.reset();
                        if (!valid) {
                            break;
                        }
                    }
                }
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while looking for PI definitions from filesystem", ioe);
            }
        });
    }
}

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

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

    try {// w ww  .  ja v a2 s  .  c o m
        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:org.wso2.appserver.integration.tests.logging.accesslogs.HttpAccessLogTestCase.java

@Test(groups = "wso2.as", description = "Send GET and POST requests to generate http access logs and read "
        + "http access log files", dependsOnMethods = "testWebAppUpload")
public void testWebAppResponse() throws Exception {
    //GET request
    HttpResponse response = HttpURLConnectionClient.sendGetRequest(getWebAppURL(WebAppTypes.WEBAPPS) + "/"
            + WEB_APP_NAME + "/services/test_access_log/simpleget?name=abc&domain=wso2.com", null);
    assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
            "GET Request was not successful in user mode : " + userMode);

    //POST Request
    assertEquals(//from w  ww . j  av  a  2 s .co m
            makePostRequest(getWebAppURL(WebAppTypes.WEBAPPS) + "/" + WEB_APP_NAME
                    + "/services/test_access_log/simplepost").toString(),
            "hello abc", "POST Request was not successful in user mode : " + userMode);

    //Register a watch service to wait until log files are created
    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path filePath = Paths.get(logFileLocation);
    filePath.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

    long time = System.currentTimeMillis() + 30 * 1000;

    boolean isNewLogFilesAreCreated = false;

    while (!isNewLogFilesAreCreated && System.currentTimeMillis() < time) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException ex) {
            return;
        }

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

            if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {

                if (request_log_file.exists() && response_log_file.exists() && variable_log_file.exists()) {
                    isNewLogFilesAreCreated = true;
                    break;
                }
            }
        }

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

}

From source file:org.wso2.carbon.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java

private void run() {
    while (!isWatchServiceStopped) {
        WatchKey watchKey;
        try {//from  w  w w.j a  v  a2s . c  o  m
            watchKey = watchService.take();
        } catch (ClosedWatchServiceException e) {
            log.debug("File watch service is closed.");
            return;
        } catch (InterruptedException e) {
            log.debug("File watch service interrupted.");
            return;
        }

        for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
            if (watchEvent.kind() != StandardWatchEventKinds.ENTRY_MODIFY) {
                continue;
            }

            Path updatedDirectory = (Path) watchKey.watchable();
            @SuppressWarnings("unchecked")
            Path updatedFileName = ((WatchEvent<Path>) watchEvent).context();
            // Updating the changed html file
            Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName);
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) {
                for (Path entry : stream) {
                    if (Files.isDirectory(entry)) {
                        continue;
                    }

                    MutableHtmlRenderable mutableHtmlRenderable = watchingRenderables.get(entry);
                    if (mutableHtmlRenderable != null) {
                        try {
                            String content = new String(Files.readAllBytes(entry), StandardCharsets.UTF_8);
                            mutableHtmlRenderable.setHtml(content);
                            log.info("HTML template '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading HTML template '" + entry + "'.", e);
                        }
                    }
                }
            } catch (IOException e) {
                log.error("An error occurred while reloading HTML template '" + updatedFileAbsolutePath + "'.",
                        e);
            }
        }

        boolean valid = watchKey.reset();
        if (!valid) {
            // Watch key cannot not be reset because watch service is already closed.
            break;
        }
    }
}

From source file:bjerne.gallery.service.impl.GalleryRootDirConfigJob.java

private void watchForChanges() {
    Path dir = configFile.getParentFile().toPath();
    try {/*from  w  ww . j a  v a 2 s .  c om*/
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        for (;;) {
            try {
                key = watcher.take();
            } catch (InterruptedException | ClosedWatchServiceException e) {
                LOG.info("Interrupted during watcher.take(). Exiting watch loop.");
                return;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    continue;
                }

                @SuppressWarnings("unchecked")
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filename = ev.context();

                Path child = dir.resolve(filename);
                if (child.equals(configFile.toPath())) {
                    LOG.debug("File was changed.");
                    updateConfigFromFile();
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    } catch (IOException ioe) {
        LOG.error("Exception in filewatcher loop. Exiting.", ioe);
    }
}

From source file:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.RenderableUpdater.java

private void run() {
    while (!isWatchServiceStopped) {
        WatchKey watchKey;
        try {//from w  w  w  .j ava  2 s . c o  m
            watchKey = watcher.take();
        } catch (ClosedWatchServiceException e) {
            log.debug("File watch service is closed.");
            return;
        } catch (InterruptedException e) {
            log.debug("File watch service interrupted.");
            return;
        }

        for (WatchEvent<?> event : watchKey.pollEvents()) {
            if (event.kind() != StandardWatchEventKinds.ENTRY_MODIFY) {
                continue; // We only watch file modify events.
            }

            Path updatedDirectory = (Path) watchKey.watchable();
            @SuppressWarnings("unchecked")
            Path updatedFileName = ((WatchEvent<Path>) event).context();
            MutableHbsRenderable mutableRenderable = watchingRenderables.get(updatedFileName);
            if (mutableRenderable != null) {
                // Updated file is a MutableHbsRenderable
                Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName);
                try {
                    String content = readFileContent(updatedFileAbsolutePath);
                    mutableRenderable.reload(new StringTemplateSource(mutableRenderable.getPath(), content));
                    log.info("Handlebars template '" + updatedFileAbsolutePath + "' reloaded successfully.");
                } catch (UUFException e) {
                    log.error("An error occurred while reloading Handlebars template '"
                            + updatedFileAbsolutePath + "'.", e);
                }
            } else {
                MutableExecutable mutableExecutable = watchingExecutables.get(updatedFileName);
                if (mutableExecutable != null) {
                    // Updated file is a MutableExecutable
                    Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName);
                    try {
                        mutableExecutable.reload(readFileContent(updatedFileAbsolutePath));
                        log.info("JavaScript file '" + updatedFileAbsolutePath + "' reloaded successfully.");
                    } catch (UUFException e) {
                        log.error("An error occurred while reloading JavaScript file '"
                                + updatedFileAbsolutePath + "'.", e);
                    }
                }
            }
        }

        boolean valid = watchKey.reset();
        if (!valid) {
            // Watch key cannot not be reset because watch service is already closed.
            break;
        }
    }
}