Java 类java.nio.file.WatchKey 实例源码

项目:ZombieLib2    文件:DirWatcherService.java   
private void watch() {
    try {
        WatchService watchService = directoryPath.getFileSystem().newWatchService();
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
        while (true) {
            WatchKey watchKey = watchService.take();
            for (final WatchEvent<?> event : watchKey.pollEvents()) {
                takeActionOnChangeEvent(event);
            }
        }

    } catch (InterruptedException interruptedException) {
        System.out.println("Thread got interrupted:" + interruptedException);
    } catch (Exception exception) {
        exception.printStackTrace();
    }

}
项目:Reer    文件:WatchServiceRegistrar.java   
protected void watchDir(Path dir) throws IOException {
    LOG.debug("Registering watch for {}", dir);
    if (Thread.currentThread().isInterrupted()) {
        LOG.debug("Skipping adding watch since current thread is interrupted.");
    }

    // check if directory is already watched
    // on Windows, check if any parent is already watched
    for (Path path = dir; path != null; path = FILE_TREE_WATCHING_SUPPORTED ? path.getParent() : null) {
        WatchKey previousWatchKey = watchKeys.get(path);
        if (previousWatchKey != null && previousWatchKey.isValid()) {
            LOG.debug("Directory {} is already watched and the watch is valid, not adding another one.", path);
            return;
        }
    }

    int retryCount = 0;
    IOException lastException = null;
    while (retryCount++ < 2) {
        try {
            WatchKey watchKey = dir.register(watchService, WATCH_KINDS, WATCH_MODIFIERS);
            watchKeys.put(dir, watchKey);
            return;
        } catch (IOException e) {
            LOG.debug("Exception in registering for watching of " + dir, e);
            lastException = e;

            if (e instanceof NoSuchFileException) {
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            }

            if (e instanceof FileSystemException && e.getMessage() != null && e.getMessage().contains("Bad file descriptor")) {
                // retry after getting "Bad file descriptor" exception
                LOG.debug("Retrying after 'Bad file descriptor'");
                continue;
            }

            // Windows at least will sometimes throw odd exceptions like java.nio.file.AccessDeniedException
            // if the file gets deleted while the watch is being set up.
            // So, we just ignore the exception if the dir doesn't exist anymore
            if (!Files.exists(dir)) {
                // return silently when directory doesn't exist
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            } else {
                // no retry
                throw e;
            }
        }
    }
    LOG.debug("Retry count exceeded, throwing last exception");
    throw lastException;
}
项目:incubator-netbeans    文件:NioNotifier.java   
@Override
protected String nextEvent() throws IOException, InterruptedException {
    WatchKey key;
    try {
        key = watcher.take();
    } catch (ClosedWatchServiceException cwse) { // #238261
        @SuppressWarnings({"ThrowableInstanceNotThrown"})
        InterruptedException ie = new InterruptedException();
        throw (InterruptedException) ie.initCause(cwse);
    }
    Path dir = (Path)key.watchable();

    String res = dir.toAbsolutePath().toString();
    for (WatchEvent<?> event: key.pollEvents()) {
        if (event.kind() == OVERFLOW) {
            // full rescan
            res = null;
        }
    }
    key.reset();
    return res;
}
项目:cas-5.1.0    文件:ServiceRegistryConfigWatcher.java   
@Override
public void run() {
    if (this.running.compareAndSet(false, true)) {
        while (this.running.get()) {
            // wait for key to be signaled
            WatchKey key = null;
            try {
                key = this.watcher.take();
                handleEvent(key);
            } catch (final InterruptedException e) {
                return;
            } finally {
                /*
                    Reset the key -- this step is critical to receive
                    further watch events. If the key is no longer valid, the directory
                    is inaccessible so exit the loop.
                 */
                final boolean valid = key != null && key.reset();
                if (!valid) {
                    LOGGER.warn("Directory key is no longer valid. Quitting watcher service");
                }
            }
        }
    }

}
项目:SuitAgent    文件:PluginPropertiesWatcher.java   
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(pluginDir);
    WatchKey key;
    while (watchService != null){
        try {
            key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                if(watchEvent.kind() == ENTRY_MODIFY){
                    String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString();
                    Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);
                    if(plugin != null){
                        plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                        log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
项目:VKMusicUploader    文件:WatchDirs.java   
/**
 * Processes subevents of the key.
 * @param key That has new events.
 * @param dir For the key.
 * @throws IOException If a subdirectory cannot be registered.
 */
private void processSubevents(final WatchKey key, final Path dir)
    throws IOException {
    for (final WatchEvent event : key.pollEvents()) {
        final WatchEvent.Kind kind = event.kind();
        final Path name = (Path) event.context();
        final Path child = dir.resolve(name);
        Logger.debug(
            this,
            "%s: %s%n", event.kind().name(), child
        );
        if (kind == ENTRY_CREATE) {
            try {
                if (Files.isDirectory(child)) {
                    this.processSubevents(child);
                }
            } catch (final IOException ex) {
                throw new IOException(
                    "Failed to register subdirectories.",
                    ex
                );
            }
        }
    }
}
项目:UDE    文件:UFM.java   
private static void setWatcherOnThemeFile() {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true) {
            final WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {
                //we only register "ENTRY_MODIFY" so the context is always a Path.
                final Path changed = (Path) event.context();
                System.out.println(changed);
                if (changed.endsWith("Theme.css")) {
                    System.out.println("Theme.css has changed...reloading stylesheet.");
                    scene.getStylesheets().clear();
                    scene.getStylesheets().add("resources/Theme.css");
                }
            }
            boolean valid = wk.reset();
            if (!valid)
                System.out.println("Watch Key has been reset...");
        }
    } catch (Exception e) { /*Thrown to void*/ }
}
项目:hippo-groovy-updater    文件:FileSystemWatcher.java   
private void registerRecursively(final Path directory) throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path visitedDirectory, final BasicFileAttributes attrs) throws IOException {
            if (!FileSystemWatcher.this.watchedFiles.matchesDirectory(visitedDirectory)) {
                return FileVisitResult.SKIP_SUBTREE;
            }


            final WatchKey key = visitedDirectory.register(watcher,
                    ENTRY_CREATE,
                    ENTRY_MODIFY,
                    ENTRY_DELETE);

            watchedPaths.put(key, visitedDirectory);

            return FileVisitResult.CONTINUE;
        }
    });
}
项目:hippo-groovy-updater    文件:FileSystemWatcher.java   
/**
 * Keep polling for a short time: when (multiple) directories get deleted the watch keys might
 * arrive just a bit later
 */
