public void run() {
    if (watchService == null || watchKey == null) {
      return;
    }

    if (DEBUG_LOG_TO_CONSOLE) {
      System.out.println("" + Thread.currentThread().getId() + " Started run method");
    }

    try {
      do {
        WatchKey watchKey = watchService.take();
        List<WatchEvent<?>> events = watchKey.pollEvents();
        if (events != null && events.size() > 0) {
          if (DEBUG_LOG_TO_CONSOLE) {
            System.out.println("" + Thread.currentThread().getId() + " Received change event");
          }

          // fire listener
          listener.onDirectoryChanged(directory);
        }
      } while (watchKey.reset());

    } catch (Throwable e) {
      // terminating
      if (DEBUG_LOG_TO_CONSOLE) {
        System.out.println("" + Thread.currentThread().getId() + " Exception: " + e.toString());
      }
    }
  }
Example #2
0
  /** Process all events for keys queued to the watcher */
  void processEvents() {
    while (true) {

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

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

      List<WatchEvent<?>> events = key.pollEvents();

      for (WatchEvent<?> event : events) {
        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
        onEvent.accept(ev, child);

        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (recursive && (kind == ENTRY_CREATE)) {
          try {
            if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
              registerAll(child);
            }
          } catch (IOException x) {
            // ignore to keep sample readbale
          }
        }
      }

      // 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;
        }
      }
    }
  }
  public void startTimer() throws IOException, InterruptedException {
    Path faxFolder = Paths.get("./plugins");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

    boolean valid = true;
    do {
      WatchKey watchKey = watchService.take();

      for (WatchEvent event : watchKey.pollEvents()) {
        WatchEvent.Kind kind = event.kind();
        if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
          String fileName = event.context().toString();
          System.out.println("Trying to add " + fileName);
          boolean success = this.server.addPlugin(fileName);
          System.out.println(
              success
                  ? "Added " + fileName + "!"
                  : fileName + " was not loaded, JAR was misformed.");
        }
        if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
          String fileName = event.context().toString();
          System.out.println("File Removed: " + fileName);
          this.server.removePlugin(fileName);
        }
      }

      valid = watchKey.reset();

    } while (valid);
  }
