Package java.nio.file

Examples of java.nio.file.WatchKey


    @Override
    public void run() {
        for (;;) {

            // Wait for the next event
            WatchKey key;
            try {
                key = fsWatchService.take();
            } catch (InterruptedException e) {
                throw new StLightException(e);
            }

            // Go through all the events
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;

                // Check the path
                Path completePath = pathByKey.get(key).resolve(pathEvent.context());
                File completeFile = completePath.toFile();

                // Check the event
                WatchEvent.Kind<Path> kind = pathEvent.kind();
                if (StandardWatchEventKinds.OVERFLOW.equals(kind)) {
                    continue;
                } else if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind)) {
                    // Check if is a directory and we want to register it
                    if (recursive && Files.isDirectory(completePath, LinkOption.NOFOLLOW_LINKS)) {
                        registerRecursively(completePath);
                    }

                    for (FileSystemUpdateHandler handler : fileSystemUpdateHandlers) {
                        handler.created(completeFile);
                    }
                } else if (StandardWatchEventKinds.ENTRY_MODIFY.equals(kind)) {
                    for (FileSystemUpdateHandler handler : fileSystemUpdateHandlers) {
                        handler.modified(completeFile);
                    }
                } else if (StandardWatchEventKinds.ENTRY_DELETE.equals(kind)) {
                    for (FileSystemUpdateHandler handler : fileSystemUpdateHandlers) {
                        handler.deleted(completeFile);
                    }
                }

            }

            // Reset
            if (!key.reset()) {
                pathByKey.remove(key);
            }

        }
    }
