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.

1  
sclass RecursiWatcherService extends AutoCloseable {
2  
  File rootFolder;
3  
  WatchService watcher;
4  
  ExecutorService executor;
5  
6  
  public void init() throws IOException {
7  
    watcher = FileSystems.getDefault().newWatchService();
8  
    executor = Executors.newSingleThreadExecutor();
9  
    startRecursiveWatcher();
10  
  }
11  
12  
  void cleanMeUp() { close(); }
13  
  public void close() {
14  
    pcall { watcher.close(); }
15  
    executor.shutdown();
16  
  }
17  
18  
    private void startRecursiveWatcher() throws IOException {
19  
        LOG.info("Starting Recursive Watcher");
20  
21  
        final Map<WatchKey, Path> keys = new HashMap<>();
22  
23  
        Consumer<Path> register = p -> {
24  
            if (!p.toFile().exists() || !p.toFile().isDirectory()) {
25  
                throw new RuntimeException("folder " + p + " does not exist or is not a directory");
26  
            }
27  
            try {
28  
                Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
29  
                    @Override
30  
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
31  
                        LOG.info("registering " + dir + " in watcher service");
32  
                        WatchKey watchKey = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE}, SensitivityWatchEventModifier.HIGH);
33  
                        keys.put(watchKey, dir);
34  
                        return FileVisitResult.CONTINUE;
35  
                    }
36  
                });
37  
            } catch (IOException e) {
38  
                throw new RuntimeException("Error registering path " + p);
39  
            }
40  
        };
41  
42  
        register.accept(rootFolder.toPath());
43  
44  
        executor.submit(() -> {
45  
            while (true) {
46  
                final WatchKey key;
47  
                try {
48  
                    key = watcher.take(); // wait for a key to be available
49  
                } catch (InterruptedException ex) {
50  
                    return;
51  
                }
52  
53  
                final Path dir = keys.get(key);
54  
                if (dir == null) {
55  
                    System.err.println("WatchKey " + key + " not recognized!");
56  
                    continue;
57  
                }
58  
59  
                key.pollEvents().stream()
60  
                        .filter(e -> (e.kind() != OVERFLOW))
61  
                        .map(e -> ((WatchEvent<Path>) e).context())
62  
                        .forEach(p -> {
63  
                            final Path absPath = dir.resolve(p);
64  
                            if (absPath.toFile().isDirectory()) {
65  
                                register.accept(absPath);
66  
                            } else {
67  
                                final File f = absPath.toFile();
68  
                                LOG.info("Detected new file " + f.getAbsolutePath());
69  
                            }
70  
                        });
71  
72  
                boolean valid = key.reset(); // IMPORTANT: The key must be reset after processed
73  
                if (!valid) {
74  
                    break;
75  
                }
76  
            }
77  
        });
78  
    }
79  
}

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: 230 / 379
Referenced in: [show references]