JsonDecoder.java

  1. /*
  2.  * The coLAB project
  3.  * Copyright (C) 2021-2023 AlbaSim, MEI, HEIG-VD, HES-SO
  4.  *
  5.  * Licensed under the MIT License
  6.  */
  7. package ch.colabproject.colab.api.ws.utils;

  8. import ch.colabproject.colab.api.ws.message.WsMessage;
  9. import ch.colabproject.colab.generator.model.tools.JsonbProvider;
  10. import java.io.StringReader;
  11. import javax.json.Json;
  12. import javax.json.JsonException;
  13. import javax.json.JsonReader;
  14. import javax.json.bind.Jsonb;
  15. import javax.websocket.DecodeException;
  16. import javax.websocket.Decoder;
  17. import javax.websocket.EndpointConfig;

  18. /**
  19.  * Convert JSON-encoded Websocket message received from clients
  20.  *
  21.  * @author maxence
  22.  */
  23. public class JsonDecoder implements Decoder.Text<WsMessage> {

  24.     /**
  25.      * Parse message with {@link JsonbProvider#getJsonb()}
  26.      *
  27.      * @param s message received from a client
  28.      *
  29.      * @return revived message
  30.      *
  31.      * @throws DecodeException if message is not parseble
  32.      */
  33.     @Override
  34.     public WsMessage decode(String s) throws DecodeException {
  35.         Jsonb jsonb = JsonbProvider.getJsonb();
  36.         return jsonb.fromJson(s, WsMessage.class);
  37.     }

  38.     /**
  39.      * Is this decoder can handler the given message ?
  40.      *
  41.      * @param s the message to decode
  42.      *
  43.      * @return true if this decoder can handle the message, false otherwise
  44.      */
  45.     @Override
  46.     public boolean willDecode(String s) {
  47.         try (JsonReader jsonReader = Json.createReader(new StringReader(s))) {
  48.             jsonReader.readObject();
  49.             return true;
  50.         } catch (JsonException e) {
  51.             return false;
  52.         }
  53.     }

  54.     /**
  55.      * {@inheritDoc }
  56.      */
  57.     @Override
  58.     public void init(EndpointConfig config) {
  59.         /* no-op */
  60.     }

  61.     /**
  62.      * {@inheritDoc }
  63.      */
  64.     @Override
  65.     public void destroy() {
  66.         /* no-op */
  67.     }

  68. }