View Full Code Here


                     dirty = true;
                  }

               }

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

               if (dirty)
               {
View Full Code Here

      }
    }
  }

  private void checkForChanges() {
    final WatchKey key = folderWatcher.poll();

    if (key != null) {
      for (WatchEvent<?> watchEvent : key.pollEvents()) {
        final Path filePath = (Path) watchEvent.context();
        final WatchEvent.Kind<?> kind = watchEvent.kind();
        log.fine(kind + " : " + filePath);
        handleFileChange(kind,
                         new File(iosServerConfiguration.getAppFolderToMonitor(),
                                  filePath.getFileName().toString()));
      }

      boolean valid = key.reset();
      if (!valid) {
        log.warning("Can't monitor folder anymore; has it been deleted?");
        stop();
      }
    }
View Full Code Here

   * New files are removed from the MarkupCache because there could be
   * {@link org.apache.wicket.markup.Markup#NO_MARKUP} (Not Found) entries for them already.
   */
  protected void checkCreated()
  {
    WatchKey watchKey = watchService.poll();
    if (watchKey != null)
    {
      List<WatchEvent<?>> events = watchKey.pollEvents();
      for (WatchEvent<?> event : events)
      {
        WatchEvent.Kind<?> eventKind = event.kind();
        Path eventPath = (Path) event.context();

        if (eventKind == ENTRY_CREATE)
        {
          if (Files.isDirectory(eventPath))
          {
            try
            {
              // a directory is created. register it for notifications
              register(eventPath, watchService);
            } catch (IOException iox)
            {
              LOG.warn("Cannot register folder '" + eventPath + "' to be watched.", iox);
            }
          }
          else
          {
            // a new file appeared. we need to clear the NOT_FOUND entry that may be added earlier.
            // MarkupCache keys are fully qualified URIs
            String absolutePath = eventPath.toAbsolutePath().toFile().toURI().toString();

            try
            {
              ThreadContext.setApplication(application);
              application.getMarkupSettings()
                  .getMarkupFactory().getMarkupCache().removeMarkup(absolutePath);
            } finally {
              ThreadContext.setApplication(null);
            }
          }
        }
      }

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

     */
    private WatchKey poll() throws ServiceException {
        if (StandardDirectoryService.LOG.isDebugEnabled()) {
            StandardDirectoryService.LOG.debug(MethodUtils.executionMessage());
        }
        WatchKey resultKey = GeneratorUtils.<WatchKey>generateDefaultUnknownValue();
        try {
            resultKey = this.getWatchService().poll(this.getPollTime(), TimeUnit.SECONDS);
            if (StandardDirectoryService.LOG.isDebugEnabled()) {
                StandardDirectoryService.LOG.debug(MethodUtils.successMessage());
            }
View Full Code Here

      final boolean considerPreexistingFilesChanged) throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult preVisitDirectory(Path currentDirectory, BasicFileAttributes attrs)
          throws IOException {
        WatchKey watchKey = currentDirectory.register(watchService,
            StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY);

        // If the recursive directory scan has gone in a loop because of symlinks.
        if (pathsByWatchKey.containsKey(watchKey)) {
View Full Code Here

  private class WatchEventPoller implements Runnable {
    @Override
    public void run() {
      try {
        while (true) {
          WatchKey watchKey;
          try {
            watchKey = watchService.take();
          } catch (InterruptedException e) {
            // Shutdown has been requested.
            return;
          } catch (ClosedWatchServiceException e) {
            // Shutdown has been requested.
            return;
          }

          synchronized (changedFiles) {
            Path containingDirectory = pathsByWatchKey.get(watchKey);

            for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
              WatchEvent.Kind<?> eventKind = watchEvent.kind();

              if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                setFailed(
                    new RuntimeException("Changes occurred faster than they could be recorded."));
                return;
              }

              if (!(watchEvent.context() instanceof Path)) {
                continue;
              }

              Path changedFileName = (Path) watchEvent.context();
              Path changedPath = containingDirectory.resolve(changedFileName);

              // Maybe listen to newly created directories.
              if (eventKind == StandardWatchEventKinds.ENTRY_CREATE
                  && Files.isDirectory(changedPath)) {
                // A new directory and some contained files can be created faster than watches can
                // be attached to new directories. So it is necessary to look for files in what are
                // believed to be "newly created" directories and consider those files changed.
                try {
                  recursivelyRegisterListeners(
                      changedPath, true /* considerPreexistingFilesChanged */);
                } catch (IOException e) {
                  setFailed(e);
                  return;
                }
              }

              // Record changed files.
              changedFiles.add(changedPath.toFile().getAbsoluteFile());
            }

            // Ensures that future change events will be seen.
            if (!watchKey.reset()) {
              pathsByWatchKey.remove(watchKey);
            }
          }
        }
      } catch (RuntimeException e) {
View Full Code Here

  @Override
  public void run() {
        while (active) {
      try {
        WatchKey watchKey = watchService.poll(sleepTime, TimeUnit.MILLISECONDS);
        if(watchKey!=null){
          List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
          for(WatchEvent<?> watchEvent : watchEvents){
            WatchEvent.Kind<?> kind = watchEvent.kind();
                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                      // TODO how is this supposed to be handled? I think the best thing to do is ignore it, but I'm not positive
                      LOG.warn("WatchService Overflow occurred");
                        continue;
                    }
            WatchEvent<Path> pathWatchEvent = cast(watchEvent);
            Path name = pathWatchEvent.context();
            Path dir = (Path) watchKey.watchable();
            Path child = dir.resolve(name).toAbsolutePath();
            File childFile = child.toFile();
            if(individualWatchedFiles.contains(child)){
              if(kind == StandardWatchEventKinds.ENTRY_CREATE){
                fireOnNew(childFile);
              }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
                fireOnChange(childFile);
              }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
                // do nothing... there's no way to communicate deletions
              }
            }else{
              List<String> fileExtensions = watchKeyToExtensionsMap.get(watchKey);
              if(fileExtensions==null){
                throw new IllegalStateException("No file extensions list found for path not being watched");
              }
              if(kind==StandardWatchEventKinds.ENTRY_CREATE){
                // new directory created, so watch its contents
                addWatchDirectory(child,fileExtensions);
              }
              if(isValidFileToMonitor(childFile,fileExtensions)){
                if(kind == StandardWatchEventKinds.ENTRY_CREATE){
                  fireOnNew(childFile);
                }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
                  fireOnChange(childFile);
                }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
                  // do nothing... there's no way to communicate deletions
                }
              }
            }
          }
          watchKey.reset();
        }
      } catch (InterruptedException e) {
        // ignore
      }
        }
View Full Code Here

                  throws IOException
              {
                if(!isValidDirectoryToMonitor(dir.toFile())){
                  return FileVisitResult.SKIP_SUBTREE;
                }
            WatchKey watchKey = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
            final List<String> originalFileExtensions = watchKeyToExtensionsMap.get(watchKey);
            if(originalFileExtensions==null){
              watchKeyToExtensionsMap.put(watchKey, fileExtensions);
            }else{
              final HashSet<String> newFileExtensions = new HashSet<String>(originalFileExtensions);
View Full Code Here

   /**
    * Register the given directory with the WatchService
    */
   private void register(Path path, ResourceMonitorImpl monitorImpl) throws IOException
   {
      WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
      keys.put(key, monitorImpl);
   }
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.