Example usage for java.nio.file WatchKey reset

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

Introduction

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

Prototype

boolean reset();

Source Link

Document

Resets this watch key.

Usage

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

private void run() {
    while (!isWatchServiceStopped) {
        WatchKey watchKey;
        try {//from   w  ww .  j  av a2 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;
        }
    }
}

From source file:ch.cyberduck.core.local.FileWatcher.java

public CountDownLatch register(final Local file, final FileWatcherListener listener) throws IOException {
    // Make sure to canonicalize the watched folder
    final Path folder = new File(file.getParent().getAbsolute()).getCanonicalFile().toPath();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Register folder %s watching for file %s", folder, file));
    }/*from  www . java2s  .c o  m*/
    final WatchKey key = monitor.register(folder,
            new WatchEvent.Kind[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY });
    if (!key.isValid()) {
        throw new IOException(String.format("Failure registering for events in %s", file));
    }
    final CountDownLatch lock = new CountDownLatch(1);
    pool.execute(new Callable<Boolean>() {
        @Override
        public Boolean call() throws IOException {
            while (true) {
                // wait for key to be signaled
                final WatchKey key;
                try {
                    lock.countDown();
                    if (log.isDebugEnabled()) {
                        log.debug(String.format("Wait for key from watch service %s", monitor));
                    }
                    key = monitor.take();
                } catch (ClosedWatchServiceException e) {
                    // If this watch service is closed
                    return true;
                } catch (InterruptedException e) {
                    return false;
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Retrieved key %s from watch service %s", key, monitor));
                }
                for (WatchEvent<?> event : key.pollEvents()) {
                    final WatchEvent.Kind<?> kind = event.kind();
                    if (log.isInfoEnabled()) {
                        log.info(String.format("Detected file system event %s", kind.name()));
                    }
                    if (kind == OVERFLOW) {
                        log.error(String.format("Overflow event for %s", folder));
                        break;
                    }
                    // The filename is the context of the event. May be absolute or relative path name.
                    if (matches(normalize(LocalFactory.get(folder.toString()), event.context().toString()),
                            LocalFactory.get(folder.toString(), file.getName()))) {
                        callback(LocalFactory.get(folder.toString()), event, listener);
                    } else {
                        log.warn(String.format("Ignored file system event for unknown file %s",
                                event.context()));
                    }
                }
                // Reset the key -- this step is critical to receive further watch events.
                boolean valid = key.reset();
                if (!valid) {
                    // The key is no longer valid and the loop can exit.
                    return true;
                }
            }
        }
    });
    return lock;
}

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

/**
 * tail??//from   w  w  w .  jav a2  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.dia.kafka.isatools.producer.DirWatcher.java

/**
 * Process all events for keys queued to the watcher
 * @param isatProd//  w ww. j a  v  a 2  s.co  m
 */
void processEvents(ISAToolsKafkaProducer isatProd) {
    for (;;) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        List<JSONObject> jsonParsedResults = new ArrayList<JSONObject>();

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

            // TBD - provide example of how OVERFLOW event is handled
            if (kind == OVERFLOW) {
                continue;
            }

            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // If an inner file has been modify then, recreate the entry
            if (kind == ENTRY_MODIFY || kind == ENTRY_CREATE) {
                File fileCheck = child.getParent().toFile();
                if (child.toFile().isDirectory()) {
                    fileCheck = child.toFile();
                }

                System.out.format("[%s] %s : %s\n", this.getClass().getSimpleName(), kind.toString(),
                        fileCheck.getAbsolutePath());
                List<String> folderFiles = ISAToolsKafkaProducer.getFolderFiles(fileCheck);
                List<JSONObject> jsonObjects = ISAToolsKafkaProducer.doTikaRequest(folderFiles);
                if (!jsonObjects.isEmpty()) {
                    //                        jsonParsedResults.addAll(jsonObjects);
                    isatProd.sendISAToolsUpdates(jsonObjects);
                }
            }

            // TODO this event has still to be specified for documents
            if (kind == ENTRY_DELETE) {
                System.err.println(String.format("Delete event not supported %s", child.toAbsolutePath()));
            }

            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (kind == ENTRY_CREATE) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException x) {
                    // ignore to keep sample readbale
                    System.err.format("IOException when creating %s \n", child.toAbsolutePath());
                }
            }
        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}

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  va 2s .  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:org.wso2.carbon.uuf.renderablecreator.hbs.internal.io.HbsRenderableUpdater.java

