forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrinterTrayWatcher.java
More file actions
94 lines (74 loc) · 3.55 KB
/
Copy pathPrinterTrayWatcher.java
File metadata and controls
94 lines (74 loc) · 3.55 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package modern.challenge;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class PrinterTrayWatcher {
private final Map<Thread, Path> threads = new HashMap<>();
public void watchTray(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
System.out.println("Printer watcher ready ...");
//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);
//get list of events for the watch key
if (key != null) {
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Sending the document to print -> " + filename);
Runnable task = new Printer(path.resolve(filename));
Thread worker = new Thread(task);
//we can set the name of the thread
worker.setName(path.resolve(filename).toString());
//store the thread and the path
threads.put(worker, path.resolve(filename));
//start the thread
worker.start();
}
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println(filename + " was successfully printed!");
}
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, per example)
if (!valid) {
threads.clear();
break;
}
}
if (!threads.isEmpty()) {
for (Iterator<Map.Entry<Thread, Path>> it =
threads.entrySet().iterator(); it.hasNext();) {
Map.Entry<Thread, Path> entry = it.next();
if (entry.getKey().getState() == Thread.State.TERMINATED) {
Files.deleteIfExists(entry.getValue());
it.remove();
}
}
}
}
}
}
}