Beispiel #1
0
  /** Обработчик всех событий помещенных в очередь */
  void processEvents() {
    for (; ; ) {

      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        LOG.log(Level.SEVERE, x.getMessage());
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        LOG.log(Level.SEVERE, "Входной каталог не найден!");
        continue;
      }

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

        // TODO - подумать над обработчиком события OVERFLOW
        if (kind == OVERFLOW) {
          continue;
        }

        WatchEvent<Path> ev = cast(event);
        Path name = ev.context();
        Path child = dir.resolve(name);

        // логируем событие
        if (kind == ENTRY_CREATE) {
          LOG.log(Level.FINEST, "{0}: {1}", new Object[] {event.kind().name(), child});
          Runnable worker = new WorkerThread(child);
          executor.execute(worker);
        }
      }

      boolean valid = key.reset();
      if (!valid) {
        keys.remove(key);
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }
  private void doProcess() throws IOException {

    // (1) Create a new watch service
    WatchService watchService = FileSystems.getDefault().newWatchService();
    System.out.println("Watch service example 1:");

    // (2) Get the directory to be monitored
    Path dir = Paths.get(watchedDir);

    // (3) Register the directory to be monitored with the watch service
    WatchKey watchKey = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    System.out.println("Registered dir: " + dir.toString());
    System.out.println("    Watch key (valid): " + watchKey.isValid());

    // (4) Get and process the events that occur
    INFINITE_WHILE_LOOP:
    while (true) {

      // (4a) Wait for the watch key to be signaled of events
      try {
        System.out.println("Waiting for watch key to be signaled...");
        watchService.take();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
        break INFINITE_WHILE_LOOP;
      }

      // (4b) Get and process the events for the watch key
      List<WatchEvent<?>> eventList = watchKey.pollEvents();
      System.out.println("Process the pending events for the watch key: " + eventList.size());

      EVENT_FOR_LOOP:
      for (WatchEvent<?> genericEvent : eventList) {

        // Retrieve and process the event kind
        if (genericEvent.kind() == OVERFLOW) {

          System.out.println("Overflow event");
          continue EVENT_FOR_LOOP; // next event
        }
        // else, genericEvent.kind() is WatchEvent.Kind<Path>
        // values: ENTRY_CREATE...
        System.out.println("Path event kind: " + genericEvent.kind());

        // Retrieve the file name associated with the event
        Path filePath = (Path) genericEvent.context();
        System.out.println("    File: " + filePath.toString());
      } // end EVENT_FOR_LOOP (for a watch key)

      // (4c) Reset the watch key
      boolean validKey = watchKey.reset();
      System.out.println("Watch key reset.");

      if (!validKey) {
        System.out.println("Invalid watch key, close the watch service");
        break INFINITE_WHILE_LOOP;
      }
    } // end, INFINITE_WHILE_LOOP

    // (5) Close the watch service
    watchService.close();
    System.out.println("Watch service closed.");
  } // doProcess()
  void scanDirectory(String path) throws IOException, InterruptedException {

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

    Path directoryName = null;
    Path dir = Paths.get(path);
    // dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    registerAll(dir);

    System.out.println("er i path");

    for (; ; ) {
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException e) {
        e.printStackTrace();
        return;
      }

      //            System.out.println("er i while");

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

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

        if (filename != null) {
          //  System.out.println("filename != null.");
          directory = dir.resolve(filename);
        } else {
          continue;
        }

        // System.out.println("filename er "+filename);
        if (kind == OVERFLOW) {
          //     System.out.println("fikk en overflow. ");
          continue;
        } else if (kind == ENTRY_MODIFY) {

          //  System.out.println(kind.name() + " for path/directory " + directory);

        } else if (kind == ENTRY_CREATE) {

          System.out.println(kind.name() + " for path/directory " + directory);
          //  System.out.println("suffix length er "+suffix[1]);
          System.out.println(kind.name() + " for path/directory " + directory);
          // System.out.println("filnavn er" + filename);
          String suffix[] = (directory.toString()).split("\\.");
          if ((suffix.length > 1) && (suffix[1].endsWith("evt"))) {
            System.out.println("Laget fil.");
            String adress =
                (directory.getParent().toAbsolutePath() + "/" + directoryName + "/" + filename);
            convertToSimpleEvent(adress);

          } else if (Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) {
            directoryName = filename;
            registerAll(directory);
            //   System.out.println("Laget fil og venter i 6 sec.");
            Thread.sleep(6000);
            // traverseDirectories(directory.toString());
            //  System.out.println("Ny mappe er laget på lokajson."+directory);
          }

        } else if (kind == ENTRY_DELETE) {

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

      boolean valid = key.reset();
      if (!valid) {
        System.out.println("ble ikke valid " + valid);
        keys.remove(key);

        // all directories are inaccessible
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }
Beispiel #4
0
  /** Process all events for keys queued to the watcher. */
  public void processEvents() {
    for (; ; ) {

      // wait for key to be signaled
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        x.printStackTrace();
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        System.err.println("WatchKey not recognized!!");
        continue;
      }

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

        // TBD - provide example of how OVERFLOW event is handled
        if (kind == OVERFLOW) {
          continue;
        }

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

        // print out event
        System.err.format("%s %s: %s\n", NAME, event.kind().name(), child);
        // determine file type
        boolean isDir = FSML.isDirectory(child);
        // [MS] replace with this:
        // Files.isDirectory(child, NOFOLLOW_LINKS);
        if (kind == ENTRY_MODIFY) {
          modifyEvent(child, isDir);
        }

        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (recursive && (kind == ENTRY_CREATE)) {
          try {
            if (isDir) {
              registerAll(child);
            }
          } catch (IOException x) {
            x.printStackTrace();
          }
        }
      }

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

        // all directories are inaccessible
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }