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:org.codelibs.empros.agent.watcher.file.FileWatcher.java

@Override
@SuppressWarnings("restriction")
public void start() {
    if (started.getAndSet(true)) {
        return;/*from   ww  w.j  a va2s  .  com*/
    }

    int count = 0;
    while (true) {
        count++;

        final String key = "watchPath" + count;
        final String value = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES, key, null);
        if (StringUtils.isEmpty(value)) {
            break;
        }

        final File file = new File(value);
        if (!file.isDirectory()) {
            continue;
        }

        final String kindStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".kinds", key,
                "create,modify,delete,overflow");
        final String[] kinds = kindStr.split(",");
        final List<Kind<?>> kindList = new ArrayList<Kind<?>>(4);
        for (final String kind : kinds) {
            if (StringUtils.isNotBlank(kind)) {
                switch (kind.trim()) {
                case "create":
                    kindList.add(StandardWatchEventKinds.ENTRY_CREATE);
                    break;
                case "modify":
                    kindList.add(StandardWatchEventKinds.ENTRY_MODIFY);
                    break;
                case "delete":
                    kindList.add(StandardWatchEventKinds.ENTRY_DELETE);
                    break;
                case "overflow":
                    kindList.add(StandardWatchEventKinds.OVERFLOW);
                    break;
                default:
                    logger.warn("unknown kind: {}", kind);
                    break;
                }
            }
        }

        final String modifierStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".modifiers", key, "");
        final String[] modifiers = modifierStr.split(",");
        final List<WatchEvent.Modifier> modifierList = new ArrayList<WatchEvent.Modifier>(4);
        for (final String modifier : modifiers) {
            if (StringUtils.isNotBlank(modifier)) {
                switch (modifier.trim()) {
                case "fileTree":
                    modifierList.add(com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE);
                    break;
                default:
                    logger.warn("unknown modifier: {}", modifier);
                    break;
                }
            }
        }

        fileWatcherList
                .add(new FileWatchTask(eventManager, file.toPath(), kindList.toArray(new Kind[kindList.size()]),
                        modifierList.toArray(new WatchEvent.Modifier[modifierList.size()])));

    }

    if (fileWatcherList.isEmpty()) {
        logger.info("Cannot find path setting.");
        // TODO shutdown fook
        return;
    }

    for (final FileWatchTask fileWatchTask : fileWatcherList) {
        fileWatchTask.start();
    }

}

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   www  . j  a  v  a  2s  .com*/
        }
    }

    // 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.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java

@Override
public void initialise(Resource resource) {
    try {//from  ww w  .j ava  2 s  .  c o m
        this.resourceFile = resource.getFile().toPath();
        Path parent = resourceFile.getParent();
        this.watchService = parent.getFileSystem().newWatchService();
        this.watchKey = parent.register(this.watchService, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_CREATE);
    } catch (IOException e) {
        throw new ConfigurationException(
                String.format("Failed to initialize watcher for resource '%s'", resource.toString()), e);
    }
}

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 a 2s . co  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:com.reactive.hzdfs.dll.JarModuleLoader.java

private void registerWatch(Path dir) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("registering: " + dir + " for file events");
    }/*w w w.  ja v  a2s  . co  m*/
    dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
}

From source file:de.elomagic.carafile.client.CaraCloud.java

