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: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));
    }// w  w w .j a va 2  s . 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:org.apache.logging.log4j.core.appender.rolling.RollingAppenderTempCompressedFilePatternTest.java

@Test
public void testAppender() throws Exception {
    final File dirTmp = new File(DIR_TMP);
    dirTmp.mkdirs();/*from   w ww.j  av  a2 s .c  o m*/
    try (final WatchService watcher = FileSystems.getDefault().newWatchService()) {
        WatchKey key = dirTmp.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

        final List<String> messages = new ArrayList<>();
        for (int i = 0; i < 500; ++i) {
            final String message = "This is test message number " + i;
            messages.add(message);
            logger.debug(message);
            if (i % 100 == 0) {
                Thread.sleep(500);
            }
        }
        if (!loggerContextRule.getLoggerContext().stop(30, TimeUnit.SECONDS)) {
            System.err.println("Could not stop cleanly " + loggerContextRule + " for " + this);
        }
        final File dir = new File(DIR);
        assertTrue("Directory not created", dir.exists());
        final File[] files = dir.listFiles();
        assertNotNull(files);
        int gzippedFiles = 0;
        for (final File file : files) {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream in = null;
            final FileExtension ext = FileExtension.lookupForFile(file.getName());
            try {
                try (FileInputStream fis = new FileInputStream(file)) {
                    if (ext != null) {
                        gzippedFiles++;
                        try {
                            in = new CompressorStreamFactory()
                                    .createCompressorInputStream(ext.name().toLowerCase(), fis);
                        } catch (final CompressorException ce) {
                            ce.printStackTrace();
                            fail("Error creating intput stream from " + file.toString() + ": "
                                    + ce.getMessage());
                        }
                    } else {
                        in = new FileInputStream(file);
                    }
                    assertNotNull("No input stream for " + file.getName(), in);
                    try {
                        IOUtils.copy(in, baos);
                    } catch (final Exception ex) {
                        ex.printStackTrace();
                        fail("Unable to decompress " + file.getAbsolutePath());
                    }
                }
            } finally {
                Closer.close(in);
            }
            final String text = new String(baos.toByteArray(), Charset.defaultCharset());
            final String[] lines = text.split("[\\r\\n]+");
            for (final String line : lines) {
                messages.remove(line);
            }
        }
        assertTrue("Log messages lost : " + messages.size(), messages.isEmpty());
        assertTrue("Files not rolled : " + files.length, files.length > 2);
        assertTrue("Files gzipped not rolled : " + gzippedFiles, gzippedFiles > 0);

        int temporaryFilesCreated = 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++;
            }
        }
        assertTrue("No temporary file created during compression", temporaryFilesCreated > 0);
        assertTrue("Temporarys file created not equals to compressed files " + temporaryFilesCreated + "/"
                + gzippedFiles, gzippedFiles == temporaryFilesCreated);
    }
}

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   w w w . j  a va 2  s  . co 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();
        }
    }
}