Example usage for java.nio.file WatchEvent kind

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

Introduction

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

Prototype

Kind<T> kind();

Source Link

Document

Returns the event kind.

Usage

From source file:org.wso2.appserver.integration.tests.logging.accesslogs.HttpAccessLogTestCase.java

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

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

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

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

    boolean isNewLogFilesAreCreated = false;

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

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

            if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {

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

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

}

From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

@SuppressWarnings("unchecked")
@Test// w w w  . j a v a 2  s. co m
public void logAndRotateAndPurge() throws Exception {
    clean("target/ArchivingTestPurge-" + format + "/logs");

    final AtomicReference<String> today = new AtomicReference<>();
    final Map<String, String> config = new HashMap<>();

    // initial config
    today.set("2015-09-01");
    config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log");
    config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives");
    config.put("archiveFormat", format);
    config.put("archiveOlderThan", "1 s");
    config.put("purgeOlderThan", "2 s");
    config.put("limit", "10 kilobytes");
    config.put("level", "INFO");
    config.put("dateCheckInterval", "1 second");

    final LocalFileHandler handler = new LocalFileHandler() {
        @Override
        protected String currentDate() {
            return today.get();
        }

        @Override
        protected String getProperty(final String name, final String defaultValue) {
            final String s = config.get(name.substring(name.lastIndexOf('.') + 1));
            return s != null ? s : defaultValue;
        }
    };

    final String string10chars = "abcdefghij";
    final int iterations = 950;
    for (int i = 0; i < iterations; i++) {
        handler.publish(new LogRecord(Level.INFO, string10chars));
    }

    today.set("2015-09-02");
    try {
        Thread.sleep(2000);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    final File logArchive = new File(
            "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format);
    final File parentFile = logArchive.getParentFile();
    if (!parentFile.exists() && !parentFile.mkdirs()) {
        Assert.fail("Unable to create: " + parentFile);
    }
    final Path dir = parentFile.toPath();
    final WatchService watcher = FileSystems.getDefault().newWatchService();
    final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    latch.set(new CountDownLatch(1));
    watch(key);

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving

    assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS));
    final WatchEvent<?> watchEvent = lastEvent.get();

    assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind())
            || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind()));

    final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;

    final String io = ev.context().toString();
    assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format));

    today.set("2015-09-03");
    try {
        Thread.sleep(2500);
    } catch (final InterruptedException e) {
        Thread.interrupted();
    }

    handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging
    handler.close();
    withRetry(10, 2, new Runnable() {
        @Override
        public void run() {
            assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists());
        }
    });
}

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

/**
 * tail??//from ww w.  jav a2  s.  c om
 *
 * @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:com.dm.estore.common.config.Cfg.java

private void startWatcher(final String configDirPath) throws IOException {
    Path path = Paths.get(configDirPath);
    path.register(watchService, ENTRY_MODIFY);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override/*from   ww  w .j a v a2 s .c om*/
        public void run() {
            try {
                keepWatching = false;
                watchService.close();
            } catch (IOException e) {
                LOG.error("Unable to stop configuration watch service", e);
            }
        }
    });

    FutureTask<Integer> watchTask = new FutureTask<>(new Callable<Integer>() {
        private int totalEventCount;

        @Override
        public Integer call() throws Exception {
            while (keepWatching) {
                try {
                    WatchKey watchKey = watchService.poll(5, TimeUnit.SECONDS);
                    if (watchKey != null) {
                        boolean updateConfiguration = false;
                        for (WatchEvent<?> event : watchKey.pollEvents()) {
                            LOG.debug("Configuration changed: " + event.kind());
                            updateConfiguration = true;
                            totalEventCount++;
                        }
                        if (!watchKey.reset()) {
                            // handle situation no longer valid
                            keepWatching = false;
                        } else {
                            if (updateConfiguration) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(1000);
                                            getConfig().getString(CommonConstants.Cfg.CFG_UPDATE_TRIGGER);
                                        } catch (InterruptedException ex) {
                                            // do nothing
                                        }
                                    }
                                }).start();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            return totalEventCount;
        }
    });
    new Thread(watchTask).start();
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLog.java

