-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathPollingFileWatchService.java
More file actions
71 lines (61 loc) · 2.08 KB
/
Copy pathPollingFileWatchService.java
File metadata and controls
71 lines (61 loc) · 2.08 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* Copyright (C) from 2022 The Play Framework Contributors <https://github.com/playframework>, 2011-2021 Lightbend Inc. <https://www.lightbend.com>
*/
package play.dev.filewatch;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/** A polling Play watch service. Polls in the background. */
public class PollingFileWatchService implements FileWatchService {
private final int pollDelayMillis;
private volatile boolean stopped;
public PollingFileWatchService(int pollDelayMillis) {
this.pollDelayMillis = pollDelayMillis;
}
private static Iterable<File> listRecursively(Iterable<File> files) {
return StreamSupport.stream(files.spliterator(), false)
.flatMap(
file -> {
try {
return Files.walk(file.toPath()).filter(path -> !path.equals(file.toPath()));
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.map(Path::toFile)
.collect(Collectors.toList());
}
@Override
public FileWatcher watch(Iterable<File> filesToWatch, Consumer<Optional<Path>> onChange) {
stopped = false;
var thread =
new Thread(
() -> {
var state = WatchState.empty();
while (!stopped) {
var result =
SourceModificationWatch.watch(
() -> PollingFileWatchService.listRecursively(filesToWatch),
pollDelayMillis,
state,
() -> stopped);
if (result.isTriggered()) {
onChange.accept(Optional.empty());
}
state = result.getState();
}
},
"play-watch-service");
thread.setDaemon(true);
thread.start();
return () -> stopped = true;
}
public int getPollDelayMillis() {
return pollDelayMillis;
}
}