Example #4
0
 /**
  * In order to implement a file watcher, we loop forever ensuring requesting to take the next
  * item from the file watchers queue.
  */
 @Override
 public void run() {
   try {
     // get the first event before looping
     WatchKey key = myWatcher.take();
     while (key != null) {
       // we have a polled event, now we traverse it and
       // receive all the states from it
       for (WatchEvent event : key.pollEvents()) {
         System.out.printf(
             "Received %s event for file: %s\n",
             event.kind(), pathToWatch + "/" + event.context());
         uploadToS3.upload(
             "bulk-delivery",
             event.context().toString(),
             pathToWatch + "/" + event.context().toString());
       }
       key.reset();
       key = myWatcher.take();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   System.out.println("Stopping thread");
 }
Example #5
0
  private void refresh() throws IOException {
    while (true) {
      WatchKey watchKey = watchService.poll();
      if (watchKey == null) {
        return;
      }

      Path parentDir = (Path) watchKey.watchable();

      for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
        WatchEvent.Kind<?> eventKind = watchEvent.kind();
        if (eventKind == OVERFLOW) {
          fullRefresh();
          return;
        }

        Path child = parentDir.resolve((Path) watchEvent.context());
        if (eventKind == ENTRY_CREATE) {
          onNewPath(child);
        } else if (eventKind == ENTRY_DELETE) {
          onRemovedPath(child);
        }
      }

      watchKey.reset();
    }
  }
Example #6
0
  public static void watchDirectoryPath(Path path) {
    // Sanity check - Check if path is a folder
    try {
      Boolean isFolder = (Boolean) Files.getAttribute(path, "basic:isDirectory", NOFOLLOW_LINKS);
      if (!isFolder) {
        throw new IllegalArgumentException("Path: " + path + " is not a folder");
      }
    } catch (IOException ioe) {
      // Folder does not exists
      ioe.printStackTrace();
    }

    // System.out.println("Watching path: " + path);

    // We obtain the file system of the Path
    FileSystem fs = path.getFileSystem();

    // We create the new WatchService using the new try() block
    try (WatchService service = fs.newWatchService()) {

      // We register the path to the service
      // We watch for creation events
      path.register(service, ENTRY_CREATE);

      // Start the infinite polling loop
      WatchKey key = null;
      while (true) {
        key = service.take();

        // Dequeueing events
        Kind<?> kind = null;
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
          // Get the type of the event
          kind = watchEvent.kind();
          if (OVERFLOW == kind) {
            continue; // loop
          } else if (ENTRY_CREATE == kind) {
            // A new Path was created
            // Path newPath = ((WatchEvent<Path>)
            // watchEvent).context();
            // Output
            // System.out.println("New path created: " + newPath);
          }
        }

        if (!key.reset()) {
          break; // loop
        }
      }

    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (InterruptedException ie) {
      ie.printStackTrace();
    }
  }
    public void run() {
      log.debug("ReloadStrategy is starting watching folder: {}", folder);

      // allow to run while starting Camel
      while (isStarting() || isRunAllowed()) {
        running = true;

        WatchKey key;
        try {
          log.trace("ReloadStrategy is polling for file changes in directory: {}", folder);
          // wait for a key to be available
          key = watcher.poll(2, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
          break;
        }

        if (key != null) {
          for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent<Path> we = (WatchEvent<Path>) event;
            Path path = we.context();
            String name = folder.resolve(path).toAbsolutePath().toFile().getAbsolutePath();
            log.trace("Modified/Created file: {}", name);

            // must be an .xml file
            if (name.toLowerCase(Locale.US).endsWith(".xml")) {
              log.debug("Modified/Created XML file: {}", name);
              try {
                FileInputStream fis = new FileInputStream(name);
                onReloadXml(getCamelContext(), name, fis);
                IOHelper.close(fis);
              } catch (Exception e) {
                log.warn(
                    "Error reloading routes from file: "
                        + name
                        + " due "
                        + e.getMessage()
                        + ". This exception is ignored.",
                    e);
              }
            }
          }

          // the key must be reset after processed
          boolean valid = key.reset();
          if (!valid) {
            break;
          }
        }
      }

      running = false;

      log.info("ReloadStrategy is stopping watching folder: {}", folder);
    }
Example #8
0
  private boolean processWatchKey(WatchKey watchKey) {
    for (WatchEvent<?> event : watchKey.pollEvents()) {
      if (StandardWatchEventKinds.OVERFLOW == event.kind()) continue;
      try {
        session.getBasicRemote().sendObject(((Path) event.context()).toFile());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return watchKey.reset();
  }
  /**
   * Process all events for keys queued to the watcher.
   *
   * <p>When the event is a ENTRY_CREATE or ENTRY_MODIFY, the folders will be added to the watcher,
   * the classes will be loaded by SpringLoaded
   */
  public void run() {
    while (isStarted) {
      // wait for key to be signalled
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

      Path dir = keys.get(key);
      if (dir == null) {
        continue;
      }

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

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

        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
          watchDirectory(child);
          // load the classes that have been copied
          final File[] classes =
              child.toFile().listFiles((FileFilter) new SuffixFileFilter(".class"));
          for (File aFile : classes) {
            final String parentFolder = aFile.getParent();
            callFileWatcherListerners(parentFolder, aFile.toPath(), kind);
          }
        } else {
          callFileWatcherListerners(dir.toString().replace(File.separator, "/"), child, kind);
        }
      }

      // 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;
        }
      }
    }
  }
  public static void main(String[] args) {
    try {
      WatchService watcher = FileSystems.getDefault().newWatchService();
      Path dir = Paths.get("D:\\take it");
      dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);

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

      System.out.println("How many files are already there " + folder.getAbsolutePath());
      listFilesForFolder(folder);

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

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

          @SuppressWarnings("unchecked")
          WatchEvent<Path> ev = (WatchEvent<Path>) event;
          Path fileName = ev.context();
          // String p = folder.getAbsolutePath()+ "\\" +fileName;
          if ((fileName.toString()).contains(".")) {
            System.out.println("snadkf");
          } else {
            System.out.println(kind.name() + ": " + fileName);
          }
          // System.out.println("New file has been arrived: "+fileName);

        }

        /*if (kind == ENTRY_MODIFY && fileName.toString().equals("DirectoryWatchDemo.java"))
        {
                           System.out.println("My source file has changed!!!");
                       }
                   }*/

        boolean valid = key.reset();
        if (!valid) {
          break;
        }
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
Example #11
0
  /** Process all events for the key queued to the watcher. */
  void processEvents() {
    for (; ; ) {

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

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

        if (kind == OVERFLOW) {
          continue;
        }

        // The filename is the context of the event.
        WatchEvent<Path> ev = (WatchEvent<Path>) event;
        Path filename = ev.context();

        // Verify that the new file is a text file.
        try {
          Path child = dir.resolve(filename);
          if (!Files.probeContentType(child).equals("text/plain")) {
            System.err.format("New file '%s' is not a plain text file.%n", filename);
            continue;
          }
        } catch (IOException x) {
          System.err.println(x);
          continue;
        }

        // Email the file to the specified email alias.
        System.out.format("Emailing file %s%n", filename);
      }

      // Reset the key -- this step is critical if you want to receive
      // further watch events. If the key is no longer valid, the directory
      // is inaccessible so exit the loop.
      boolean valid = key.reset();
      if (!valid) {
        break;
      }
    }
  }