@Override
public Integer call() throws Exception {
    Integer res = 0;/*  ww  w.j a v  a2 s  . com*/

    String backupDirStr = config.getBackupDirStr();
    String fullBackupPathStr = config.getFullBackupPathStr();
    String fullBackupDatePatternStr = config.getFullBackupDatePatternStr();
    String laterThanStr = config.getLaterThanStr();
    String fullBackupPatternStr = config.getFullBackupPatternStr();
    String logBackupPatternStr = config.getLogBackupPatternStr();
    String logBackupDatePatternStr = config.getLogBackupDatePatternStr();

    String sqlHost = config.getSqlHost();
    String sqlDb = config.getSqlDb();
    String sqlUser = config.getSqlUser();
    String sqlPass = config.getSqlPass();
    String sqlURL = config.getSqlUrl();
    String sqlProcessUser = config.getSqlProcessUser();

    boolean useLogFileLastMode = BooleanUtils.isTrue(config.getUseLogFileLastMode());
    boolean doFullRestore = BooleanUtils.isTrue(config.getDoFullRestore());
    boolean monitorLogBackupDir = BooleanUtils.isTrue(config.getMonitorLogBackupDir());

    Path backupsDir = null;
    Instant laterThan = null;

    Path fullBackupPath = null;

    // Validate the Log Backup Directory
    if (StringUtils.isBlank(backupDirStr)) {
        LOGGER.error("Invalid blank/empty backup directory");

        return 1;
    }

    try {
        backupsDir = Paths.get(backupDirStr);
    } catch (Exception ex) {
        LOGGER.error(String.format("Error parsing Backup Directory '%s'", backupDirStr), ex);

        return 1;
    }

    if (Files.notExists(backupsDir)) {
        LOGGER.error(String.format("Invalid non-existant backup directory '%s'", backupsDir));

        return 1;
    }

    if (StringUtils.isBlank(logBackupPatternStr)) {
        LOGGER.warn(String.format(
                "\"Log Backup Pattern\" cannot be empty.  Defaulting to " + "%s regex in backup directory",
                DEFAULT_LOG_FILE_PATTERN_STR));

        logBackupPatternStr = DEFAULT_LOG_FILE_PATTERN_STR;
    }

    if (StringUtils.isNoneBlank(fullBackupPathStr)) {
        fullBackupPath = Paths.get(fullBackupPathStr);
        if (Files.notExists(fullBackupPath) || Files.isRegularFile(fullBackupPath) == false) {
            LOGGER.error(String.format("Invalid Full Backup file '%s'", backupDirStr));

            return 1;
        }
    }

    if (StringUtils.isNoneBlank(fullBackupDatePatternStr) && StringUtils.isBlank(laterThanStr)
            && fullBackupPath != null) {
        // Retrieve the "Later Than" date from the full backup file name
        laterThan = FSHelper.getTimestampFromFilename(fullBackupPatternStr, fullBackupDatePatternStr, 1,
                fullBackupPath);
        if (laterThan == null) {
            LOGGER.error("'Later Than' cannot be null");

            return 1;
        }
    } else {
        // Use the "Later Than" timestamp from the command line or properties
        // file.

        try {
            laterThan = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(laterThanStr));
        } catch (Exception ex) {
            LOGGER.error(String.format("Error parsing 'Later Than' time '%s'", laterThanStr), ex);
        }
    }

    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        LOGGER.error("Error loading SQL Server driver [ net.sourceforge.jtds.jdbc.Driver ]", ex);

        return 1;
    }

    if (StringUtils.isBlank(sqlURL)) {
        // Build the SQL URL
        sqlURL = String.format("jdbc:jtds:sqlserver://%s;DatabaseName=master", sqlHost);
    }

    Properties props = new Properties();

    props.setProperty("user", sqlUser);
    props.setProperty("password", sqlPass);

    try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
        if (conn == null) {
            LOGGER.error("Connection to MSSQL failed.");

            return 1;
        }

        if (doFullRestore) {
            LOGGER.info(String.format("\nStarting full restore of '%s'...", fullBackupPathStr));

            StopWatch sw = new StopWatch();

            sw.start();

            String strDevice = fullBackupPathStr;

            String query = String.format("RESTORE DATABASE %s FROM DISK='%s' WITH NORECOVERY, REPLACE", sqlDb,
                    strDevice);

            Statement stmt = null;

            try {
                stmt = conn.createStatement();
            } catch (SQLException ex) {
                LOGGER.debug("Error creating statement", ex);

                return 1;
            }

            try {
                boolean sqlRes = stmt.execute(query);
            } catch (SQLException ex) {
                LOGGER.error(String.format("Error executing...\n'%s'", query), ex);

                return 1;
            }

            sw.stop();

            LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString()));
        }
    } catch (SQLException ex) {
        LOGGER.error("SQL Exception restoring the full backup", ex);
    }

    // Filter the log files.

    // Loop multiple times to catch new logs that have been transferred
    // while we process.
    List<Path> files = null;
    do {
        try {
            files = FSHelper.listLogFiles(backupsDir, laterThan, useLogFileLastMode, logBackupPatternStr,
                    logBackupDatePatternStr, files);
        } catch (IOException ex) {
            LOGGER.error("Log Backup file filter/sort failed", ex);

            return 1;
        }

        if (files == null || files.isEmpty()) {
            LOGGER.debug("No Log Backup files found this iteration.");

            continue;
        }

        StringBuilder msg = new StringBuilder();

        for (Path file : files) {
            msg.append(String.format("file : '%s'\n", file));
        }

        LOGGER.debug(msg.toString());

        // Restore all log files
        try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
            for (Path p : files) {
                try {
                    MSSQLHelper.restoreLog(p, sqlProcessUser, sqlDb, conn);
                } catch (SQLException ex) {
                    LOGGER.error(String.format("SQL Exception restoring the log backup '%s'", p), ex);
                }
            }
        } catch (SQLException ex) {
            LOGGER.error("SQL Exception restoring the log backup", ex);
        }
    } while (files != null && files.isEmpty() == false);

    if (monitorLogBackupDir) {
        // Watch for new log files
        List<Path> paths = new ArrayList();
        paths.add(backupsDir);

        final Watch watch;
        final String currSQLDb = sqlDb;
        final String currSQLProcUser = sqlProcessUser;
        final String currSQLURL = sqlURL;
        final String currLogBackupPatternStr = logBackupPatternStr;

        try {
            watch = Watch.from(paths);
            watch.processEvents((WatchEvent<Path> event, Path path) -> {
                int watchRes = 0;

                if (event.kind() != StandardWatchEventKinds.ENTRY_CREATE) {
                    return watchRes;
                }

                Pattern fileMatcher = Pattern.compile(currLogBackupPatternStr);

                if (fileMatcher.matcher(path.getFileName().toString()).matches()) {
                    try (Connection conn = MSSQLHelper.getConn(currSQLURL, props)) {
                        MSSQLHelper.restoreLog(path, currSQLProcUser, currSQLDb, conn);
                    } catch (SQLException ex) {
                        // There's really no recovering from a failed log backup

                        LOGGER.error("SQL Exception restoring the log backup", ex);

                        System.exit(1);
                    }
                }

                return watchRes;
            });
        } catch (IOException | FileCheckException ex) {
            LOGGER.error(String.format("Error watching backup directory...\n'%s'", backupsDir), ex);

            return 1;
        } catch (InterruptedException ex) {
            LOGGER.info(String.format("Interrupted watching backup directory...\n'%s'", backupsDir), ex);
        }
    }

    return res;
}

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