/**
 * Starts synchronization of the given base path with the registry.
 * <p/>/*from  w ww .j a v  a  2s.  c om*/
 * This method will block till call method {@link CaraCloud#stop() }
 *
 * @throws IOException Thrown when an I/O error occurs
 * @throws InterruptedException Thrown when method stop was called or application will terminate
 * @throws GeneralSecurityException
 */
public void start() throws IOException, InterruptedException, GeneralSecurityException {
    if (client == null) {
        throw new IllegalStateException("Attribute \"client\" must be set.");
    }

    if (basePath == null) {
        throw new IllegalStateException("Attribute \"basePath\" must be set.");
    }

    if (!Files.exists(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must exists.");
    }

    if (!Files.isDirectory(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must be a directory/folder.");
    }

    watcher = FileSystems.getDefault().newWatchService();
    registerDefaultWatch(basePath);

    while (!Thread.interrupted()) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path path = basePath.resolve(event.context().toString());
                createFile(path);
            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {

            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                Path path = basePath.resolve(event.context().toString());
                deleteFile(path);
            } else {
                LOG.error("Unsupported kind: " + event.kind() + ", path: " + event.context());
            }
        }

        key.reset();
    }
}

From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void registerWatcherForFolder(IWatchEventHandler handler, String folder) {
    Path itemsDir = FileSystems.getDefault().getPath(folder);
    try {/*from www. j  av a  2s  . c o m*/
        if (new File(itemsDir.toString()).isDirectory()) {
            itemsDir.register(watcher,
                    new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY,
                            StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE },
                    SensitivityWatchEventModifier.HIGH);
            Log.fine("Folder registered with watcher {0}", folder);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.mangoo.build.Watcher.java

/**
 *
 * USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS:
 *
 * WatchKey watchKey = path.register(//from   www. j a v  a2 s  .  co m
 *    watchService,
 *    ENTRY_CREATE,
 *    ENTRY_DELETE,
 *    ENTRY_MODIFY);
 *
 *  BUT THIS IS DAMN SLOW (at least on a Mac)
 *  THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER
 *  THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
 *   MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
 *
 * @param path
 * @throws IOException
 */
private void register(Path path) throws IOException {
    WatchKey watchKey = path.register(watchService,
            new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE, //NOSONAR
                    StandardWatchEventKinds.ENTRY_MODIFY, //NOSONAR
                    StandardWatchEventKinds.ENTRY_DELETE //NOSONAR
            }, SensitivityWatchEventModifier.HIGH);

    watchKeys.put(watchKey, path);
}

From source file:acromusashi.stream.ml.common.spout.WatchTextBatchSpout.java

/**
 * ???????????????????//from  ww w  .  j a  v a  2 s .  co m
 * 
 * @param collector Collector
 * @throws IOException 
 * @throws InterruptedException ?
 */
@SuppressWarnings({ "rawtypes" })
protected void checkDataFile(TridentCollector collector) throws IOException, InterruptedException {
    // ?????????????????
    if (this.isInitialReaded == false) {
        List<String> fileContents = FileUtils.readLines(this.targetFile);
        emitTuples(fileContents, collector);
        this.isInitialReaded = true;

        // 
        Path dirPath = new File(this.dataFileDir).toPath();
        FileSystem fileSystem = dirPath.getFileSystem();
        this.watcherService = fileSystem.newWatchService();
        this.watchKey = dirPath.register(this.watcherService,
                new Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY });

        return;
    }

    // ????????
    WatchKey detectedKey = this.watcherService.poll(1, TimeUnit.SECONDS);

    // ???????????????????????
    if (detectedKey == null || detectedKey.equals(this.watchKey) == false) {
        return;
    }

    try {
        // ???????????????
        for (WatchEvent event : detectedKey.pollEvents()) {

            Path filePath = (Path) event.context();

            // ?????????????
            if (filePath == null
                    || this.targetFile.toPath().getFileName().equals(filePath.getFileName()) == false) {
                continue;
            }

            List<String> fileContents = FileUtils.readLines(this.targetFile);
            emitTuples(fileContents, collector);
        }
    } finally {
        detectedKey.reset();
    }
}

From source file:com.temenos.interaction.loader.detector.DirectoryChangeActionNotifier.java

protected void initWatchers(Collection<? extends File> resources) {
    if (scheduledTask != null) {
        scheduledTask.cancel(true);/*w  w w.  j a  v a  2 s .  c  om*/
    }
    if (resources == null || resources.isEmpty() || getListeners() == null || getListeners().isEmpty()) {
        return;
    }
    try {
        WatchService ws = FileSystems.getDefault().newWatchService();
        for (File file : resources) {
            Path filePath = Paths.get(file.toURI());
            filePath.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE);
        }

        watchService = ws;
        scheduledTask = executorService.scheduleWithFixedDelay(
                new ListenerNotificationTask(watchService, getListeners(), getIntervalSeconds() * 1000), 5,
                getIntervalSeconds(), TimeUnit.SECONDS);
    } catch (IOException ex) {
        throw new RuntimeException("Error configuring directory change listener - unexpected IOException", ex);
    }
}