/**
  * 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");
 }
Beispiel #2
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();
    }
  }
Beispiel #3
0
  /** Check that a cancelled key will never be queued */
  static void testCancel(Path dir) throws IOException {
    System.out.println("-- Cancel --");

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

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

      System.out.println("cancel key");
      myKey.cancel();

      // create a file in the directory
      Path file = dir.resolve("mars");
      System.out.format("create: %s\n", file);
      Files.createFile(file);

      // poll for keys - there will be none
      System.out.println("poll...");
      try {
        WatchKey key = watcher.poll(3000, TimeUnit.MILLISECONDS);
        if (key != null) throw new RuntimeException("key should not be queued");
      } catch (InterruptedException x) {
        throw new RuntimeException(x);
      }

      // done
      Files.delete(file);

      System.out.println("OKAY");
    }
  }
Beispiel #4
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 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());
      }
    }
  }
  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);
  }
Beispiel #7
0
  private static void handleDirectoryChangeEvent(String path) {
    try {
      System.out.println("sss");
      Path dir = Paths.get(path);
      WatchService watchService = FileSystems.getDefault().newWatchService();
      dir.register(
          watchService,
          StandardWatchEventKinds.ENTRY_CREATE,
          StandardWatchEventKinds.ENTRY_MODIFY,
          StandardWatchEventKinds.ENTRY_DELETE);
      WatchKey watchKey = watchService.take();
      for (WatchEvent<?> event : watchKey.pollEvents()) {
        final WatchEvent<Path> ev = (WatchEvent<Path>) event;
        final Path name = ev.context();
        final Path child = dir.resolve(name);
        final Kind<?> kind = event.kind();
        // event 처리

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

        if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
          // final Path directory_path = director
          // System.out.println("Created: " + object.context().toString());
          // System.out.println("Created: " +  ((Path) event).toRealPath(true)+"/"+ ((WatchEvent<?>)
          // kind).context().toString());
        }

        System.out.format("%s: %s\n", event.kind().name(), child);
      }
    } catch (Exception x) {
      return;
    }
  }
Beispiel #8
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);
    }
  public static void main(String[] args) throws Exception {
    final Path path = Paths.get(".");
    final WatchService watchService = path.getFileSystem().newWatchService();
    path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
    System.out.println("Report any file changed within next 1 minute...");

    final WatchKey watchKey = watchService.poll(1, TimeUnit.MINUTES);
    if (watchKey != null) {
      watchKey.pollEvents().stream().forEach(event -> System.out.println(event.context()));
    }
  }
Beispiel #11
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 synchronized void unwatchPath(File file, final FileChangeCallback callback) {
   PathData data = files.get(file);
   if (data != null) {
     data.callbacks.remove(callback);
     if (data.callbacks.isEmpty()) {
       files.remove(file);
       for (WatchKey key : data.keys) {
         key.cancel();
         pathDataByKey.remove(key);
       }
     }
   }
 }
  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);
    }
  }
Beispiel #15
0
 public void blockOnFileDeletion(String filename) throws IOException {
   if (!new File(filename).exists()) return;
   System.out.println("Waiting for file " + filename + " to be deleted");
   WatchService watchService = FileSystems.getDefault().newWatchService();
   Path parent = Paths.get(filename).getParent();
   WatchKey watchKey = parent.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);
   try {
     WatchKey key = watchService.take();
     for (WatchEvent<?> event : key.pollEvents()) {
       if (filename.endsWith(event.context().toString())) return;
     }
   } catch (InterruptedException e) {
   }
   return;
 }
Beispiel #16
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;
      }
    }
  }
Beispiel #17
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();
    }
  }
Beispiel #20
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);
  }
Beispiel #21
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.");
      }
    }
  }
Beispiel #22
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.
   }
 }
Beispiel #23
0
 private void rescan() throws IOException {
   try {
     synchronized (processing) {
       while (processing.get() > 0) {
         processing.wait();
       }
     }
     for (WatchKey key : keys.keySet()) {
       key.cancel();
     }
     keys.clear();
     Files.walkFileTree(root, new FilteringFileVisitor());
     synchronized (processing) {
       while (processing.get() > 0) {
         processing.wait();
       }
     }
   } catch (InterruptedException e) {
     throw (IOException) new InterruptedIOException().initCause(e);
   }
 }
    @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;
      }
    }
Beispiel #25
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());
   }
 }
  /** 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();
  }
Beispiel #27
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");
    }
  }
Beispiel #28
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;
        }
      }
    }
  }
Beispiel #29
0
  public void downloadFile(String relPath) {
    VOSync.debug("Downloading file from storage: " + relPath);
    Path filePath = FileSystems.getDefault().getPath(startDir.toString(), relPath.substring(1));
    try {
      WatchKey key =
          filePath.getParent().register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.remove(key);
      key.cancel();

      FileOutputStream outp = new FileOutputStream(filePath.toFile());
      DropboxFileInfo info = api.getFile(relPath, null, outp, null);
      outp.close();

      key = filePath.getParent().register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.put(key, filePath.getParent());

      MetaHandler.setFile(relPath, filePath.toFile(), info.getMetadata().rev);
    } catch (IOException ex) {
      logger.error("Error downloading file " + relPath + ": " + ex.getMessage());
    } catch (DropboxException ex) {
      ex.printStackTrace();
      logger.error("Error downloading file " + relPath + ": " + ex.getMessage());
    }
  }
 /** @return */
 @ManagedAttribute
 public boolean isWatchKeyValid() {
   if (watchKey == null) return false;
   return watchKey.isValid();
 }