Example #12
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;
        }
      }
    }
  }
  @Override
  public void run() {
    try {
      WatchService service = FileSystems.getDefault().newWatchService();
      Path path = Paths.get(Settings.AVAILABLE_USERS_PATH);
      path.register(service, StandardWatchEventKinds.ENTRY_MODIFY);

      while (true) {
        // wait until a directory change is detected
        WatchKey key = service.take();

        // remove all pending directory change events
        key.pollEvents();

        // get an up-to-date list of the currently available users
        Set<String> availableUsers = getAvailableUsers();

        // has anyone just come online?
        Set<String> logOns = new HashSet<String>(availableUsers);
        logOns.removeAll(users);

        // has anyone just gone offline?
        Set<String> logOffs = new HashSet<String>(users);
        logOffs.removeAll(availableUsers);

        // update the list of available users
        users = availableUsers;

        // notify the delegate of the changes
        delegate.change(logOns, logOffs);

        boolean valid = key.reset();
        if (!valid) {
          break; // Exit if directory is deleted
        }
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private void initWatcher() throws IOException, InterruptedException {
    WatchService watcher = path.getFileSystem().newWatchService();
    path.register(
        watcher,
        StandardWatchEventKinds.ENTRY_CREATE,
        StandardWatchEventKinds.ENTRY_MODIFY,
        StandardWatchEventKinds.ENTRY_DELETE);

    LOG.info("Now watching template folder: " + path.toFile().getAbsolutePath());

    while (true) {
      WatchKey key = watcher.take();
      List<WatchEvent<?>> events = key.pollEvents();
      if (!events.isEmpty()) {
        updateTemplates();
      }
      key.reset();
    }
  }
Example #15
0
  /**
   * @param args
   * @throws IOException
   * @throws InterruptedException
   */
  public static void main(String[] args) throws IOException, InterruptedException {

    final String dir = "C:\\work\\docs\\PHD_Work\\thesis\\";

    File folder = new File(dir);
    File[] listOfFiles = folder.listFiles();

    for (int i = 0; i < listOfFiles.length; i++) {

      if (listOfFiles[i].isFile()) {
        String file = listOfFiles[i].getName();

        if (file.endsWith(".tex")) {
          latexToHTML(dir + file);
        }
      }
    }

    // define a folder root
    Path myDir = Paths.get(dir);
    WatchService watcher = myDir.getFileSystem().newWatchService();
    myDir.register(watcher, ENTRY_MODIFY);

    do {

      WatchKey watckKey = watcher.poll();

      if (watckKey != null) {
        List<WatchEvent<?>> events = watckKey.pollEvents();
        for (WatchEvent event : events) {
          String filename = event.context().toString();
          if (filename.endsWith(".tex")) {
            latexToHTML(dir + filename);
          }
        }

        watckKey.reset();
      }
      Thread.sleep(500);

    } while (true);
  }
Example #16
0
  public static void watchDirectoryPath(Path path) {
    if (path != null) {

      System.out.println("Watching path: " + path);

      FileSystem fs = path.getFileSystem();

      try (WatchService service = fs.newWatchService()) {

        path.register(service, ENTRY_CREATE);

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

          // Dequeueing events
          Kind<?> kind;
          for (WatchEvent<?> watchEvent : key.pollEvents()) {
            // Get the type of the event
            kind = watchEvent.kind();
            if (OVERFLOW == kind) {
              continue; // loop
            } else if (ENTRY_CREATE == kind) {
              // A new Path was created
              Path newPath = ((WatchEvent<Path>) watchEvent).context();
              // Output
              System.out.println("New path created/modified: " + newPath);
              checkPath(newPath.toString());
            }
          }

          if (!key.reset()) {
            break; // resets the key so it continues to look for new creation events.
          }
        }

      } catch (IOException | InterruptedException ioe) {
        System.out.println("The file watcher was interrupted.");
      }
    }
  }
Example #17
0
 public static void watchService() {
   try {
     WatchService watcher = FileSystems.getDefault().newWatchService();
     WatchKey watchKey =
         Paths.get("/Users/caocao024/Desktop")
             .register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
     while (true) {
       // watchKey = watcher.take();
       for (WatchEvent<?> event : watcher.poll(10, TimeUnit.MILLISECONDS).pollEvents()) {
         if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
           System.out.println("====" + event.context() + " | " + event.count());
         }
       }
       watchKey.reset();
     }
   } catch (IOException | InterruptedException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
 }
    @Override
    public void run() {
      try {
        for (; ; ) {
          WatchKey key = null;
          try {
            key = watchService.take();
          } catch (InterruptedException e) {
            return;
          }

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

            if (kind == OVERFLOW) {
              continue;
            }

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

            // print out event
            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
              try {
                processConfigFile(
                    new File(getServiceConfigFolder() + File.separator + name.toString()));
              } catch (IOException e) {
                logger.warn("Could not process config file '{}': {}", name, e);
              }
            }
          }
          key.reset();
        }
      } catch (ClosedWatchServiceException ecx) {
        logger.debug("Terminated thread {}", Thread.currentThread().getName());
        return;
      }
    }
  /** Creates a WatchService and registers the given directory */
  private void setupWatch(String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("jshelltemp");
    this.tmpfile = Files.createTempFile(dir, null, ".edit");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    watchedThread =
        new Thread(
            () -> {
              for (; ; ) {
                WatchKey key;
                try {
                  key = watcher.take();
                } catch (ClosedWatchServiceException ex) {
                  // The watch service has been closed, we are done
                  break;
                } catch (InterruptedException ex) {
                  // tolerate an interrupt
                  continue;
                }

                if (!key.pollEvents().isEmpty()) {
                  // Changes have occurred in temp edit directory,
                  // transfer the new sources to JShell (unless the editor is
                  // running directly in JShell's window -- don't make a mess)
                  if (!input.terminalEditorRunning()) {
                    saveFile();
                  }
                }

                boolean valid = key.reset();
                if (!valid) {
                  // The watch service has been closed, we are done
                  break;
                }
              }
            });
    watchedThread.start();
  }