private void run() {
    while (!isWatchServiceStopped) {
        WatchKey watchKey;
        try {//w ww. j av  a2  s  .  co 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();
            Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName);
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) {
                for (Path entry : stream) {
                    if (Files.isDirectory(entry)) {
                        continue;
                    }

                    MutableHbsRenderable mutableRenderable = watchingRenderables.get(entry);
                    if (mutableRenderable != null) {
                        // Updated file is a MutableHbsRenderable
                        try {
                            mutableRenderable.reload(new StringTemplateSource(
                                    mutableRenderable.getComponentPath(), readFileContent(entry)));
                            log.info("Handlebars template '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading Handlebars template '" + entry + "'.",
                                    e);
                        }
                        continue;
                    }

                    MutableExecutable mutableExecutable = watchingExecutables.get(entry);
                    if (mutableExecutable != null) {
                        // Updated file is a MutableExecutable
                        try {
                            mutableExecutable.reload(readFileContent(entry));
                            log.info("JavaScript file '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading JavaScript file '" + entry + "'.", e);
                        }
                    }
                }
            } catch (IOException e) {
                log.error("An error occurred while reloading modified files '" + updatedFileAbsolutePath + "'.",
                        e);
            }
        }

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

From source file:com.mycompany.trafficimportfileconverter2.Main2Controller.java

private void watchForConsumption() throws IOException {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    try {//  w  w  w .j av a2  s.  c o m
        Path dir = getOutputDir().toPath();
        WatchKey key = dir.register(watcher, ENTRY_DELETE);

        for (;;) {

            if (Thread.interrupted()) {
                key.cancel();
                return;
            }
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

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

                // This key is registered only
                // for ENTRY_CREATE events,
                // but an OVERFLOW event can
                // occur regardless if events
                // are lost or discarded.
                if (kind == OVERFLOW) {
                    continue;
                }

                //                        // The filename is the
                //                        // context of the event.
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filepath = ev.context();
                String filename = filepath.toString();
                System.out.println("the filename was: " + filename);
                System.out.println(kind);
                Optional<String> res = findFile(filename);
                if (res.isPresent()) {
                    System.out.println("BEFORE REMOVAL: " + myfiles.toString());
                    System.out.println("removing: " + res.get());
                    removeFromFiles(res.get());
                    System.out.println("Removed. Now: " + myfiles.toString());
                    int dpi = findThisDP(res.get());
                    if (-1 != dpi) {
                        UI(() -> {
                            datePickers[dpi].setStyle("-fx-background-color: lightgreen");
                            dayLabels[dpi].setStyle("-fx-background-color: lightgreen");
                        });
                    }
                    log("Wide Orbit CONSUMED: " + filename);

                } else {
                    System.out.println("is present was false for: " + filename);
                    System.out.println(myfiles.toString());
                }
                // 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) {
                    return;
                }
                if (myfiles.isEmpty()) {
                    key.cancel();
                    log("ALL WRITTEN FILES CONSUMED.");
                    System.out.println("\n\n\n");

                    return;
                }
            } //end of events
        } //end of infinite loop

    } catch (IOException x) {
        System.err.println(x);
    } finally {
        Thread.currentThread().interrupt();
    }

}

