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 info.magnolia.init.MagnoliaConfigurationProperties;
37
38 import java.io.IOException;
39 import java.nio.file.Path;
40 import java.util.concurrent.ExecutorService;
41 import java.util.concurrent.Executors;
42 import java.util.concurrent.Future;
43 import java.util.concurrent.TimeUnit;
44 import java.util.function.Predicate;
45
46 import javax.inject.Inject;
47 import javax.inject.Singleton;
48
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52
53
54
55
56
57
58 @Singleton
59 public class DirectoryWatcherService {
60
61 private static final Logger log = LoggerFactory.getLogger(DirectoryWatcherService.class);
62
63 private static final boolean RECURSIVE = true;
64 private static final boolean FOLLOW_LINKS = true;
65
66 private final ExecutorService executorService;
67 private final DirectoryWatcher watcher;
68
69 private Future<?> watcherFuture;
70
71 @Inject
72 public DirectoryWatcherService(MagnoliaConfigurationProperties properties) throws IOException {
73
74 this.executorService = Executors.newSingleThreadExecutor();
75 this.watcher = new DirectoryWatcher(RECURSIVE, FOLLOW_LINKS, properties);
76 }
77
78 public void start() {
79 }
80
81
82
83
84 public synchronized void register(Path path, Predicate<Path> filterPredicate, WatcherCallback callback) throws IOException {
85 if (watcherFuture == null) {
86 log.info("Starting DirectoryWatcher");
87 watcherFuture = executorService.submit(watcher);
88 }
89 watcher.register(path, filterPredicate, callback);
90 }
91
92
93
94
95
96
97 @Deprecated
98 public synchronized void register(Path path, com.google.common.base.Predicate<Path> filterPredicate, WatcherCallback callback) throws IOException {
99 register(path, (Predicate<Path>) filterPredicate::apply, callback);
100 }
101
102 public void stop() {
103 executorService.shutdownNow();
104
105 boolean terminated = false;
106 try {
107 terminated = executorService.awaitTermination(1, TimeUnit.SECONDS);
108 } catch (InterruptedException e) {
109 log.error("Exception during service termination", e);
110 }
111 if (terminated) {
112 log.info("{} terminated.", getClass().getSimpleName());
113 } else {
114 log.warn("{} not terminated, some tasks are still running.", getClass().getSimpleName());
115 }
116 }
117
118 }