Example #20
0
 /** 监听目录 */
 @Test
 public void testWatchFile() {
   // 监听目录变化
   try {
     WatchService watcher = FileSystems.getDefault().newWatchService();
     Path dir = FileSystems.getDefault().getPath(ParentPath);
     WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
     boolean shutdown = false;
     while (!shutdown) {
       System.out.println(1);
       key = watcher.take();
       for (WatchEvent<?> event : key.pollEvents()) {
         if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
           System.out.println("Home dir changed!");
         }
       }
       key.reset();
     }
   } catch (IOException | InterruptedException e) {
     System.out.println(e.getMessage());
   }
 }
Example #21
0
  /** Check that deleting a registered directory causes the key to be cancelled and queued. */
  static void testAutomaticCancel(Path dir) throws IOException {
    System.out.println("-- Automatic Cancel --");

    Path subdir = Files.createDirectory(dir.resolve("bar"));

    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {

      System.out.format("register %s for events\n", subdir);
      WatchKey myKey =
          subdir.register(
              watcher, new WatchEvent.Kind<?>[] {ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY});

      System.out.format("delete: %s\n", subdir);
      Files.delete(subdir);
      takeExpectedKey(watcher, myKey);

      System.out.println("reset key");
      if (myKey.reset()) throw new RuntimeException("Key was not cancelled");
      if (myKey.isValid()) throw new RuntimeException("Key is still valid");

      System.out.println("OKAY");
    }
  }
