Package java.nio.file

Examples of java.nio.file.WatchKey


   @Override
   public void run()
   {
      while (alive)
      {
         WatchKey key;
         try
         {
            key = watcher.take();
         }
         catch (InterruptedException e)
         {
            break;
         }
         List<WatchEvent<?>> pollEvents = key.pollEvents();
         for (WatchEvent<?> event : pollEvents)
         {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW)
            {
               continue;
            }

            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            ResourceMonitorImpl resourceMonitor = keys.get(key);
            if (resourceMonitor == null)
            {
               log.finest("WatchKey not recognized " + name + " - " + key.watchable() + "> " + kind);
               continue;
            }
            Path resourcePath = resourceMonitor.getResourcePath();
            Path child = resourcePath.resolve(name);
            log.log(Level.FINE, String.format("%s: %s %s %s\n", event.kind().name(), child, key, keys.keySet()));
            if (kind == ENTRY_CREATE)
            {
               try
               {
                  if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
                  {
                     registerAll(child, resourceMonitor);
                  }
               }
               catch (IOException e)
               {
                  log.log(Level.SEVERE, "Error while registering child directories", e);
               }
               resourceMonitor.onPathCreate(child);
            }
            else if (kind == ENTRY_DELETE)
            {
               resourceMonitor.onPathDelete(child);
            }
            else if (kind == ENTRY_MODIFY)
            {
               resourceMonitor.onPathModify(child);
            }
         }

         if (!keys.containsKey(key))
         {
            // key is no longer available in the keys Map. Cancel it
            key.cancel();
         }
         else
         {
            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid)
            {
               keys.remove(key);
            }
         }
View Full Code Here


   /**
    * Register the given directory with the WatchService
    */
   private void register(Path path, ResourceMonitorImpl monitorImpl) throws IOException
   {
      WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.put(key, monitorImpl);
   }
View Full Code Here

   @Override
   public void run()
   {
      while (alive)
      {
         WatchKey key;
         try
         {
            key = watcher.take();
         }
         catch (InterruptedException e)
         {
            break;
         }
         List<WatchEvent<?>> pollEvents = key.pollEvents();
         for (WatchEvent<?> event : pollEvents)
         {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind == OVERFLOW)
            {
               continue;
            }

            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            ResourceMonitorImpl resourceMonitor = keys.get(key);
            if (resourceMonitor == null)
            {
               log.severe("WatchKey not recognized " + name + " - " + key.watchable() + "> " + kind);
               continue;
            }
            Path resourcePath = resourceMonitor.getResourcePath();
            Path child = resourcePath.resolve(name);
            log.log(Level.FINE, String.format("%s: %s %s %s\n", event.kind().name(), child, key, keys.keySet()));
            if (kind == ENTRY_CREATE)
            {
               try
               {
                  if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS))
                  {
                     registerAll(child, resourceMonitor);
                  }
               }
               catch (IOException e)
               {
                  log.log(Level.SEVERE, "Error while registering child directories", e);
               }
               resourceMonitor.onPathCreate(child);
            }
            else if (kind == ENTRY_DELETE)
            {
               resourceMonitor.onPathDelete(child);
            }
            else if (kind == ENTRY_MODIFY)
            {
               resourceMonitor.onPathModify(child);
            }
         }

         // reset key and remove from set if directory no longer accessible
         boolean valid = key.reset();
         if (!valid)
         {
            keys.remove(key);
         }
      }