private void pollForMoreChanges() throws ClosedWatchServiceException, InterruptedException {
    boolean keepPolling = true;
    List<WatchKey> polledKeys = new ArrayList<>();
    final long startPolling = System.currentTimeMillis();
    while (keepPolling) {
        log.debug("Waiting {} ms for more changes...", POLLING_TIME_MILLIS);
        WatchKey key = watcher.poll(POLLING_TIME_MILLIS, TimeUnit.MILLISECONDS);
        if (key == null) {
            keepPolling = false;
        } else {
            log.debug("Found change for '{}' found during extra polling time", key.watchable());
            polledKeys.add(key);
        }
    }
    log.debug("Polled '{}' more changes during '{}' ms", polledKeys.size(), String.valueOf(System.currentTimeMillis() - startPolling));
    for (WatchKey polledKey : polledKeys) {
        processWatchKey(polledKey);
    }
}
项目:Motunautr    文件:FileWatcher.java   
@SuppressWarnings("unchecked")
@Override
public void run() {
    while (running) {
        try {
            final WatchKey watchKey = watcher.take();
            for (final WatchEvent<?> event : watchKey.pollEvents()) {
                Path changed = (Path) event.context();
                if (changed == null || event.kind() == StandardWatchEventKinds.OVERFLOW) {
                    System.out.println("bad file watch event: " + event);
                    continue;
                }
                changed = watchedDirectory.resolve(changed);
                for (final ListenerAndPath x : listeners) {
                    if (Thread.interrupted() && !running)
                        return;
                    if (changed.startsWith(x.startPath)) {
                        x.listener.fileChanged(changed, (Kind<Path>) event.kind());
                    }
                }
            }
            watchKey.reset();
        } catch (final InterruptedException e) {}
    }
}
项目:ProjectAres    文件:PathWatcherServiceImpl.java   
@Override
protected void run() {
    while(isRunning()) {
        try {
            final WatchKey key = watchService.take();
            final WatchedDirectory watchedDirectory = dirsByKey.get(key);
            if(watchedDirectory == null) {
                logger.warning("Cancelling unknown key " + key);
                key.cancel();
            } else {
                for(WatchEvent<?> event : key.pollEvents()) {
                    watchedDirectory.dispatch((WatchEvent<Path>) event);
                }
                key.reset();
            }
        } catch(InterruptedException e) {
            // ignore, just check for termination
        }
    }
}
项目:Photato    文件:PhotatoFilesManager.java   
private void manageDirectoryDeletion(Path filename) throws IOException {
    PhotatoFolder parentFolder = getCurrentFolder(filename.getParent());
    parentFolder.subFolders.remove(filename.getFileName().toString());
    WatchKey removed = watchedDirectoriesKeys.remove(filename);
    if (removed != null) {
        removed.cancel();
        watchedDirectoriesPaths.remove(removed);
    }

    PhotatoFolder currentFolder = getCurrentFolder(filename);
    if (currentFolder.medias != null) {
        for (PhotatoMedia media : currentFolder.medias) {
            try {
                searchManager.removeMedia(media);
                albumsManager.removeMedia(media);
                thumbnailGenerator.deleteThumbnail(media.fsPath, media.lastModificationTimestamp);
                fullScreenImageGetter.deleteImage(media);
            } catch (IOException ex) {
            }
        }
    }
}
项目:util4j    文件:FileMonitorJdkImpl.java   
public void simpleTest(Path path) throws Exception
{
    WatchService watchService=FileSystems.getDefault().newWatchService();  
    path.register(watchService,   
            StandardWatchEventKinds.ENTRY_CREATE,  
            StandardWatchEventKinds.ENTRY_DELETE,  
            StandardWatchEventKinds.ENTRY_MODIFY);  
    while(true)  
    {  
        WatchKey watchKey=watchService.take();  
           List<WatchEvent<?>> watchEvents = watchKey.pollEvents();  
           for(WatchEvent<?> event : watchEvents){  
               //TODO 根据事件类型采取不同的操作。。。。。。。  
               System.out.println("["+event.context()+"]文件发生了["+event.kind()+"]事件");    
           }  
           watchKey.reset(); 
    } 
}
项目:curiostack    文件:FileWatcher.java   
private FileWatcher(Map<Path, Consumer<Path>> registeredPaths) {
  this.registeredPaths = ImmutableMap.copyOf(registeredPaths);
  try {
    watchService = FileSystems.getDefault().newWatchService();
    ImmutableMap.Builder<WatchKey, Path> watchedDirsBuilder = ImmutableMap.builder();
    for (Map.Entry<Path, Consumer<Path>> entry : registeredPaths.entrySet()) {
      Path dir = entry.getKey().getParent();
      WatchKey key =
          dir.register(
              watchService,
              StandardWatchEventKinds.ENTRY_CREATE,
              StandardWatchEventKinds.ENTRY_DELETE,
              StandardWatchEventKinds.ENTRY_MODIFY);
      watchedDirsBuilder.put(key, dir);
    }
    this.watchedDirs = watchedDirsBuilder.build();
  } catch (IOException e) {
    throw new UncheckedIOException("Could not create WatchService.", e);
  }
  executor = Executors.newSingleThreadScheduledExecutor();
}
项目:jdk8u-jdk    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:jdk8u-jdk    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:openjdk-jdk10    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(int id, Path dir, WatchService watcher) {
    System.out.printf("begin handle %d%n", id);
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            System.out.printf("WatchService %d closing ...%n", id);
            watcher.close();
            System.out.printf("WatchService %d closed %n", id);
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end handle %d%n", id);
}
项目:openjdk-jdk10    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(int id, WatchService watcher) {
    System.out.printf("begin poll %d%n", id);
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do but print
        System.out.printf("poll %d expected exception %s%n", id, expected);
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
    System.out.printf("end poll %d%n", id);
}
项目:handycapper    文件:WatchDir.java   
/**
 * Creates a WatchService and registers the given directory
 */