Example #22
0
  private void watchLoop() throws IOException {

    WatchService watcher = FileSystems.getDefault().newWatchService();
    toWatch_.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

    while (running_) {

      // wait for key to be signaled
      WatchKey key;
      try {

        key = watcher.take();

      } catch (InterruptedException x) {
        return;
      }

      if (key != null) {
        for (WatchEvent<?> event : key.pollEvents()) {

          if (!running_) {
            return;
          }
          System.out.println("Processing event...");
          processEvent(event);
        }

        // Reset the key -- this step is critical if you want to
        // receive further watch events. If the key is no longer valid,
        // the directory is inaccessible so exit the loop.
        boolean valid = key.reset();
        if (!valid) {
          break;
        }
      }
    }
  }
Example #23
0
  public void watchForNewEdges() {
    // File file = new File("C:\\Users\\rvanduijnhoven\\Documents\\jsfoutput\\jsfweek14.bin");

    // Get the file system
    // FileSystem fs = path.getFileSystem();

    // Create the watchservice
    try {
      Path path = Paths.get("C:/Users/rvanduijnhoven/Documents/jsfoutput/");
      WatchService service = FileSystems.getDefault().newWatchService();
      path.register(service, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      WatchKey key;
      while (true) {
        key = service.take();
        for (WatchEvent<?> event : key.pollEvents()) {
          // Code here that does something when new edges have been generated
          System.out.println(event.context().toString());
          WatchEvent<Path> ev = (WatchEvent<Path>) event;
          WatchEvent.Kind kind = ev.kind();

          if (kind == OVERFLOW) {
            continue; // just to demonstrate
          }

          Path changed = ev.context();
          Path child = path.resolve(changed);
          if (changed.toString().equals("jsfweek14.bin")) {

            clearKochPanel();
            File file = new File("C:\\Users\\rvanduijnhoven\\Documents\\jsfoutput\\jsfweek14.bin");
            FileChannel fileChannel = null;
            MappedByteBuffer map = null;
            int counter = 0;
            // Now read every edge from the file and draw it.
            try {
              fileChannel = new RandomAccessFile(file, "r").getChannel();
              map = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, 4096 * 128 * 128);
              double d = map.getDouble();
              currentLevel = (int) d;
              counter = (int) (3 * Math.pow(4, currentLevel - 1));
              for (int i = 0; i <= counter; i++) {
                double X1 = map.getDouble();
                double Y1 = map.getDouble();
                double X2 = map.getDouble();
                double Y2 = map.getDouble();
                double red = map.getDouble();
                double green = map.getDouble();
                double blue = map.getDouble();
                Edge e = new Edge(X1, Y1, X2, Y2, new Color(red, green, blue, 1));
                drawEdge(e);
              }
              key.reset();

            } catch (Exception ex) {
              ex.printStackTrace();
            } finally {
              fileChannel.close();
              map.clear();
            }
          }
          key.reset();
        }
      }

    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (Exception ie) {
      ie.printStackTrace();
    }
  }
Example #24
0
  @Override
  public void run() {
    while (running) {
      try {
        WatchKey key = watcher.take();
        sleep(100);
        for (WatchEvent<?> event : key.pollEvents()) {
          Kind<?> kind = event.kind();
          String dateiname = event.context().toString();
          int linie;
          LineReader lr;
          switch (kind.name()) {
            case "ENTRY_CREATE":
              // HTreff<X>PN<Y>.ctl
              // HTreff<X>PN<Y>.nrt
              // HTreff<X>MN<Y>.ctl
              // HTreff<X>MN<Y>.nrt
              if (!dateiname.startsWith("HTreff")) break;

              int endIndex = dateiname.indexOf('N') - 1;
              linie = Integer.parseUnsignedInt(dateiname.substring(6, endIndex));
              lr = getLineReaderByNumber(linie);
              if (lr != null) {
                File datei = new File(dateiname);
                if (dateiname.endsWith(".ctl")) {
                  FileInputStream reader = null;
                  try {
                    reader = new FileInputStream(dateiname);
                    List<String> lines = IOUtils.readLines(reader, Charset.forName("UTF-8"));
                    if (lines.size() > 0) lr.addTreffer(new Hit(lines.get(0)));
                  } catch (IOException e) {
                    e.printStackTrace();
                  } finally {
                    if (reader != null) IOUtils.closeQuietly(reader);
                  }
                }
                if (!datei.delete()) {
                  System.out.println(dateiname + " konnte nicht gelöscht werden.");
                }
              }
              break;
            case "ENTRY_DELETE":
              // HServ<X>.ctl
              if (dateiname.startsWith("HServ") && dateiname.endsWith(".ctl")) {
                linie = Integer.parseUnsignedInt(dateiname.substring(5, dateiname.length() - 4));
                lr = getLineReaderByNumber(linie);
                if (lr != null) lr.reenable();
              }
              break;
            default: // OVERFLOW
              continue;
          }
        }
        key.reset();
      } catch (InterruptedException | ClosedWatchServiceException e) {
        if (running) {
          e.printStackTrace();
        }
      }
    }
  }
  @Override
  public void run() {
    while (!stopped) {
      try {
        final WatchKey key = watchService.take();
        if (key != null) {
          try {
            PathData pathData = pathDataByKey.get(key);
            if (pathData != null) {
              List<WatchEvent<?>> events = new ArrayList<>(key.pollEvents());
              final List<FileChangeEvent> results = new ArrayList<>();
              List<WatchEvent<?>> latest;
              do {
                // we need to wait till nothing has changed in 500ms to make sure we have picked up
                // all the changes
                Thread.sleep(WAIT_TIME);
                latest = key.pollEvents();
                events.addAll(latest);
              } while (!latest.isEmpty());
              final Set<File> addedFiles = new HashSet<>();
              final Set<File> deletedFiles = new HashSet<>();
              for (WatchEvent<?> event : events) {
                Path eventPath = (Path) event.context();
                File targetFile = ((Path) key.watchable()).resolve(eventPath).toFile();
                FileChangeEvent.Type type;

                if (event.kind() == ENTRY_CREATE) {
                  type = FileChangeEvent.Type.ADDED;
                  addedFiles.add(targetFile);
                  if (targetFile.isDirectory()) {
                    try {
                      addWatchedDirectory(pathData, targetFile);
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                } else if (event.kind() == ENTRY_MODIFY) {
                  type = FileChangeEvent.Type.MODIFIED;
                } else if (event.kind() == ENTRY_DELETE) {
                  type = FileChangeEvent.Type.REMOVED;
                  deletedFiles.add(targetFile);
                } else {
                  continue;
                }
                results.add(new FileChangeEvent(targetFile, type));
              }
              key.pollEvents().clear();

              // now we need to prune the results, to remove duplicates
              // e.g. if the file is modified after creation we only want to
              // show the create event
              final List<FileChangeEvent> newEvents = new ArrayList<>();
              Iterator<FileChangeEvent> it = results.iterator();
              while (it.hasNext()) {
                FileChangeEvent event = it.next();
                boolean added = addedFiles.contains(event.getFile());
                boolean deleted = deletedFiles.contains(event.getFile());
                if (event.getType() == FileChangeEvent.Type.MODIFIED) {
                  if (added || deleted) {
                    it.remove();
                  }
                } else if (event.getType() == FileChangeEvent.Type.ADDED) {
                  if (deleted) {
                    it.remove();
                    newEvents.add(
                        new FileChangeEvent(
                            event.getFile(),
                            FileChangeEvent.Type
                                .MODIFIED)); // if it was both deleted and added it was modified
                  }
                } else if (event.getType() == FileChangeEvent.Type.REMOVED) {
                  if (added) {
                    it.remove();
                  }
                }
              }
              results.addAll(newEvents);

              if (!results.isEmpty()) {
                for (FileChangeCallback callback : pathData.callbacks) {
                  invokeCallback(callback, results);
                }
              }
            }
          } finally {
            // if the key is no longer valid remove it from the files list
            if (!key.reset()) {
              files.remove(key.watchable());
            }
          }
        }
      } catch (InterruptedException e) {
        // ignore
      } catch (ClosedWatchServiceException cwse) {
        // the watcher service is closed, so no more waiting on events
        // @see https://developer.jboss.org/message/911519
        break;
      }
    }
  }
Example #26
0
  private void processEvents() {
    while (true) {
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException e) {
        return;
      }
      Path dir = keys.get(key);
      if (dir == null) {
        LOGGER.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);

        LOGGER.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) {
        LOGGER.debug("Removing key " + key + " and dir " + dir + " from keys");
        keys.remove(key);

        // all directories are inaccessible
        if (keys.isEmpty()) {
          break;
        }
      }
    }
  }
Example #27
0
  // void processEvents() {
  public void run() {
    System.out.println("WatchDir Thread INFO: priority=" + Thread.currentThread().getPriority());
    for (; ; ) {
      // wait for key to be signalled
      System.out.println("WatchDir INFO: restarting loop...acquiring new key");
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        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) {
          System.out.println("Encountered OVERFLOW Event - " + event);
          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.out.format("[WatchDir] %s: %s\n", event.kind().name(), child);

        // if directory is created, and watching recursively, then
        // register it and its sub-directories
        if (recursive && (kind == ENTRY_CREATE)) {
          try {
            if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
              registerAll(child);
            }
          } catch (IOException x) {
            // ignore to keep sample readbale
          }
        }

        long t = System.currentTimeMillis();
        if (!Folder.dontWatch.contains(Folder.getInternalPath(child))) {
          Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
          System.out.println(
              "WatchDir#"
                  + key
                  + " INFO: path="
                  + child
                  + ", internal="
                  + Folder.getInternalPath(child)
                  + " is NOT in don't watch list. Forwarding it to other peers. @"
                  + Main.timeToString(t)); // DEBUG
          forwardToItopic(kind, child);
        } else {
          Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
          System.out.println(
              "WatchDir#"
                  + key
                  + " INFO: path="
                  + child
                  + ", internal="
                  + Folder.getInternalPath(child)
                  + " IS in the don't watch list. NOT forwarding. @"
                  + Main.timeToString(t)); // DEBUG
          // try{
          //     Thread.sleep(minDelayBtwnWatchEvents);
          // } catch(InterruptedException ex) {
          //     System.err.println("Exception:"+ex+" while trying to sleep WatchDir thread");
          //     ex.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;
        }
      }
    }
  }
