Example usage for java.nio.file Path register

List of usage examples for java.nio.file Path register

Introduction

In this page you can find the example usage for java.nio.file Path register.

Prototype

@Override
WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
        throws IOException;

Source Link

Document

Registers the file located by this path with a watch service.

Usage

From source file:cz.muni.fi.pb138.cvmanager.service.PDFgenerator.java

/**
 * By external calling pdflatex function of laTex generates pdf curriculum vitae document from .tex file
 * @param username name of user whose is the CV
 * @return language to export (sk/en)/*from w  w w  . j a  v  a 2  s .  c  o  m*/
 * @throws IOException
 * @throws InterruptedException
 * @throws NullPointerException
 */
public InputStream latexToPdf(String username) throws IOException, InterruptedException, NullPointerException {
    ProcessBuilder pb = new ProcessBuilder("pdflatex", username + "_cv.tex", "--output-directory=");
    File file = new File("cvxml/");
    pb.directory(file);
    Process p = pb.start();

    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("cvxml/");
    dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

    while (true) {
        // wait for a key to be available for 10 seconds
        WatchKey key = watcher.poll(10000L, TimeUnit.MILLISECONDS);
        if (key == null) {
            break;
        }

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

            // get file name
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path fileName = ev.context();

            System.out.println(kind.name() + ": " + fileName);
        }

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

    System.out.println("end of cycle");

    File pdf = new File("cvxml/" + username + "_cv.pdf");

    return new FileInputStream(pdf);
}

From source file:com.xiaomi.linden.common.util.FileChangeWatcher.java

@Override
public void run() {
    try {//from ww w. ja  va  2 s . c o  m
        watcher = FileSystems.getDefault().newWatchService();
        Path path = new File(absolutePath).toPath().getParent();
        String fileWatched = FilenameUtils.getName(absolutePath);
        path.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY },
                SensitivityWatchEventModifier.HIGH);
        LOGGER.info("File watcher start to watch {}", absolutePath);

        while (isAlive()) {
            try {
                Thread.sleep(interval);
                WatchKey key = watcher.poll(1000l, TimeUnit.MILLISECONDS);
                if (key == null) {
                    continue;
                }

                List<WatchEvent<?>> events = key.pollEvents();
                for (WatchEvent<?> event : events) {
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        String file = event.context().toString();
                        if (fileWatched.equals(file)) {
                            doOnChange();
                        }
                    }
                }

                if (!key.reset()) {
                    LOGGER.info("File watcher key not valid.");
                }
            } catch (InterruptedException e) {
                LOGGER.error("File watcher thread exit!");
                break;
            }
        }
    } catch (Throwable e) {
        LOGGER.error("File watcher error {}", Throwables.getStackTraceAsString(e));
    }
}

From source file:com.gwac.job.FileTransferServiceImpl.java

void test() {
    try {/*  w w w . ja  v a 2 s  .c  o  m*/
        System.out.println("123");
        watcher = FileSystems.getDefault().newWatchService();
        Path dir = Paths.get("E:/TestData/gwacTest");
        dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
        System.out.println("Watch Service registered for dir: " + dir.getFileName());
        isSuccess = true;
    } catch (IOException ex) {
        isSuccess = false;
        ex.printStackTrace();
    }
}

From source file:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java

@Override
public void initialise(Resource resource) {
    try {/* w  w  w . ja v a2  s  . co 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:com.gwac.job.FileTransferServiceImpl.java

public void transFile() {
    System.out.println("123");
    try {//from w  ww . j  av  a2s  .co m
        System.out.println("123");
        watcher = FileSystems.getDefault().newWatchService();
        Path dir = Paths.get("E:/TestData/gwacTest");
        dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
        System.out.println("Watch Service registered for dir: " + dir.getFileName());
        isSuccess = true;
    } catch (IOException ex) {
        isSuccess = false;
        ex.printStackTrace();
    }

    if (isBeiJingServer || !isSuccess) {
        return;
    }

    if (running == true) {
        log.debug("start job fileTransferJob...");
        running = false;
    } else {
        log.warn("job fileTransferJob is running, jump this scheduler.");
        return;
    }
    try {
        WatchKey key = watcher.poll();
        if (key != null) {
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path fileName = ev.context();
                System.out.println(kind.name() + ": " + fileName);

                if (kind == ENTRY_MODIFY) {
                    System.out.println("My source file has changed!!!");
                }
            }
        }

        boolean valid = key.reset();
        if (!valid) {
            return;
        }
    } catch (Exception ex) {
    }

    if (running == false) {
        running = true;
        log.debug("job fileTransferJob is done.");
    }
}

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 va2s . 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:net.mindengine.dashserver.compiler.GlobalAssetsFileWatcher.java

@Override
public void run() {
    copyAllAssets();//  ww w . j av a2  s . co  m

    Path path = Paths.get(this.assetsFolderPath);
    FileSystem fileSystem = path.getFileSystem();
    try (WatchService service = fileSystem.newWatchService()) {
        path.register(service, ENTRY_MODIFY, ENTRY_CREATE);

        while (true) {
            WatchKey watchKey = service.take();

            for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
                Path watchEventPath = (Path) watchEvent.context();
                String fileName = watchEventPath.toString();
                copyFileAsset(fileName);
            }

            if (!watchKey.reset()) {
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.smarthome.core.transform.AbstractFileTransformationService.java

private void watchSubDirectory(String subDirectory) {
    if (watchedDirectories.indexOf(subDirectory) == -1) {
        String watchedDirectory = getSourcePath() + subDirectory;
        Path transformFilePath = Paths.get(watchedDirectory);
        try {/*from  w  ww  .  j  av a2 s  .c o  m*/
            transformFilePath.register(watchService, ENTRY_DELETE, ENTRY_MODIFY);
            logger.debug("Watching directory {}", transformFilePath);
            watchedDirectories.add(subDirectory);
        } catch (IOException e) {
            logger.warn("Unable to watch transformation directory : {}", watchedDirectory);
            cachedFiles.clear();
        }
    }
}

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 ww.j  a v a  2s  .  co  m
    dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);
}

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

private void registerWatcherForFolder(IWatchEventHandler handler, String folder) {
    Path itemsDir = FileSystems.getDefault().getPath(folder);
    try {//  ww  w. j  a v  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);
    }
}