-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloModel.java
More file actions
94 lines (78 loc) · 3.24 KB
/
HelloModel.java
File metadata and controls
94 lines (78 loc) · 3.24 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 com.example;
import io.github.cdimascio.dotenv.Dotenv;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import tools.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Objects;
/**
* Model layer: encapsulates application data and business logic.
*/
public class HelloModel {
private final String hostName;
private final HttpClient http = HttpClient.newHttpClient();
private final ObjectMapper mapper = new ObjectMapper();
private final ObservableList<NtfyMessageDto> messages = FXCollections.observableArrayList();
private boolean senderMe=false;
public HelloModel() {
Dotenv dotenv = Dotenv.load();
hostName = Objects.requireNonNull(dotenv.get("HOST_NAME"));
receiveMessage();
}
public ObservableList<NtfyMessageDto> getMessages() {
return messages;
}
/**
* Returns a greeting based on the current Java and JavaFX versions.
*/
public String getGreeting() {
String javaVersion = System.getProperty("java.version");
String javafxVersion = System.getProperty("javafx.version");
return "Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + ".";
}
public void sendMessage(String text) {
senderMe=true;
long now = System.currentTimeMillis() / 1000;
NtfyMessageDto myMsg = new NtfyMessageDto("local", now, "message", "me", text);
Platform.runLater(() -> messages.add(myMsg));
HttpRequest httpRequest= HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(text))
.uri(URI.create(hostName + "/mytopic"))
.build();
http.sendAsync(httpRequest, HttpResponse.BodyHandlers.discarding())
.exceptionally(ex -> {
System.out.println("Error sending message: " + ex.getMessage());
return null;
});
}
public void receiveMessage(){
HttpRequest httpRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(hostName + "/mytopic/json"))
.build();
http.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofLines())
.thenAccept(response -> response.body()
.map(s -> {
try {
return mapper.readValue(s, NtfyMessageDto.class);
} catch (Exception e) {
System.err.println("Failed to parse message: " + e.getMessage());
return null;
}
})
.filter(Objects::nonNull)
.filter(msg -> "message".equals(msg.event()))
.forEach(msg->{
if (senderMe) {
senderMe=false;
return;
}
Platform.runLater(() -> messages.add(msg));
}));
}
}