Package java.nio.file

Examples of java.nio.file.WatchKey


      System.out.println("Watch Service registered for dir: "
          + dir.getFileName());

      while (true) {
        WatchKey key;
        try {
          key = watcher.take();
        } catch (final InterruptedException ex) {
          return;
        }

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

          java.awt.EventQueue
              // i dont question the Java API, it works now.
          .invokeLater(() -> {

                final DefaultListModel playListModel = new DefaultListModel();

            final File[] playListFolder = new File(
                Constants.DATA_PATH + "playlist/")
            .listFiles();
            if ((kind == ENTRY_CREATE)
                || ((kind == ENTRY_DELETE)
                    && (playListModel != null) && (playListFolder != null))) {

              for (final File file : playListFolder) {
                playListModel.addElement(file);
              }
              displayList.setModel(playListModel);
                  // / displayList.updateUI();
            }
          });

        }

        final boolean valid = key.reset();
        if (!valid) {
          break;
        }
      }
View Full Code Here


   * @param log
   *              a logger that can be used to log the events
   */
  protected void checkCreated(Logger log)
  {
    WatchKey watchKey = watchService.poll();
    if (watchKey != null)
    {
      List<WatchEvent<?>> events = watchKey.pollEvents();
      for (WatchEvent<?> event : events)
      {
        WatchEvent.Kind<?> eventKind = event.kind();
        Path eventPath = (Path) event.context();

        if (eventKind == ENTRY_CREATE)
        {
          entryCreated(eventPath, log);
        }
        else if (eventKind == ENTRY_DELETE)
        {
          entryDeleted(eventPath, log);
        }
        else if (eventKind == ENTRY_MODIFY)
        {
          entryModified(eventPath, log);
        }
      }

      watchKey.reset();
    }
  }
View Full Code Here

                     dirty = true;
                  }

               }

               WatchKey key = watcher.poll();
               while (key != null)
               {
                  List<WatchEvent<?>> events = key.pollEvents();
                  if (!events.isEmpty())
                  {
                     logger.log(Level.INFO, "Detected changes in repository [" + events.iterator().next().context()
                              + "].");
                     dirty = true;
                  }
                  key.reset();
                  key = watcher.poll();
               }

               if (dirty)
               {
View Full Code Here

    System.out.println("starting scan");


    while (scan) {

      WatchKey watchKey = null;

      try {
        watchKey = watchService.take();
        System.out.println("getting new file...");
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      List<WatchEvent<?>> watchEvents =
          watchKey.pollEvents();

      for (WatchEvent<?> watchEvent : watchEvents) {

        WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;

        paths.add(ev.context());

      }
      watchKey.reset();
    }

  }
View Full Code Here

   */
  @Override
  public void run() {
    while(true) {

      WatchKey key = null;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        org.apache.log4j.Logger fLog = org.apache.log4j.Logger.getLogger("log.script.scriptwatcher");
        fLog.error("Key taking intrrupted.", x);
      }

      Path dir = keys.get(key);

      if (dir == null) {
        System.err.println("Unrecognized key: " + key);
        continue;
      }
     
      for (WatchEvent<?> event : key.pollEvents()) {
       
        @SuppressWarnings("unchecked")
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path name = ev.context();
        Path child = dir.resolve(name);
        File f = child.toFile();
        updateFile(event, f);
      }
     
      key.reset();
    }
  }