From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void doRun() {
    while (shouldRun) {
        Log.fine("Running the file system watcher.");
        WatchKey key;
        try {/*from   w w  w  . j ava2  s.c  o m*/
            key = watcher.take();
        } catch (InterruptedException x) {
            Log.warn("Interuppted the watcher!!!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.info("Exit watcher run method.");
                return;
            }
            continue;
        }
        Log.fine("Watch event key taken. Runner instance is {0}", this.hashCode());

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

            WatchEvent.Kind<?> kind = event.kind();
            Log.fine("Event is " + kind);
            // This key is registered only
            // for ENTRY_CREATE events,
            // but an OVERFLOW event can
            // occur regardless if events
            // are lost or discarded.
            if (kind == OVERFLOW) {
                continue;
            }

            // The filename is the
            // context of the event.
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path filename = ev.context();

            // Ignore emacs autosave files
            if (filename.toString().contains(".#")) {
                continue;
            }
            Log.finer("Changed file is {0}", filename);
            Path directory = (Path) key.watchable();
            Log.finer("Changed directory is {0}", directory);
            Path fullPath = directory.resolve(filename);
            Log.fine("Changed path is {0}", fullPath);
            Boolean handlerFound = false;
            for (IWatchEventHandler handler : watchedByPath.values()) {
                Log.finer("Checking matching handler {0} {1}", handler.getInternalHandlerLabel(),
                        handler.getWatchedFolder());
                // Ignore private files
                if (filename.getFileName().startsWith(".")) {
                    continue;
                }
                if ((handler.getWatchedFolder().equals(directory.toAbsolutePath().toString())
                        || (handler.getWatchTree() && directory.startsWith(handler.getWatchedFolder())))
                        && (StringUtils.isEmpty(handler.getExtension())
                                || fullPath.toString().endsWith(handler.getExtension()))) {
                    String relativePath = filename.getFileName().toString();
                    Log.info("Handling {0} with watcher {1} for folder {2}", filename,
                            handler.getClass().getName(), handler.getWatchedFolder());
                    try {
                        handler.handle(relativePath, fullPath.toString(), kind, event);
                        handlerFound = true;
                    } catch (Exception e) {
                        Log.exception(e, "Exception processing path={0} handler={1}", relativePath,
                                handler.getClass().getName());
                    }
                }
            }
            if (!handlerFound) {
                Log.info("No handler found for {0}", fullPath);
            }
        }
        // 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) {
            Log.warn("Key invalid! Exit watch.");
            break;
        }
    }
}

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

