-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonitorThread.java
More file actions
58 lines (47 loc) · 2.2 KB
/
MonitorThread.java
File metadata and controls
58 lines (47 loc) · 2.2 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
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class MonitorThread extends Thread {
private final BlockingQueue<DataRecord> queue;
private final RecommendationEngine engine = new RecommendationEngine();
private volatile boolean running = true;
public MonitorThread(BlockingQueue<DataRecord> queue) {
this.queue = queue;
}
@Override
public void run() {
while (running || !queue.isEmpty()) {
try {
DataRecord record = queue.poll(1, TimeUnit.SECONDS);
if (record == null) continue;
// Generate recommendation text
String advice = engine.processRecord(record);
// Save formatted recommendation to history file
FileManager.writeToFile(FileManager.HISTORY_FILE, advice);
// (Optionally) ensure raw CSV is saved (GUI or console may already save it)
// But to be safe, write raw CSV here too (it will append)
FileManager.writeToFile(FileManager.DATA_FILE, record.toCSV());
// Detect alerts and save
List<String> alerts = engine.detectAlerts(record);
if (!alerts.isEmpty()) {
String header = "[" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "] Location: " + record.location;
FileManager.writeToFile(FileManager.ALERT_FILE, header);
for (String a : alerts) FileManager.writeToFile(FileManager.ALERT_FILE, a);
}
// Recompute daily report (reads data.txt)
FileManager.updateDailyReport();
// Also print to console (helpful for debugging)
System.out.println("\n✅ New Recommendation Generated:\n" + advice);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception ex) {
System.out.println("Error in monitor thread: " + ex.getMessage());
}
}
}
public void stopThread() {
running = false;
}
}