1+ package com .example ;
2+
3+ import io .github .cdimascio .dotenv .Dotenv ;
4+ import tools .jackson .databind .ObjectMapper ;
5+
6+ import java .io .IOException ;
7+ import java .net .URI ;
8+ import java .net .http .HttpClient ;
9+ import java .net .http .HttpRequest ;
10+ import java .net .http .HttpResponse ;
11+ import java .util .Objects ;
12+ import java .util .function .Consumer ;
13+
14+ public class NtfyConnectionImpl implements NtfyConnection {
15+
16+ private final HttpClient http = HttpClient .newHttpClient ();
17+ private final String hostName ;
18+ private final ObjectMapper mapper = new ObjectMapper ();
19+
20+ public NtfyConnectionImpl () {
21+ Dotenv dotenv = Dotenv .load ();
22+ hostName = Objects .requireNonNull (dotenv .get ("HOST_NAME" ));
23+ }
24+
25+ public NtfyConnectionImpl (String hostName ) {
26+ this .hostName = hostName ;
27+ }
28+
29+ @ Override
30+ public boolean send (String message ) {
31+ HttpRequest httpRequest = HttpRequest .newBuilder ()
32+ .POST (HttpRequest .BodyPublishers .ofString (message ))
33+ .header ("Cache" , "no" )
34+ .uri (URI .create (hostName + "/mytopic" ))
35+ .build ();
36+ try {
37+ //Todo: handle long blocking send requests to not freeze the JavaFX thread
38+ //1. Use thread send message?
39+ //2. Use async?
40+ var reponse = http .send (httpRequest , HttpResponse .BodyHandlers .discarding ());
41+ return true ;
42+ } catch (IOException e ) {
43+ System .out .println ("Error sending message" );
44+ } catch (InterruptedException e ) {
45+ System .out .println ("Interruped sending message" );
46+ }
47+ return false ;
48+ }
49+
50+ @ Override
51+ public void receive (Consumer <NtfyMessageDto > messageHandler ) {
52+ HttpRequest httpRequest = HttpRequest .newBuilder ()
53+ .GET ()
54+ .uri (URI .create (hostName + "/mytopic/json" ))
55+ .build ();
56+
57+ http .sendAsync (httpRequest , HttpResponse .BodyHandlers .ofLines ())
58+ .thenAccept (response -> response .body ()
59+ .map (s ->
60+ mapper .readValue (s , NtfyMessageDto .class ))
61+ .filter (message -> message .event ().equals ("message" ))
62+ .peek (System .out ::println )
63+ .forEach (messageHandler ));
64+ }
65+ }
0 commit comments