DHTClient.java

  1. package it.cnr.iit.utility.dht;

  2. import jakarta.websocket.*;

  3. import java.io.IOException;
  4. import java.net.URI;
  5. import java.net.URISyntaxException;
  6. import java.util.concurrent.Executors;
  7. import java.util.concurrent.ScheduledExecutorService;
  8. import java.util.concurrent.TimeUnit;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;

  11. import static it.cnr.iit.utility.dht.DHTUtils.isDhtReachable;

  12. @ClientEndpoint
  13. public class DHTClient {

  14.     Session session = null;
  15.     private MessageHandler handler;

  16.     private boolean isLoggingEnabled;

  17.     private WebSocketContainer container;

  18.     private URI wsURI;

  19.     private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

  20.     {
  21.         try {
  22.             wsURI = new URI("ws://localhost:3000/ws");
  23.         } catch (URISyntaxException e) {
  24.             throw new RuntimeException(e);
  25.         }
  26.     }

  27.     public DHTClient(URI endpointURI) {
  28.         this.wsURI = endpointURI;
  29.         connect(wsURI);
  30.     }

  31.     public DHTClient() {
  32.         connect(wsURI);
  33.     }

  34.     private void connect(URI endpointURI) throws RuntimeException {
  35.         try {
  36.             container = ContainerProvider.getWebSocketContainer();
  37.             session = container.connectToServer(this, endpointURI);
  38.         } catch (Exception e) {
  39.             //throw new RuntimeException("Unable to connect to " + wsURI.toString() + ". " + e.getMessage());
  40.             System.err.println("Unable to connect to " + endpointURI.toString());
  41.             scheduleReconnect();
  42.         }
  43.         isLoggingEnabled = true;
  44.     }

  45.     @OnOpen
  46.     public void onOpen(Session session) {
  47.         this.session = session;
  48.         System.out.println("Established websocket connection at " + wsURI);
  49.         System.out.println();
  50.     }

  51.     @OnError
  52.     public void onError(Session session, Throwable throwable) {
  53.         System.err.println("There was an error for session: " + session.getId());
  54.         handler.handleError();
  55.     }

  56.     public void addMessageHandler(MessageHandler msgHandler) {
  57.         this.handler = msgHandler;
  58.     }

  59.     @OnMessage
  60.     public void onMessage(String message) {
  61.         handler.handleMessage(message);
  62.         //System.out.println("Received message in client: " + message);
  63.     }

  64.     @OnClose
  65.     public void onClose(Session session, CloseReason closeReason) {
  66.         System.out.println("WebSocket connection closed: " + closeReason.getReasonPhrase());
  67.         scheduleReconnect();
  68.     }

  69.     private void scheduleReconnect() {
  70.         executor.schedule(() -> {
  71.             if (!session.isOpen()) {
  72.                 System.out.println("WebSocket reconnecting...");
  73.                 connect(wsURI);
  74.             }
  75.         }, 5, TimeUnit.SECONDS);
  76.     }

  77.     /**
  78.      * Sends a logging message to the DHT
  79.      *
  80.      */
  81.      public boolean sendMessage(String jsonOut) {

  82.         // Return if DHT logging is not used
  83.         if (!isLoggingEnabled) {
  84.             return false;
  85.         }

  86.         // If a connection is not established yet (which should
  87.         // have been done from the application), do it now
  88.         if (container == null || session == null) {
  89.             try {
  90.                 connect(wsURI);
  91.             } catch (RuntimeException e) {
  92.                 return false;
  93.             }
  94.         }

  95.         // Now send the payload to the DHT
  96.         try {
  97.             session.getBasicRemote().sendText(jsonOut);
  98.         } catch (IOException e) {
  99.             System.err.println("Error: Sending logging payload to DHT failed");
  100.             Logger.getLogger(DHTClient.class.getName()).log(Level.SEVERE, null, e);
  101.             e.printStackTrace();
  102.             return false;
  103.         }
  104.         return true;
  105.     }

  106.     public interface MessageHandler {
  107.          void handleMessage(String message);
  108.          void handleError();
  109.     }
  110. }