View Full Code Here

          System.out.println("scanning from: " + path.toAbsolutePath() + '/');
        } else {
          System.out.println("add: /" + path + '/');
        }
        parents.push(path);
        WatchKey key = path.register(
            watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
        map.put(key, path);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
        System.out.println("add: /" + path);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.out.println("visitFileFailed: " + file);
        throw exc;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        if (exc != null) {
          System.out.println("postVisitDirectory failed: " + dir);
          throw exc;
        }
        parents.pop();
        return FileVisitResult.CONTINUE;
      }
    };
    Files.walkFileTree(rootPath, visitor);
   
    new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(1000);
          Files.createDirectory(rootPath.resolve("tmp"));
          Files.createDirectory(rootPath.resolve("tmp/dir"));
          Files.createFile(rootPath.resolve("tmp/file"));
          Files.createFile(rootPath.resolve("tmp/dir/file2"));
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }).start();

    for (;;) {
      // retrieve key
      WatchKey key = watcher.take();
      Path parent = map.get(key);
      System.out.println("-----");
      // process events
      for (WatchEvent<?> event : key.pollEvents()) {
        if (event.kind().type() == Path.class) {
          Path path = (Path) event.context();
          Path resolved = parent.resolve(path);
          if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
            System.out.println("cre: /" + resolved);
            parents.push(parent);
            Files.walkFileTree(resolved, visitor);
            parents.pop();
          } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
            System.out.println("mod: /" + resolved);
          } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
            System.out.println("del: /" + resolved);
          } else {
            assert false : "Unknown event type: " + event.kind().name();
          }
        } else {
          assert event.kind() == StandardWatchEventKinds.OVERFLOW;
          System.out.print(event.kind().name() + ": ");
          System.out.println(event.count());
        }
      }

      // reset the key
      boolean valid = key.reset();
      if (!valid) {
        // object no longer registered
        map.remove(key);
      }
    }
View Full Code Here

    generate();
    new Thread(new Runnable() {
      @Override
      public void run() {
        while (running) {
          WatchKey key;
          if ((key = watchService.poll()) != null) {
            List<WatchEvent<?>> watchEvents = key.pollEvents();
            for (WatchEvent<?> event : watchEvents) {
              WatchEvent<Path> ev = cast(event);
              if(ev.context().equals(messages)) {
                generate();
                key.reset();
              }
            }
          } else {
            try {
              Thread.sleep(100);
View Full Code Here

        try (WatchService watcher = FileSystems.getDefault().newWatchService();) {
            moduleDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

            LOG.info("Filesystem monitor: Watching module directory " + moduleDir + " for changes.");
            for (;;) {
                final WatchKey key = watcher.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    final WatchEvent.Kind<?> kind = event.kind();

                    if (kind == OVERFLOW) { // An OVERFLOW event can occur regardless of registration if events are lost or discarded.
                        LOG.warn("Filesystem monitor: filesystem events may have been missed");
                        continue;
                    }

                    final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    final Path filename = ev.context(); // The filename is the context of the event.
                    final Path child = moduleDir.resolve(filename); // Resolve the filename against the directory.
                    if (isValidFile(child, kind == ENTRY_DELETE)) {
                        try {
                            final URL jarUrl = child.toUri().toURL();

                            LOG.info("Filesystem monitor: detected module file {} {}", child,
                                    kind == ENTRY_CREATE ? "created"
                                    : kind == ENTRY_MODIFY ? "modified"
                                    : kind == ENTRY_DELETE ? "deleted"
                                    : null);

                            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                                instance.reloadModule(jarUrl);
                            else if (kind == ENTRY_DELETE)
                                instance.unloadModule(jarUrl);
                        } catch (Exception e) {
                            LOG.error("Filesystem monitor: exception while processing " + child, e);
                        }
                    } else {
                        if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                            LOG.warn("Filesystem monitor: A non-jar item " + child.getFileName() + " has been placed in the modules directory " + moduleDir);
                    }
                }
                if (!key.reset())
                    throw new IOException("Directory " + moduleDir + " is no longer accessible");
            }
        } catch (Exception e) {
            LOG.error("Filesystem monitor thread terminated with an exception", e);
            throw Exceptions.rethrow(e);
View Full Code Here

  public static void main(String[] args) throws IOException, InterruptedException {
    Path rootDir = Paths.get("new","directory2");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    rootDir.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

    WatchKey watchKey;
    while (true) {
      watchKey = watchService.take();
      processEvenKey(watchKey);
      watchKey.reset();
    }
  }
View Full Code Here

     * @param path
     *            the path
     */
    protected void register(Path path) {
        try {
            WatchKey key = path.register(fsWatchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
            pathByKey.put(key, path);
        } catch (IOException e) {
            throw new StLightException(e);
        }
    }
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.