1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.dirwatch;
35
36 import java.io.IOException;
37 import java.nio.file.Path;
38 import java.util.concurrent.ExecutorService;
39 import java.util.concurrent.Executors;
40 import java.util.concurrent.Future;
41 import java.util.concurrent.TimeUnit;
42
43 import javax.inject.Singleton;
44
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 import com.google.common.base.Predicate;
49
50
51
52
53
54
55
56 @Singleton
57 public class DirectoryWatcherService {
58
59 private static final Logger log = LoggerFactory.getLogger(DirectoryWatcherService.class);
60
61 private static final boolean RECURSIVE = true;
62 private static final boolean FOLLOW_LINKS = true;
63
64 private final ExecutorService executorService;
65 private final DirectoryWatcher watcher;
66
67 private Future<?> watcherFuture;
68
69 public DirectoryWatcherService() throws IOException {
70
71 this.executorService = Executors.newSingleThreadExecutor();
72 this.watcher = new DirectoryWatcher(RECURSIVE, FOLLOW_LINKS);
73 }
74
75 public void start() {
76 }
77
78
79
80
81 public synchronized void register(Path path, Predicate<Path> filterPredicate, WatcherCallback callback) throws IOException {
82 if (watcherFuture == null) {
83 log.info("Starting DirectoryWatcher");
84 watcherFuture = executorService.submit(watcher);
85 }
86 watcher.register(path, filterPredicate, callback);
87 }
88
89 public void stop() {
90 executorService.shutdownNow();
91
92 boolean terminated = false;
93 try {
94 terminated = executorService.awaitTermination(1, TimeUnit.SECONDS);
95 } catch (InterruptedException e) {
96 log.error("Exception during service termination", e);
97 }
98 if (terminated) {
99 log.info("{} terminated.", getClass().getSimpleName());
100 } else {
101 log.warn("{} not terminated, some tasks are still running.", getClass().getSimpleName());
102 }
103 }
104
105 }