Example usage for java.nio.file WatchEvent context

List of usage examples for java.nio.file WatchEvent context

Introduction

In this page you can find the example usage for java.nio.file WatchEvent context.

Prototype

T context();

Source Link

Document

Returns the context for the event.

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;
                }//  w w w  . ja v a2  s.co m
                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: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;
        }/*from   w  w w.ja v a 2  s  . c o  m*/
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            System.out.println("Kind: " + event.kind());
            System.out.println("Context: " + event.context());
            System.out.println("Count: " + event.count());
            System.out.println();
        }
        boolean valid = watchKey.reset();
        System.out.println(valid);

    }
}

From source file:Main.java

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

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();// ww w .  j  ava 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: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.ja 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: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  www.  ja va  2  s .  c o m*/
 * @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: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;
                }/*  ww w.  j a  v a  2s  .  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(11, TimeUnit.SECONDS);

        if (key == null) {
            System.out.println("The video camera is jammed - security watch system is canceled!");
            break;
        } else {/*from  w ww. j av  a2  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: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  .  ja v  a  2 s . co 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.apache.logging.log4j.core.appender.rolling.RollingAppenderDirectWriteTempCompressedFilePatternTest.java

@Test
public void testAppender() throws Exception {
    final File dir = new File(DIR);
    dir.mkdirs();/*from  w  w  w  .j  a  v a  2  s.c  o  m*/
    try (final WatchService watcher = FileSystems.getDefault().newWatchService()) {
        WatchKey key = dir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

        for (int i = 0; i < 100; ++i) {
            logger.debug("This is test message number " + i);
        }
        Thread.sleep(50);
        assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
        final File[] files = dir.listFiles();
        assertNotNull(files);
        assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz"))))));

        int temporaryFilesCreated = 0;
        int compressedFiles = 0;
        key = watcher.take();

        for (final WatchEvent<?> event : key.pollEvents()) {
            final WatchEvent<Path> ev = (WatchEvent<Path>) event;
            final Path filename = ev.context();
            if (filename.toString().endsWith(".tmp")) {
                temporaryFilesCreated++;
            }
            if (filename.toString().endsWith(".gz")) {
                compressedFiles++;
            }
        }
        assertTrue("No temporary file created during compression", temporaryFilesCreated > 0);
        assertTrue("Temporarys file created not equals to compressed files",
                compressedFiles == temporaryFilesCreated);
    }
}

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  a2  s .co 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");
    }
}