@Override
public void run() {
    try {/*from   w ww  .  jav a  2 s.  co  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:MonitorSaurausRex.MainMenu.java

public boolean MonitorDirectory() {

    Path directory = Paths.get("C:/Users/" + user + "/Documents/");
    try {//from   ww  w .  ja  v  a 2s . c o m
        WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);

        testTimer = new TimerTask() {

            @Override
            public void run() {
                checkPause = true;
                test = changeCheck();

                if (test) {
                    testTimer.cancel();
                    System.out.println("Quaritnen sucsessfully activates");
                }
            }

        };

        Timer timer = new Timer();
        timer.schedule(testTimer, 0, 1000);
        while (true) {
            WatchKey watchKeyActual = fileSystemWatchService.take();
            for (WatchEvent<?> event : watchKeyActual.pollEvents()) {

                WatchEvent.Kind<?> eventKind = event.kind();

                if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }

                WatchEvent<Path> eventPath = (WatchEvent<Path>) event;
                Path fileName = eventPath.context();

                //timerCheck(); ????? 
                //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java
                //  boolean test = false;
                if (checkPause == false) {
                    checkPause = true;
                } else {
                    ChangeCounter++;
                    System.out.println("Event " + eventKind + " occurred on " + fileName);
                }
                if (test)
                    break;
            }
            boolean isReset = watchKeyActual.reset();
            if (!isReset || test) {
                break;
            }
        }

    } catch (IOException | InterruptedException ioe) {
    }

    return true; /// EXIT METHOD
}

From source file:org.flowerplatform.web.git.GitUtils.java

public void listenForChanges(File file) throws IOException {
    Path path = file.toPath();//from ww  w  .ja va2s.  c  o  m
    if (file.isDirectory()) {
        WatchService ws = path.getFileSystem().newWatchService();
        path.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);
        WatchKey watch = null;
        while (true) {
            System.out.println("Watching directory: " + file.getPath());
            try {
                watch = ws.take();
            } catch (InterruptedException ex) {
                System.err.println("Interrupted");
            }
            List<WatchEvent<?>> events = watch.pollEvents();
            if (!watch.reset()) {
                break;
            }
            for (WatchEvent<?> event : events) {
                Kind<Path> kind = (Kind<Path>) event.kind();
                Path context = (Path) event.context();
                if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
                    System.out.println("OVERFLOW");
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
                    System.out.println("Created: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) {
                    System.out.println("Deleted: " + context.getFileName());
                } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
                    System.out.println("Modified: " + context.getFileName());
                }
            }
        }
    } else {
        System.err.println("Not a directory. Will exit.");
    }
}

From source file:org.pgptool.gui.tools.fileswatcher.MultipleFilesWatcher.java

private Thread buildThreadAndStart() {
    Thread ret = new Thread("FilesWatcher-" + watcherName) {
        @Override//from   ww  w.  j a  v  a  2s . c o  m
        public void run() {
            log.debug("FileWatcher thread started " + watcherName);
            boolean continueWatching = true;
            while (continueWatching) {
                WatchKey key;
                try {
                    idleIfNoKeysRegistered();
                    key = watcher.take();
                    // NOTE: Since we're watching only one folder we assume
                    // that there will be only one key for our folder
                } catch (ClosedWatchServiceException cwe) {
                    log.error("ClosedWatchServiceException fired, stoppign thread.", cwe);
                    return;
                } catch (InterruptedException x) {
                    log.debug("FileWatcher thread stopped by InterruptedException", x);
                    return;
                } catch (Throwable t) {
                    log.error("Unexpected exception while checking for updates on watched file", t);
                    return;
                }

                BaseFolder baseFolder = null;
                synchronized (watcherName) {
                    baseFolder = keys.get(key);
                }
                if (baseFolder == null) {
                    key.cancel();
                    continue;
                }

                for (WatchEvent<?> event : key.pollEvents()) {
                    // Context for directory entry event is the file name of
                    // entry
                    WatchEvent<Path> ev = cast(event);
                    Path name = ev.context();
                    Path child = baseFolder.path.resolve(name);
                    String relativeFilename = FilenameUtils.getName(child.toString());
                    if (!baseFolder.interestedFiles.contains(relativeFilename)
                            && !event.kind().equals(ENTRY_CREATE)) {
                        continue;
                    }

                    // print out event
                    log.debug("Watcher event: " + event.kind().name() + ", file " + child);
                    dirWatcherHandler.handleFileChanged(event.kind(), child.toString());
                }

                // reset key and remove from set if directory no longer
                // accessible
                boolean valid = key.reset();
                if (!valid) {
                    synchronized (watcherName) {
                        keys.remove(key);
                        baseFolders.remove(baseFolder.folder);
                    }
                }
            }
            log.debug("FileWatcher thread stopped " + watcherName);
        }

        private void idleIfNoKeysRegistered() throws InterruptedException {
            while (true) {
                synchronized (watcherName) {
                    if (!keys.isEmpty()) {
                        break;
                    }
                }
                Thread.sleep(500);
            }
        };
    };
    ret.start();
    return ret;
}

From source file:erigo.filewatch.FileWatch.java

/**
 * Process new file events from the Java WatchService; stop when we see a file called "end.txt".
 *
 * This method uses Java WatchService, i.e. this is an event-driven method to get file updates.
 *///from  w ww.j  a va  2s  .  co  m
void processEvents_watchservice() throws IOException {
    for (;;) {

        // wait for key to be signaled
        WatchKey key;
        try {
            // The ".take()" method is a blocking read; can also use one of
            // the ".poll()" non-blocking methods if desired.
            key = watcher.take();
        } catch (InterruptedException x) {
            System.err.println("processEvents(): got InterruptedException: " + x);
            return;
        }

        // process all events
        // base time for all files currently in the queue
        double eventTime = (double) (System.currentTimeMillis());
        Boolean bDone = false;
        for (WatchEvent<?> event : key.pollEvents()) {
            Kind<?> kind = event.kind();
            if (kind == OVERFLOW) {
                // Note: even though we've only registered for ENTRY_CREATE
                //       events, we get OVERFLOW events automatically.
                System.err.println("OVERFLOW detected");
                continue;
            }
            // Extract the filename from the event
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            String filenameStr = name.toString();
            bDone = processNewFile(filenameStr, eventTime);
            if (bDone) {
                break;
            }
        }

        boolean valid = key.reset();
        if (!valid || bDone) {
            // Directory must have gone away or we have received the "end.txt" file
            // we're done
            break;
        }

    }
}