Package java.nio.file

Examples of java.nio.file.WatchKey


    /**
     * Register a single directory with the WatchService
     */
    private void register(Path dir) throws IOException {
        WatchKey key = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        monitoredKeys.put(key, dir);
        monitoredDirs.add(dir.toString());
        // uncomment to see every directory, rather than parent directories only.
        // LOG.info("Monitoring individual directory " + dir.toString());
    }
View Full Code Here


    public void run() {
        // loop forever, waiting on monitor for watchService, unless isTerminateThread
        for (;;) {

            // wait for watchService to become signaled
            WatchKey key;
            try {
                key = watchService.take();
                if (isTerminateThread()) {
                    return;
                }
            } catch (InterruptedException x) {
                return;
            }

            Path dir = monitoredKeys.get(key);
            if (dir == null) {
                LOG.info("did not recognize the requested WatchKey!");
                continue;
            }

            List<WatchEvent<?>> events = key.pollEvents();
            // process all events on the key
            for (WatchEvent<?> event : events) {
                WatchEvent.Kind<?> kind = event.kind();

                if (kind == OVERFLOW) {
                    // TODO - perhaps notify a special event to clear all caches,
                    // if file changes overflow the monitor
                    LOG.info("WatchService for aura file changes has overflowed.  Changes may have been missed.");
                    continue;
                }

                // once we have a directory event, we know the context is the file name of entry
                WatchEvent<Path> pathWatchEvent = cast(event);
                Path name = pathWatchEvent.context();

                // ensure the path resolution (absolute, relative) matches between paths
                Path child = dir.resolve(name);

                // isDir is true is file exists and is directory
                boolean isDir = Files.isDirectory(child, NOFOLLOW_LINKS);

                // signal appropriate handlers
                if (!isDir) {
                    try {
                        if (kind == ENTRY_CREATE) {
                            listener.fileCreated(new FileChangeEvent(child));
                        }
                        else if (kind == ENTRY_MODIFY) {
                            listener.fileChanged(new FileChangeEvent(child));
                        }
                        else if (kind == ENTRY_DELETE) {
                            listener.fileDeleted(new FileChangeEvent(child));
                        }
                    } catch (Exception ex) {
                        LOG.info("Unable to signal source change due to exception: " + ex.getMessage());
                    }
                }
                // recursively add any new directories created
                else if (kind == ENTRY_CREATE) {
                    try {
                        registerAll(child);
                    } catch (IOException x) {
                        // if we can't monitor it for some reason, it is not an error
                    }
                }
            }

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

                // all directories are inaccessible
View Full Code Here

        boolean notDone;
        notDone     = true;
       
        while (notDone){
            try {
                WatchKey claveBusqueda = watchService.poll(7, TimeUnit.DAYS);
                List<WatchEvent<?>> events = claveBusqueda.pollEvents();
                if (events.size() > 0){
                    for (WatchEvent event : events){
                        //Procesamos los eventos
                        switch (event.kind().toString()){
                            case "ENTRY_CREATE":
                                Archivos ret    = compruebaItems(event.context().toString());
                                if (ret != null){
                                    System.out.println("Añadimos " + ret.getNombre());
                                    cola.put( event.context().toString(), ret);
                                }
                                break;
                            case "ENTRY_DELETE":
                                cola.remove(event.context().toString());
                                break;
                            default:
                                break;
                        }

                        listado();
                    }
                    if (!claveBusqueda.reset()){
                        // Reseteamos la clave
                    }
                }
            } catch (    InterruptedException | NullPointerException e){
                System.out.println(e);
View Full Code Here

            LOGGER.debug("[{}] Starting up a new {} (thread ID: {})", mySessionHashCode, LogWatcherThread.class
                    .getSimpleName(), getId());
        }

        while (Thread.interrupted() == false) {
            WatchKey key;

            try {
                key = myWatchService.poll(10, TimeUnit.MILLISECONDS);
            } catch (InterruptedException details) {
                break;
            } catch (ClosedWatchServiceException details) {
                break;
            }

            if (key != null) {
                Path path = myKeys.get(key);

                for (WatchEvent<?> i : key.pollEvents()) {
                    @SuppressWarnings("unchecked")
                    WatchEvent<Path> event = (WatchEvent<Path>) i;
                    WatchEvent.Kind<Path> kind = event.kind();
                    Path name = event.context();
                    Path child = path.resolve(name);

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("[{}] {}: {} {}", mySessionHashCode, kind.name(), path, child);
                    }

                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
                            try {
                                Files.walkFileTree(child, new LogFileVisitor());
                            } catch (IOException details) {
                                details.printStackTrace();
                            }
                        }
                    }

                    if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                        LOGGER.info("Last modified: {}", child.toFile().lastModified());

                    }
                }

                if (key.reset() == false) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("[{}] Key '{}' is invalid", mySessionHashCode, key);
                    }

                    myKeys.remove(key);
