Example usage for java.nio.file StandardWatchEventKinds ENTRY_CREATE

List of usage examples for java.nio.file StandardWatchEventKinds ENTRY_CREATE

Introduction

In this page you can find the example usage for java.nio.file StandardWatchEventKinds ENTRY_CREATE.

Prototype

WatchEvent.Kind ENTRY_CREATE

To view the source code for java.nio.file StandardWatchEventKinds ENTRY_CREATE.

Click Source Link

Document

Directory entry created.

Usage

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(() -> {/* ww  w .  ja  va2  s  . 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:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

@Override
public void run() {
    try {/*from  ww w. j av  a  2s .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:com.aspc.cms.module.SyncResourceApp.java

private void registerDir(final WatchService watchService, final File dir) throws Exception {
    // Folder we are going to watch
    Path p = dir.toPath();/*from   w w w  .  ja v  a  2  s . co m*/

    p.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE);

    for (File f : dir.listFiles()) {
        if (f.isDirectory()) {
            registerDir(watchService, f);
        }
    }
}

From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java

private Set<File> filesFromEvents() {
    WatchKey key = watcher.poll();
    Set<File> files = new LinkedHashSet<File>();
    while (key != null) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": " + file);
                }//w w w .j  av  a2  s  .c  o m
                if (file.isDirectory()) {
                    files.addAll(walkDirectory(file.toPath()));
                } else {
                    files.add(file);
                }
            } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
                if (event.context() != null && event.context() instanceof Path) {
                    files.addAll(walkDirectory((Path) event.context()));
                } else {
                    files.addAll(walkDirectory(this.directory));
                }
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
            }
        }
        key.reset();
        key = watcher.poll();
    }
    return files;
}

From source file:com.reactive.hzdfs.dll.JarModuleLoader.java

private Set<File> filesFromEvents() throws InterruptedException {
    WatchKey key = watcher.take();
    Set<File> files = new LinkedHashSet<File>();
    if (key != null && key.isValid()) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
                    || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": " + file);
                }/*from  w ww  . j  a  v  a  2s  .c  om*/
                if (isJarFile(file)) {
                    files.add(file);
                } else
                    log.warn("[JAR Loader] Ignoring file:- " + file);
            }

        }
        key.reset();

    }
    return files;
}

From source file:request.processing.ServletLoader.java

/**
 * Watch dir monitors the current directory for any new files and calls
 * loadJar on them./*from  ww  w . ja v  a2  s  .  co m*/
 */
public static void watchDir() {

    WatchService watcher = null;
    try {
        watcher = FileSystems.getDefault().newWatchService();
        WatchKey key = servletDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        servletDir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    } catch (IOException x) {
        System.err.println(x);
    }

    while (true) {
        WatchKey key = null;
        try {
            key = watcher.take();

        } catch (InterruptedException x) {
            System.err.println("Interrupted Exception");
            x.printStackTrace();
        }

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

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

            try {
                System.out.println("Directory Changed!");
                Thread.sleep(1000);
                loadServletsAndConfig();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

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

}

From source file:com.reactivetechnologies.platform.rest.dll.JarModuleLoader.java

private Set<File> filesFromEvents() throws InterruptedException {
    WatchKey key = watcher.take();
    Set<File> files = new LinkedHashSet<File>();
    if (key != null && key.isValid()) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
                    || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": " + file);
                }// w ww  .  j a va 2 s .  c o  m
                if (isJarFile(file)) {
                    files.add(file);
                } else
                    log.warn("[JAR Loader] Ignoring file " + file);
            }

        }
        key.reset();

    }
    return files;
}

From source file:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java

private Set<File> filesFromEvents() {
    Set<File> files = new LinkedHashSet<File>();
    if (this.watcher == null) {
        return files;
    }//from  w  w  w  . j  a v  a 2  s .c  om
    WatchKey key = this.watcher.poll();
    while (key != null) {
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE
                    || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                Path item = (Path) event.context();
                File file = new File(
                        ((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName());
                if (file.isDirectory()) {
                    files.addAll(walkDirectory(file.toPath()));
                } else {
                    if (!file.getPath().contains(".git")
                            && !PatternMatchUtils.simpleMatch(this.excludes, file.getName())) {
                        if (log.isDebugEnabled()) {
                            log.debug("Watch Event: " + event.kind() + ": " + file);
                        }
                        files.add(file);
                    }
                }
            } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
                if (event.context() != null && event.context() instanceof Path) {
                    files.addAll(walkDirectory((Path) event.context()));
                } else {
                    for (Path path : this.directory) {
                        files.addAll(walkDirectory(path));
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Watch Event: " + event.kind() + ": context: " + event.context());
                }
            }
        }
        key.reset();
        key = this.watcher.poll();
    }
    return files;
}

From source file:ddf.camel.component.catalog.content.ContentProducerDataAccessObjectTest.java

@Test
public void testGetEventType() throws Exception {
    File testFile = temporaryFolder.newFile("testEventType");
    GenericFileMessage<File> mockMessage = getMockMessage(testFile);

    // test that a new standard kind is created if storeRefKey == false
    assertThat(contentProducerDataAccessObject.getEventType(false, mockMessage)
            .equals(StandardWatchEventKinds.ENTRY_CREATE), is(true));

    // test that the sample kind is returned when storeRefKey == true
    assertThat(contentProducerDataAccessObject.getEventType(true, mockMessage).name().equals("example"),
            is(true));/*from ww w . jav a  2  s .  com*/
}

From source file:org.springframework.integration.file.WatchServiceDirectoryScanner.java

private void registerWatch(Path dir) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("registering: " + dir + " for file creation events");
    }/*from   ww w.  j a  va 2  s.c o m*/
    dir.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE);
}