View Full Code Here

  @Override
  public void run() {
    while (running) {
      try {
        WatchKey wk = this.ws.poll(15l, TimeUnit.SECONDS);
        if (wk != null) {
          try {
            List<WatchEvent<?>> events = wk.pollEvents();
            for (WatchEvent<?> event : events) {
              if (StandardWatchEventKinds.ENTRY_CREATE
                  .equals(event.kind())) {
                /*
                 * resolve full path to source file
                 */
                Path file = this.sourceFolder
                    .resolve((Path) event.context());
                if (ConfigUtil.handleFile(file, pair)) {
                  handleNewFile(file);
                }
              } else if (StandardWatchEventKinds.ENTRY_DELETE
                  .equals(event.kind())) {
                /*
                 * check if we had a symlink to this file
                 */
                Path file = (Path) event.context();
                if (SymlinkHelper.isSymlinkExisting(file, this.targetFolder)){
                  handleFileDeleted(file);
                }
              }
            }
          } finally {
            wk.reset();
          }
        }
      } catch (InterruptedException e) {
        /*
         * ignore we just take the next iteration or break
View Full Code Here

public class WatchMe {
    public static void main(String[] args) {
        Path currentDirectory = Paths.get(System.getProperty("java.io.tmpdir"));

        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            WatchKey watchKey = currentDirectory.register(watchService, ENTRY_CREATE, ENTRY_DELETE,
                    ENTRY_MODIFY);
           
            do {
                watchKey = watchService.take();

                for (WatchEvent<?> event : watchKey.pollEvents()) {
                    System.out.println(String.format("%s event on %s",
                            event.kind(), event.context()));
                }
            } while (watchKey.reset());
        } catch (Exception e) {
        }
    }
View Full Code Here

        public void run() {
            try {
                WatchService watcher = FileSystems.getDefault().newWatchService();
                Path path = FileSystems.getDefault().getPath(this.modulePath);
                WatchKey key = path.getParent().register(watcher, ENTRY_MODIFY);

                for (;;) {
                    key = watcher.take();
                    for (WatchEvent event: key.pollEvents()) {
                        if (event.kind() == ENTRY_MODIFY){
                            WatchEvent<Path> ev = (WatchEvent<Path>)event;
                            Path filename = ev.context();
                            if (filename.equals(path.getFileName())){
                                this.strategy.reloadPythonModule();
                            }
                        }
                    }
                    key.reset();
                }
            } catch (JFException e) {
            } catch (IOException e) {
                java.lang.System.console().printf(e.toString());
            } catch (InterruptedException e) {
View Full Code Here

  }

  public void watch() throws IOException, InterruptedException {
    LOG.info("Watching directory {} for event(s) {}", watchDirectory, watchEvents);

    WatchKey watchKey = watchDirectory.register(watchService, watchEvents.toArray(new WatchEvent.Kind[watchEvents.size()]));

    while (!stopped) {
      if (watchKey != null) {

        processWatchKey(watchKey);

        if (!watchKey.reset()) {
          LOG.warn("WatchKey for {} no longer valid", watchDirectory);
          break;
        }
      }
View Full Code Here

        try {
          Path root = Paths.get(path);
          WatchService watcher = root.getFileSystem().newWatchService();
          register(root, watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
          while (true) {
            final WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
             
              @SuppressWarnings("unchecked")
              Path item = ((WatchEvent<Path>) event).context();
              Path dir = keys.get(key);
              File file = new File(dir.toString(), item.toString()).getAbsoluteFile();
             
              if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
                if (file.isDirectory()) {
                  //recursive registration of sub-directories
                  register(Paths.get(dir.toString(), item.toString()), watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
                  task.updateProgress(++count);
                } else {
                  URI context = getTargetContext(file);
                  log.debug("Importing '{}'...", file.getAbsolutePath());
                  task.updateMessage("importing...");
                  task.updateDetailMessage(TASK_DETAIL_PATH, file.getAbsolutePath());
                  task.updateDetailMessage(TASK_DETAIL_CONTEXT, context.stringValue());
                  if (execImport(file, context)) {
                    log.info("Sucessfully imported file '{}' into {}", file.getAbsolutePath(), context.stringValue());
                    try {
                      //delete the imported file
                      log.debug("Deleting {}...", file.getAbsolutePath());
                      file.delete();
                    } catch (Exception ex) {
                      log.error("Error deleing {}: {}", file.getAbsolutePath(), ex.getMessage());
                    }
                  }
                  task.updateProgress(++count);
                  task.updateMessage("watching...");
                  task.updateDetailMessage(TASK_DETAIL_PATH, path);
                  task.removeDetailMessage(TASK_DETAIL_CONTEXT);
                }
              } else if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind()) && Files.isDirectory(item)) {
                //TODO: unregister deleted directories?
                task.updateProgress(++count);
              }
             
            }
            if (!key.reset()) {
              // exit loop if the key is not valid
              // e.g. if the directory was deleted
              break;
            }
          }
View Full Code Here

        Files.walkFileTree(root, new FilteringFileVisitor());
    }

    public void processEvents() {
        while (true) {
            WatchKey key = watcher.poll();
            if (key == null) {
                break;
            }
            Path dir = keys.get(key);
            if (dir == null) {
                warn("Could not find key for " + key);
                continue;
            }

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

                // Context for directory entry event is the file name of entry
                Path name = ev.context();
                Path child = dir.resolve(name);

                debug("Processing event {} on path {}", kind, child);

                if (kind == OVERFLOW) {
//                    rescan();
                    continue;
                }

                try {
                    if (kind == ENTRY_CREATE) {
                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {

                            // if directory is created, and watching recursively, then
                            // register it and its sub-directories
                            Files.walkFileTree(child, new FilteringFileVisitor());
                        } else if (Files.isRegularFile(child, NOFOLLOW_LINKS)) {
                            scan(child);
                        }
                    } else if (kind == ENTRY_MODIFY) {
                        if (Files.isRegularFile(child, NOFOLLOW_LINKS)) {
                            scan(child);
                        }
                    } else if (kind == ENTRY_DELETE) {
                        unscan(child);
                    }
                } catch (IOException x) {
                    // ignore to keep sample readbale
                    x.printStackTrace();
                }
            }

            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid) {
                debug("Removing key " + key + " and dir " + dir + " from keys");
                keys.remove(key);

                // all directories are inaccessible
View Full Code Here

        }
    }

    private void watch(final Path path) throws IOException {
        if (watcher != null) {
            WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
            keys.put(key, path);
            debug("Watched path " + path + " key " + key);
        } else {
            warn("No watcher yet for path " + path);
        }
View Full Code Here

TOP

Related Classes of java.nio.file.WatchKey

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.