View Full Code Here

   */
  private class WatcherThread implements Runnable {
    @Override
    public void run() {
      while (true) {
        WatchKey key = null;
        try {
          key = watchService.take();
        } catch (InterruptedException | ClosedWatchServiceException e) {
          return;
        }

        /* Poll the events and handle */
        for (WatchEvent<?> event : key.pollEvents()) {
          try {
            handleEvent(key, (WatchEvent<Path>) event);
          } catch (IOException e) {
            continue;
          }
        }

        /* Reset the Key to get more events later */
        if (!key.reset()) {
          try {
            handleDirectoryDeleted(key, (Path) key.watchable());
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
View Full Code Here

      throw new RuntimeException(e);
    }
    }
  
   private void register(Path dir) throws IOException {
       WatchKey key = dir.register(service, ENTRY_CREATE,
        ENTRY_MODIFY,
        ENTRY_DELETE);
       if (trace) {
           Path prev = keys.get(key);
           if (prev == null) {
View Full Code Here

  @SuppressWarnings("unchecked")
  @Override
  public void run() {
    while (running) {
      WatchKey key = getKey();
      if (key == null)
        continue;
      Path dir = keys.get(key);
      if (dir == null) {
        err.println("WatchKey not recognized: " + key);
        continue;
      }

      List<WatchEvent<?>> events = key.pollEvents();
      boolean shouldDelete = events.stream()
        .map(WatchEvent::kind)
        .anyMatch(ENTRY_DELETE::equals);
      events.stream()
        .map(e -> (WatchEvent<Path>) e)
        .peek(e -> out.println("> " + dir.resolve(e.context()).getFileName()))
        .filter(e -> e.kind()==ENTRY_CREATE)
        .map(e -> e.context())
        .map(name -> dir.resolve(name))
        .filter(path -> isDirectory(path, NOFOLLOW_LINKS))
        .forEach(this::registerAll);

      if(shouldDelete) compiler.clear();
      compiler.compileAll();
      key.reset();
    }
  }
View Full Code Here

  /**
   * Register the given directory with the WatchService
   */
  private void register(Path dir) throws IOException
  {
    WatchKey key= dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    if (trace)
    {
      Path prev= keys.get(key);
      if (prev == null)
      {
View Full Code Here

  {
    for (;;)
    {

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

      System.out.print(lines);
      lines= "";

      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.out.format("%s: %s\n", humanReadable(event.kind().name()), child.getName(child.getNameCount() - 1));

        if (reschedulableTimer.isScheduling())
          reschedulableTimer.reschedule(500);
        else
          reschedulableTimer.schedule(new Runnable()
          {
            public void run()
            {
              compile(classPath, path);
            }

          }, 500);

        // 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
View Full Code Here

  /**
   * Register the given directory with the WatchService
   */
  private void register(Path dir) throws IOException {
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE,
        ENTRY_MODIFY);
    // if (trace) {
    // Path prev = keys.get(key);
    // if (prev == null) {
    // System.out.format("register: %s\n", dir);
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.