Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

79
LINES

< > BotCompany Repo | #1019340 // Recursive Watcher Service Spike [dev.]

JavaX source code (desktop) - run with: x30.jar

Download Jar.

sclass RecursiWatcherService extends AutoCloseable {
  File rootFolder;
  WatchService watcher;
  ExecutorService executor;

  public void init() throws IOException {
    watcher = FileSystems.getDefault().newWatchService();
    executor = Executors.newSingleThreadExecutor();
    startRecursiveWatcher();
  }

  void cleanMeUp() { close(); }
  public void close() {
    pcall { watcher.close(); }
    executor.shutdown();
  }

    private void startRecursiveWatcher() throws IOException {
        LOG.info("Starting Recursive Watcher");

        final Map<WatchKey, Path> keys = new HashMap<>();

        Consumer<Path> register = p -> {
            if (!p.toFile().exists() || !p.toFile().isDirectory()) {
                throw new RuntimeException("folder " + p + " does not exist or is not a directory");
            }
            try {
                Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                        LOG.info("registering " + dir + " in watcher service");
                        WatchKey watchKey = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE}, SensitivityWatchEventModifier.HIGH);
                        keys.put(watchKey, dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                throw new RuntimeException("Error registering path " + p);
            }
        };

        register.accept(rootFolder.toPath());

        executor.submit(() -> {
            while (true) {
                final WatchKey key;
                try {
                    key = watcher.take(); // wait for a key to be available
                } catch (InterruptedException ex) {
                    return;
                }

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

                key.pollEvents().stream()
                        .filter(e -> (e.kind() != OVERFLOW))
                        .map(e -> ((WatchEvent<Path>) e).context())
                        .forEach(p -> {
                            final Path absPath = dir.resolve(p);
                            if (absPath.toFile().isDirectory()) {
                                register.accept(absPath);
                            } else {
                                final File f = absPath.toFile();
                                LOG.info("Detected new file " + f.getAbsolutePath());
                            }
                        });

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

download  show line numbers  debug dex  old transpilations   

Travelled to 12 computer(s): bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1019340
Snippet name: Recursive Watcher Service Spike [dev.]
Eternal ID of this version: #1019340/1
Text MD5: 79658dc5046db62d09809c6bd6e1a2e8
Author: stefan
Category: javax / gui / a.i.
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-11-03 12:27:56
Source code size: 3048 bytes / 79 lines
Pitched / IR pitched: No / No
Views / Downloads: 359 / 561
Referenced in: [show references]