Example usage for java.nio.file Path register

List of usage examples for java.nio.file Path register

Introduction

In this page you can find the example usage for java.nio.file Path register.

Prototype

@Override
default WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException 

Source Link

Document

Registers the file located by this path with a watch service.

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();/*ww  w  .  j  a va  2 s . c  o  m*/
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == ENTRY_MODIFY) {
                System.out.println("Home dir changed!");
            }
        }
        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 .  com*/
        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 w ww . j a v  a 2s  .  co 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();// www  .j  a  v a  2s  .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:org.apache.nifi.minifi.bootstrap.configuration.ingestors.FileChangeIngestor.java

protected static WatchService initializeWatcher(Path filePath) {
    try {/*from   ww  w. j  a v  a2s .  co m*/
        final WatchService fsWatcher = FileSystems.getDefault().newWatchService();
        final Path watchDirectory = filePath.getParent();
        watchDirectory.register(fsWatcher, ENTRY_MODIFY);

        return fsWatcher;
    } catch (IOException ioe) {
        throw new IllegalStateException("Unable to initialize a file system watcher for the path " + filePath,
                ioe);
    }
}

From source file:SecurityWatch.java

private void register(Path path, Kind<Path> kind) throws IOException {
    path.register(watchService, kind);
}

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/*from ww  w .j  ava  2  s. com*/
 * @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();
        }
    }
}

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  w w  . 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.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java

public void add(MutableHtmlRenderable mutableHtmlRenderable) {
    Path renderablePath = Paths.get(mutableHtmlRenderable.getAbsoluteFilePath());
    Path parentDirectory = renderablePath.getParent();
    if (watchingDirectories.add(parentDirectory)) {
        try {//from ww w.j av a  2  s  .  c  om
            parentDirectory.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        } catch (ClosedWatchServiceException e) {
            throw new UUFException("File watch service is closed.", e);
        } catch (NotDirectoryException e) {
            throw new FileOperationException("Cannot register path '" + parentDirectory
                    + "' to file watch service as it is not a directory.", e);
        } catch (IOException e) {
            throw new FileOperationException("An IO error occurred when registering path '" + parentDirectory
                    + "' to file watch service.'", e);
        }
    }
    watchingRenderables.put(renderablePath, mutableHtmlRenderable);
}

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

private void add(FileReference fileReference, MutableHbsRenderable mutableRenderable) {
    Path renderablePath = Paths.get(fileReference.getAbsolutePath());
    Path parentDirectory = renderablePath.getParent();
    if (watchingDirectories.add(parentDirectory)) {
        try {/*w ww.  j av a2s.com*/
            parentDirectory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
        } catch (ClosedWatchServiceException e) {
            throw new UUFException("File watch service is closed.", e);
        } catch (NotDirectoryException e) {
            throw new FileOperationException("Cannot register path '" + parentDirectory
                    + "' to file watch service as it is not a directory.", e);
        } catch (IOException e) {
            throw new FileOperationException("An IO error occurred when registering path '" + parentDirectory
                    + "' to file watch service.'", e);
        }
    }
    watchingRenderables.put(renderablePath.getFileName(), mutableRenderable);
    mutableRenderable.getMutableExecutable()
            .ifPresent(me -> watchingExecutables.put(Paths.get(me.getPath()).getFileName(), me));
}