Package java.nio.file

Examples of java.nio.file.WatchKey


                register(watchService, root);
            }
            log.debug("watching...");
            while (true) {
                try {
                    final WatchKey key = watchService.take();

                    final Path parent = pathTable.get(key);
                    if (parent == null) {
                        log.warn("WatchKey not recognized: {}, ignoring event", key);
                        continue;
                    }
                    try {
                        for (WatchEvent<?> event : key.pollEvents()) {
                            final WatchEvent.Kind<?> kind = event.kind();

                            if (kind == OVERFLOW) {
                                log.trace("overflow event for {}", parent);
                                continue;
                            }

                            @SuppressWarnings("unchecked")
                            final WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;

                            final Path localPath = pathEvent.context();
                            if (localPath == null) {
                                log.warn("Could not get context for %s in %s", kind, parent);
                                continue;
                            }
                            final Path target = parent.resolve(localPath);
                            if (kind == ENTRY_CREATE) {
                                if (Files.isDirectory(target)) {
                                    log.trace("created dir: {}", target);
                                    onDirectoryCreated(target);
                                    if (recursive) {
                                        registerAll(watchService, target);
                                    }
                                } else {
                                    log.trace("created file: {}", target);
                                    onFileCreated(target);
                                }
                                log.trace("new child in {}: {}", parent, localPath);
                                onChildCreated(parent, target);
                            } else if (kind == ENTRY_MODIFY) {
                                log.trace("modified file: {}", target);
                                onFileModified(target);
                            } else if (kind == ENTRY_DELETE) {
                                log.trace("deleted child in {}: {}", parent, localPath);
                                onChildDeleted(parent, target);
                            } else {
                                log.error("Unexpected event type: {}", kind);
                                continue;
                            }
                        }
                    } finally {
                        if (!key.reset()) {
                            pathTable.remove(key);
                        }
                    }
                } catch (InterruptedException | ClosedWatchServiceException e) {
                    log.trace("shutting down...");
View Full Code Here


     * @param dir the dir to register
     * @return the registered {@link WatchKey}
     * @throws IOException
     */
    private WatchKey register(WatchService watcher, Path dir) throws IOException {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

        Path prev = pathTable.get(key);
        if (prev == null) {
            log.trace("new watch on {}", dir);
        } else {
View Full Code Here

        //// THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER
        //// THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
        //// MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
        ////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       
        WatchKey watchKey = path.register(
                watchService,
           new WatchEvent.Kind[]{
               StandardWatchEventKinds.ENTRY_CREATE,
               StandardWatchEventKinds.ENTRY_MODIFY,
               StandardWatchEventKinds.ENTRY_DELETE
View Full Code Here

    public void startWatching() {

        for (;;) {

            WatchKey watchKey;
            try {
                watchKey = watchService.take();
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
                return;
            }

            Path path = mapOfWatchKeysToPaths.get(watchKey);
            if (path == null) {
                System.err.println("WatchKey not recognized!!");
                continue;
            }



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

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

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

                // print out watchEvent
                //System.out.format("%s: %s\n", watchEvent.kind().name(), child);
               
                if (watchEventKind == ENTRY_MODIFY) {
                   
                    // we are not interested in events from parent directories...
                    if (! child.toFile().isDirectory()) {
                       
                        if (!checkIfMatchesPattern(exludePatterns, child.toFile().getAbsolutePath())) {
                       
                            System.out.println(
                                    "Found file modification - triggering reload:  "
                                        + child.toFile().getAbsolutePath());
                           
                            restartAfterSomeTimeAndChanges.triggerRestart();
                           
                        }
                   
                    }

                }

                // ninjaJettyInsideSeparateJvm.restartNinjaJetty();
                // if directory is created, then
                // register it and its sub-directories recursively
                if (watchEventKind == ENTRY_CREATE) {
                   
                    restartAfterSomeTimeAndChanges.triggerRestart();
                   
                    try {
                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                            registerAll(child);
                        }
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                        // ignore to keep sample readable
                    }

                }

            }

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

                // all directories are inaccessible
                if (mapOfWatchKeysToPaths.isEmpty()) {
View Full Code Here

      System.err.println(x);
    }

    for (;;) {

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

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

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

       
        Path dirPath = (Path)key.watchable();
        Path fullPath = dirPath.resolve((Path) event.context());
       

        ImportFile importer = new ImportFile();
       
        if (importer.checkExtension(fullPath.toString())) {
          importer.setDir(fullPath.toString());
          DomainResults result = importer.importFile();
          result.saveResult(fullPath.toFile().getName().toString().replace(".dat", ""), dirOut);
        }
      }
      boolean valid = key.reset();
      if (!valid) {
        break;
      }

    }
View Full Code Here

      dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
      getLog().info("Watching " + inputPath + " for changes");
      generate();
      boolean valid = true;
      while (valid) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
          if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
            continue;
          }
          WatchEvent<Path> ev = (WatchEvent<Path>) event;
          if(dir.resolve(ev.context()).equals(inputPath)) {
            generate();
          }
        }
        valid = key.reset();
      }
    } catch (IOException | InterruptedException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
View Full Code Here

        @Override
        @SuppressWarnings( "unchecked" )
        public Void call() throws Exception {
            for (;;) {
                try {
                    WatchKey watchKey = watchService.take();
                    @SuppressWarnings( "synthetic-access" )
                    ConnectorChangeSet connectorChangeSet = connector.newConnectorChangedSet();
                    for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
                        WatchEvent.Kind<?> kind = watchEvent.kind();

                        Path eventPath = ((WatchEvent<Path>)watchEvent).context();
                        Path resolvedPath = ((Path)watchKey.watchable()).resolve(eventPath);
                        File resolvedFile = resolvedPath.toFile();

                        if (connector.isExcluded(resolvedFile)) {
                            continue;
                        }

                        if (kind == ENTRY_CREATE) {
                            fireEntryCreated(connectorChangeSet, resolvedPath);
                        } else if (kind == ENTRY_DELETE) {
                            fireEntryDeleted(connectorChangeSet, resolvedPath);
                        } else if (kind == ENTRY_MODIFY) {
                            fireEntryModified(connectorChangeSet, resolvedPath);
                        }
                    }
                    watchKey.reset();
                    connectorChangeSet.publish(null);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                    watchService.close();
                    break;
View Full Code Here

  }

  private void assertWatcherHasEvents(
      List<WatchEvent<?>> expected, List<WatchEvent<?>> alternate) throws InterruptedException {
    ensureTimeToPoll(); // otherwise we could read 1 event but not all the events we're expecting
    WatchKey key = watcher.take();
    List<WatchEvent<?>> keyEvents = key.pollEvents();

    if (keyEvents.size() == expected.size() || alternate.isEmpty()) {
      assertThat(keyEvents).containsExactlyElementsIn(expected);
    } else {
      assertThat(keyEvents).containsExactlyElementsIn(alternate);
    }
    key.reset();
  }
View Full Code Here

        try (WatchService watcher = FileSystems.getDefault().newWatchService();) {
            moduleDir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

            LOG.info("Filesystem monitor: Watching module directory " + moduleDir + " for changes.");
            for (;;) {
                final WatchKey key = watcher.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    final WatchEvent.Kind<?> kind = event.kind();

                    if (kind == OVERFLOW) { // An OVERFLOW event can occur regardless of registration if events are lost or discarded.
                        LOG.warn("Filesystem monitor: filesystem events may have been missed");
                        continue;
                    }

                    final WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    final Path filename = ev.context(); // The filename is the context of the event.
                    final Path child = moduleDir.resolve(filename); // Resolve the filename against the directory.
                    if (isValidFile(child, kind == ENTRY_DELETE)) {
                        try {
                            final URL jarUrl = child.toUri().toURL();

                            LOG.info("Filesystem monitor: detected module file {} {}", child,
                                    kind == ENTRY_CREATE ? "created"
                                    : kind == ENTRY_MODIFY ? "modified"
                                    : kind == ENTRY_DELETE ? "deleted"
                                    : null);

                            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                                instance.reloadModule(jarUrl);
                            else if (kind == ENTRY_DELETE)
                                instance.unloadModule(jarUrl);
                        } catch (Exception e) {
                            LOG.error("Filesystem monitor: exception while processing " + child, e);
                        }
                    } else {
                        if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY)
                            LOG.warn("Filesystem monitor: A non-jar item " + child.getFileName() + " has been placed in the modules directory " + moduleDir);
                    }
                }
                if (!key.reset())
                    throw new IOException("Directory " + moduleDir + " is no longer accessible");
            }
        } catch (Exception e) {
            LOG.error("Filesystem monitor thread terminated with an exception", e);
            throw Exceptions.rethrow(e);
View Full Code Here

    key.post(event);
    key.signal();

    assertThat(watcher.queuedKeys()).containsExactly(key);

    WatchKey retrievedKey = watcher.poll();
    assertThat(retrievedKey).isEqualTo(key);

    List<WatchEvent<?>> events = retrievedKey.pollEvents();
    assertThat(events.size()).is(1);
    assertThat(events.get(0)).isEqualTo(event);

    // polling should have removed all events
    assertThat(retrievedKey.pollEvents()).isEmpty();
  }
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.