Example #28
0
  @Override
  public void run() {
    logger.debug("Register root " + startDir.toString());

    try {
      registerAll(startDir);
    } catch (IOException ex) {
      logger.error(ex.getMessage());
      return;
    }

    if (isInterrupted()) return;

    VOSync.debug("Sync local db with drive");

    DbPool.goSql(
        "Synching the local db with drive",
        "select NAME from FILES",
        new SqlWorker<Boolean>() {
          @Override
          public Boolean go(Connection conn, PreparedStatement stmt) throws SQLException {
            ResultSet resSet = stmt.executeQuery();
            while (resSet.next()) {
              try {
                String fileName = resSet.getString(1);
                Path filePath =
                    FileSystems.getDefault().getPath(startDir.toString(), fileName.substring(1));
                if (!filePath.toFile().exists()) {
                  logger.debug(
                      "Deleting file " + fileName + " existing in DB and not present on disk");
                  api.delete(fileName);
                  MetaHandler.delete(fileName);
                }
              } catch (DropboxException ex) {
              }
            }
            resSet.close();
            return true;
          }
        });

    if (isInterrupted()) return;

    VOSync.debug("Sync storage");

    syncStorage();

    logger.debug("Start watching");

    while (!isInterrupted()) {
      WatchKey key;
      try {
        key = watcher.take();
      } catch (InterruptedException x) {
        return;
      }

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

      for (WatchEvent<?> event : key.pollEvents()) {
        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);
        Path relativeDir = startDir.relativize(child);
        String fileRelPath = "/" + fixPath(relativeDir.toString());

        // print out event
        logger.debug(event.kind().name() + ":" + child + " " + name + " " + key);

        try {
          if (Files.exists(child, new LinkOption[] {}) && Files.isHidden(child)) {
            logger.error(
                "Skipping hidden file " + child.getFileName()); // skip OS generated catalog files
          } else {
            if (event.kind() == ENTRY_CREATE) {
              if (Files.isRegularFile(child, NOFOLLOW_LINKS)) { // file modified
                uploadFile(fileRelPath, child);
              } else if (Files.isDirectory(child, NOFOLLOW_LINKS)) { // directory contents changed
                registerAll(child);
              }
            } else if (event.kind() == ENTRY_DELETE) {
              logger.debug("Deleting " + fileRelPath);
              api.delete(fileRelPath);
              MetaHandler.delete(fileRelPath);
              logger.debug("Deleted!");
            } else if (event.kind() == ENTRY_MODIFY) {
              if (Files.isRegularFile(child, NOFOLLOW_LINKS)) { // file modified
                uploadFile(fileRelPath, child);
              } else if (Files.isDirectory(child, NOFOLLOW_LINKS)) { // directory contents changed
                // logger.debug("Renewing dir: "+relativeDir.toString());
                // TODO update folder date
                // MetaHandler.setFile(fileRelPath, child, rev);
              }
            }
          }
        } catch (IOException ex) {
          ex.printStackTrace();
          logger.error(ex.getMessage());
        } catch (DropboxException ex) {
          ex.printStackTrace();
          logger.error(ex.getMessage());
        }
      }

      boolean valid = key.reset();

      if (!valid) keys.remove(key);
    }
  }
    /**
     * In order to implement a file watcher, we loop forever ensuring requesting to take the next
     * item from the file watchers queue.
     */
    @Override
    public void run() {

      final Path path = Paths.get(spath);
      try {
        // We wait until the file we are told to monitor exists.
        while (!Files.exists(path)) {
          Thread.sleep(200);
        }

        // get the first event before looping
        WatchKey key = null;
        while (session.isOpen() && connected && (key = watcher.take()) != null) {

          try {
            if (!Files.exists(path)) continue;

            for (WatchEvent<?> event : key.pollEvents()) {

              if (!Files.exists(path)) continue;

              Path epath = (Path) event.context();
              if (!Files.isDirectory(path) && !path.endsWith(epath)) continue;

              try {
                // Data has changed, read its shape and publish the event using a web socket.
                final IDataHolder holder =
                    ServiceHolder.getLoaderService().getData(spath, new IMonitor.Stub());
                if (holder == null) continue; // We do not stop if the loader got nothing.

                final ILazyDataset lz =
                    sdataset != null && !"".equals(sdataset)
                        ? holder.getLazyDataset(sdataset)
                        : holder.getLazyDataset(0);
                if (lz == null) continue; // We do not stop if the loader got nothing.

                if (lz instanceof IDynamicDataset) {
                  ((IDynamicDataset) lz).refreshShape();
                }

                if (writing) {
                  ServiceHolder.getLoaderService().clearSoftReferenceCache(spath);
                }
                final DataEvent evt = new DataEvent(lz.getName(), lz.getShape());
                evt.setFilePath(spath);

                // We manually JSON the object because we
                // do not want a dependency and object simple
                String json = evt.encode();
                session.getRemote().sendString(json);
                if (diagInfo != null) diagInfo.record("JSON Send", json);

              } catch (HDF5FunctionArgumentException h5error) {
                // This happens sometimes when the file is not ready to read.
                logger.trace("Path might not be ready to read " + path);
                continue;

              } catch (Exception ne) {
                logger.error("Exception getting data from " + path);
                continue;
              }
              break;
            }

          } finally {
            key.reset();
          }
        }

      } catch (Exception e) {
        logger.error("Exception monitoring " + path, e);
        if (session.isOpen()) session.close(403, e.getMessage());

      } finally {
        if (diagInfo != null) diagInfo.record("Close Thread", Thread.currentThread().getName());
        try {
          watcher.close();
        } catch (IOException e) {
          logger.error("Error closing watcher", e);
        }
      }
    }
  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;
        }
      }
    }
  }