|
1 | 1 | package com.example; |
2 | 2 |
|
3 | | -/** |
4 | | - * Model layer: encapsulates application data and business logic. |
5 | | - */ |
| 3 | +import java.net.URI; |
| 4 | +import java.net.http.HttpClient; |
| 5 | +import java.net.http.HttpRequest; |
| 6 | +import java.net.http.HttpResponse; |
| 7 | +import java.util.concurrent.CompletableFuture; |
| 8 | + |
6 | 9 | public class HelloModel { |
7 | | - /** |
8 | | - * Returns a greeting based on the current Java and JavaFX versions. |
9 | | - */ |
10 | | - public String getGreeting() { |
11 | | - String javaVersion = System.getProperty("java.version"); |
12 | | - String javafxVersion = System.getProperty("javafx.version"); |
13 | | - return "Hello, JavaFX " + javafxVersion + ", running on Java " + javaVersion + "."; |
| 10 | + private final HttpClient client = HttpClient.newHttpClient(); |
| 11 | + private final String topic; |
| 12 | + private final String backendUrl; |
| 13 | + |
| 14 | + public HelloModel(String topic) { |
| 15 | + this.topic = topic; |
| 16 | + this.backendUrl = System.getenv("BACKEND_URL"); |
| 17 | + if (backendUrl == null) { |
| 18 | + throw new IllegalStateException("BACKEND_URL is not set!"); |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public void sendMessage(String message) { |
| 23 | + String json = "{\"message\": \"" + message + "\"}"; |
| 24 | + String url = backendUrl + "/" + topic; |
| 25 | + |
| 26 | + HttpRequest request = HttpRequest.newBuilder() |
| 27 | + .uri(URI.create(url)) |
| 28 | + .header("Content-Type", "application/json") |
| 29 | + .POST(HttpRequest.BodyPublishers.ofString(json)) |
| 30 | + .build(); |
| 31 | + |
| 32 | + client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); |
| 33 | + } |
| 34 | + |
| 35 | + public CompletableFuture<Void> listen(MessageHandler handler) { |
| 36 | + String url = backendUrl + "/" + topic + "/json"; |
| 37 | + HttpRequest request = HttpRequest.newBuilder() |
| 38 | + .uri(URI.create(url)) |
| 39 | + .build(); |
| 40 | + |
| 41 | + return client.sendAsync(request, HttpResponse.BodyHandlers.ofLines()) |
| 42 | + .thenAccept(response -> response.body().forEach(line -> { |
| 43 | + if (line.contains("\"message\"")) { |
| 44 | + handler.onMessage(line); |
| 45 | + } |
| 46 | + })); |
| 47 | + } |
| 48 | + |
| 49 | + public interface MessageHandler { |
| 50 | + void onMessage(String message); |
14 | 51 | } |
15 | 52 | } |
0 commit comments