WatchDir(Path dir, boolean recursive) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey, Path>();
    this.recursive = recursive;

    if (recursive) {
        System.out.format("Scanning %s ...\n", dir);
        registerAll(dir);
        System.out.println("Done.");
    } else {
        register(dir);
    }

    // enable trace after initial registration
    this.trace = true;
}
项目:nifi-minifi    文件:FileChangeIngestorTest.java   
private WatchKey createMockWatchKeyForPath(String configFilePath) {
    final WatchKey mockWatchKey = Mockito.mock(WatchKey.class);
    final List<WatchEvent<?>> mockWatchEvents = (List<WatchEvent<?>>) Mockito.mock(List.class);
    when(mockWatchKey.pollEvents()).thenReturn(mockWatchEvents);
    when(mockWatchKey.reset()).thenReturn(true);

    final Iterator mockIterator = Mockito.mock(Iterator.class);
    when(mockWatchEvents.iterator()).thenReturn(mockIterator);

    final WatchEvent mockWatchEvent = Mockito.mock(WatchEvent.class);
    when(mockIterator.hasNext()).thenReturn(true, false);
    when(mockIterator.next()).thenReturn(mockWatchEvent);

    // In this case, we receive a trigger event for the directory monitored, and it was the file monitored
    when(mockWatchEvent.context()).thenReturn(Paths.get(configFilePath));
    when(mockWatchEvent.kind()).thenReturn(ENTRY_MODIFY);

    return mockWatchKey;
}
项目:code-similarity    文件:FileWatchServiceDemo.java   
public static void main(String[] args) throws Throwable {
    String tempDirPath = "/tmp";
    System.out.println("Starting watcher for " + tempDirPath);
    Path p = Paths.get(tempDirPath);
    WatchService watcher = 
        FileSystems.getDefault().newWatchService();
    Kind<?>[] watchKinds = { ENTRY_CREATE, ENTRY_MODIFY };
    p.register(watcher, watchKinds);
    mainRunner = Thread.currentThread();
    new Thread(new DemoService()).start();
    while (!done) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> e : key.pollEvents()) {
            System.out.println(
                "Saw event " + e.kind() + " on " + 
                e.context());
            if (e.context().toString().equals("MyFileSema.for")) {
                System.out.println("Semaphore found, shutting down watcher");
                done = true;
            }
        }
        if (!key.reset()) {
            System.err.println("Key failed to reset!");
        }
    }
}
项目:openjdk9    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:demo    文件:DirectoryWatcher.java   
/** Notify file system event. */
void processEvent() {
    while(true) {
        WatchKey signal;

        try {
            signal = watcher.take();
        } catch (InterruptedException e) {
            return;
        }

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

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

            Path name = (Path)event.context();
            notify(name.toAbsolutePath().toString(), kind);
        }

        key.reset();
    }
}
项目:Mastering-Mesos    文件:WatchServiceHelper.java   
private void processWatchKey(WatchKey watchKey) throws IOException {
  final long start = System.currentTimeMillis();
  final List<WatchEvent<?>> events = watchKey.pollEvents();

  int processed = 0;

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

    if (!watchEvents.contains(kind)) {
      LOG.trace("Ignoring an {} event to {}", event.context());
      continue;
    }

    WatchEvent<Path> ev = cast(event);
    Path filename = ev.context();

    if (processEvent(kind, filename)) {
      processed++;
    }
  }

  LOG.debug("Handled {} out of {} event(s) for {} in {}", processed, events.size(), watchDirectory, JavaUtils.duration(start));
}
项目:dsync-client    文件:WatcherRegisterConsumer.java   
/**
     * Register watchers recursively. Applicable for unix type operation systems.
     *
     * @param path to directory
     * @throws IOException during watchers registration
     */
    private void registerWatchersRecursively(final Path path) throws IOException {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(final Path dir,
                                                     final BasicFileAttributes attrs) throws IOException {
                LOG.trace("Registering in watcher server: {}", () -> dir);
                final WatchKey watchKey = dir
                        .register(watchService,
                                StandardWatchEventKinds.ENTRY_CREATE,
                                StandardWatchEventKinds.ENTRY_DELETE,
                                StandardWatchEventKinds.ENTRY_MODIFY);
//                 , SensitivityWatchEventModifier.HIGH);
                if (watchKeyConsumer != null) {
                    watchKeyConsumer.accept(watchKey);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
项目:mssqlapplylogs    文件:Watch.java   
private static void registerAll(final Path start,
                                final Map<WatchKey,Path> keys,
                                final WatchService watcher ) throws IOException
{
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>()
    {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException
        {
            register(dir, keys, watcher);

            return FileVisitResult.CONTINUE;
        }
    });
}
项目:elastic-config    文件:LocalFileListenerManager.java   
/**
 * 是否监听事件
 * 
 * @return 是否监听
 */
private boolean listenEvent() {
    WatchKey signal;
    try {
        Thread.sleep(500L);
        signal = watchService.take();
    }
    catch (InterruptedException e) {
        return false;
    }

    for (WatchEvent<?> event : signal.pollEvents()) {
        log.info("event:" + event.kind() + "," + "filename:" + event.context());
        pushEvent(event);
    }

    return signal.reset();
}
项目:baratine    文件:JWatchService.java   
@Override
public void close() throws IOException
{
  ArrayList<JWatchKey> watchList = new ArrayList<>();

  if (_isClosed.getAndSet(true)) {
    return;
  }

  watchList.addAll(_watchList);
  _watchList.clear();

  for (WatchKey key : watchList) {
    key.cancel();
  }
}
项目:LuckPerms    文件:FileWatcher.java   
public void subscribe(String id, Path path, Consumer<String> consumer) {
    if (this.watchService == null) {
        return;
    }

    // Register with a delay to ignore changes made at startup
    this.plugin.getScheduler().asyncLater(() -> {
        try {
            // doesn't need to be atomic
            if (this.keyMap.containsKey(id)) {
                throw new IllegalArgumentException("id already registered");
            }

            WatchKey key = path.register(this.watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
            this.keyMap.put(id, new WatchedLocation(path, key, consumer));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }, 40L);
}
项目:heartbeat    文件:WatcherPinListener.java   
public void run() {
    Logger.info(TAG, "Modified %s STARTED", pin.getCode());
    while (!closed) {
        WatchKey key = null;
        try {
            key = service.take();
        } catch (InterruptedException e) {
        }
        if (this.key.equals(key)) {
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (!kind.equals(ENTRY_MODIFY) || !event.context().toString().equals(pin.getPath().getName()))
                    continue;
                onChange(pin);
            }
        }
        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }
}
项目:OpenFalcon-SuitAgent    文件:PluginPropertiesWatcher.java   
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(pluginDir);
    WatchKey key;
    while (watchService != null){
        try {
            key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                if(watchEvent.kind() == ENTRY_MODIFY){
                    String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString();
                    Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);
                    if(plugin != null){
                        plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                        log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
项目:lider    文件:LiderHotDeployListener.java   
public void init(){
    try {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<WatchKey,Path>();
        File hotDeploymentPath = new File("configurationService.getHotDeploymentPath()");
        if(! hotDeploymentPath.exists()){
            hotDeploymentPath.mkdirs();
        }
        Path dir = Paths.get(configurationService.getHotDeploymentPath()); 
        register(dir);
        new Thread(this).start(); //TODO do something better
    } catch (IOException e) {
        logger.error("[LiderHotDeployListener] Exeption occured when initializing hot deployment listener...");
        e.printStackTrace();
    } 
}
项目:jdk8u_jdk    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:reactive-data    文件: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);
        }
        if(isJarFile(file))
        {
          files.add(file);
        }
        else
          log.warn("[JAR Loader] Ignoring file "+file);
      }

    }
    key.reset();

  }
  return files;
}
项目:milo    文件:DefaultCertificateValidator.java   
private void createWatchService() {
    try {
        this.watchService = trustedDir.toPath().getFileSystem().newWatchService();

        WatchKey trustedKey = trustedDir.toPath().register(
            watchService,
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY
        );

        this.thread = new Thread(new Watcher(watchService, trustedKey));
        this.thread.setName("ua-certificate-directory-watcher");
        this.thread.setDaemon(true);
        this.thread.start();
    } catch (IOException e) {
        logger.error("Error creating WatchService.", e);
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:LotsOfCancels.java   
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:LotsOfCancels.java   
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
项目:sldeditor    文件:FileSystemWatcher.java   
/**
 * Instantiates a new file system watcher.
 *
 * @param parent the parent
 * @param path the path
 */
public void addWatch(FileWatcherUpdateInterface parent, Path path) {
    if (path != null) {
        // The directory that has to be watched needs to be registered. Any
        // object that implements the Watchable interface can be registered.

        // Register three events. i.e. whenever a file is created, deleted or
        // modified the watcher gets informed
        try {
            WatchKey key = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

            watcherMap.put(key, parent);

        } catch (IOException e) {
            // Ignore
        }
    }
}
项目:Reer    文件:WatchServiceRegistrar.java   
private Iterable<File> getCurrentWatchPoints() {
    List<File> currentWatchPoints = new LinkedList<File>();
    for (Map.Entry<Path, WatchKey> entry : watchKeys.entrySet()) {
        if (entry.getValue().isValid()) {
            currentWatchPoints.add(entry.getKey().toFile());
        }
    }
    return currentWatchPoints;
}
项目:incubator-netbeans    文件:NioNotifier.java   
@Override
protected WatchKey addWatch(String pathStr) throws IOException {
    Path path = Paths.get(pathStr);
    try {
        WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        return key;
    } catch (ClosedWatchServiceException ex) {
        throw new IOException(ex);
    }
}