@Override
public void run() {
    try {/*from   w w w . j  a va 2  s  . 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:de.prozesskraft.pkraft.Manager.java

/**
 * erstellt fuer jeden running step einen watchkey
 * es soll jedes stepverzeichnis mit dem status 'working' observiert werden bis das file ".exit" erscheint
 * @param process/*  w w w. j  a v  a 2s . c om*/
 * @throws IOException 
 */
private static void createWatchKeysForAllRunningSteps(Process process) throws IOException {
    // diesen Thread ablegen, damit er vom zyklischen thread gekillt werden kann
    watcherThread = Thread.currentThread();

    // einen neuen map erzeugen fuer die watchKeys
    keys = new HashMap<WatchKey, Path>();

    WatchService watcher = FileSystems.getDefault().newWatchService();

    // Anlegen des WatchKeys fuer den Prozess (falls er gestoppt wird, erfolgt die Komunikation mit diesem manager ueber das binaerfile)
    Path processDir = Paths.get(process.getRootdir());
    System.err.println("info: creating a watchkey for the process path " + process.getRootdir());
    WatchKey keyProcess = processDir.register(watcher, ENTRY_MODIFY);
    keys.put(keyProcess, processDir);

    // Anlegen der WatchKeys fuer jeden laufenden Step
    for (Step actStep : process.getStep()) {
        if (actStep.getStatus().equals("working")) {
            Path stepDir = Paths.get(actStep.getAbsdir());
            try {
                System.err.println("info: step " + actStep.getName()
                        + " is working -> creating a watchkey for its path " + actStep.getAbsdir());
                System.err.println("debug: creating...");
                WatchKey key = stepDir.register(watcher, ENTRY_CREATE);
                System.err.println("debug: creating...done. putting to the map");
                keys.put(key, stepDir);
                System.err.println("debug: creating...done. putting to the map...done");
            } catch (IOException e) {
                System.err.println(e);
            } catch (Exception e) {
                System.err.println(e);
            }

            java.io.File stepDirExitFile = new java.io.File(actStep.getAbsdir() + "/.exit");
            java.io.File stepDirStatusFile = new java.io.File(actStep.getAbsdir() + "/.status");

            // falls die datei bereits existiert, wird sofort erneut der Prozess weitergeschoben
            // dies ist dann der fall, wenn ein step gestartet wurde, und danach der manager neu gestartet wurde
            if (stepDirExitFile.exists()) {
                System.err.println("info: .exit file already exists -> shortcutting to pushing the process");

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            // falls der step ein process ist, bibts dort kein .exit file sondern ein .status file
            else if (stepDirStatusFile.exists()) {
                System.err.println("info: .status file already exists.");
                try {
                    java.util.List<String> statusInhalt = Files.readAllLines(stepDirStatusFile.toPath(),
                            Charset.defaultCharset());
                    if (statusInhalt.size() > 0) {
                        String firstLine = statusInhalt.get(0);
                        System.err.println("info: status changed to: " + firstLine);

                        System.err.println("info: .status file contains status " + firstLine);
                        // wenn ein finaler status, dann soll manager aufgeweckt werden
                        if (firstLine.equals("error") || firstLine.equals("finished")) {
                            System.err.println("info: --> shortcutting to pushing process");
                            // alle keys loeschen
                            keys = null;

                            // den prozess weiter pushen
                            pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.err.println(
                            "IOException: trying to read file: " + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                } catch (ExceptionInInitializerError e) {
                    System.err.println("ExceptionInInitializerError: trying to read file: "
                            + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                }
            }

        }
    }

    process.log("info", "now into the watchloop");

    // warten auf ein Signal von einem WatchKey
    for (;;) {

        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            System.err.println(new Timestamp(System.currentTimeMillis())
                    + ": ---- watcher thread: interrupted! returning to alternativer Thread");
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            //            System.err.println("debug: poll event " + event);

            WatchEvent.Kind kind = event.kind();

            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            // dieses logging fuehrt zur aenderung von stderr.txt und .log, was wiederum ein ENTRY_MODIFY ausloest etc. endlosschleife bis platte volllaeuft
            //            System.err.println("debug: poll context " + name);
            Path child = dir.resolve(name);
            //            System.err.println("debug: poll child " + child);

            if (kind == ENTRY_CREATE) {
                if (child.endsWith(".exit")) {
                    System.err.println("info: waking up, because file created: " + child.toString());

                    // alle keys loeschen
                    keys = null;

                    // den prozess weiter pushen
                    pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                }
            }
            if ((kind == ENTRY_MODIFY) && (child.endsWith("process.pmb"))) {
                //               System.err.println("info: waking up, because process binary file has been modified: " + child.toString());

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
                if (child.endsWith(".status")) {
                    try {
                        java.util.List<String> statusInhalt = Files.readAllLines(child,
                                Charset.defaultCharset());
                        if (statusInhalt.size() > 0) {
                            String firstLine = statusInhalt.get(0);
                            System.err.println("info: status changed to: " + firstLine);

                            // wenn ein finaler status, dann soll manager aufgeweckt werden
                            if (firstLine.equals("error") || firstLine.equals("finished")) {
                                System.err.println("info: waking up, because status changed to: " + firstLine);
                                // alle keys loeschen
                                keys = null;

                                // den prozess weiter pushen
                                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                            }
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.err.println("IOException: trying to read file: " + child.toString());
                        e.printStackTrace();
                    } catch (ExceptionInInitializerError e) {
                        System.err.println(
                                "ExceptionInInitializerError: trying to read file: " + child.toString());
                        e.printStackTrace();
                    }

                }
            }

            // reset the triggered key
            key.reset();
        }
    }
}