|
| 1 | +package dev.loat.web_socket_console.web_socket.receive; |
| 2 | + |
| 3 | +import dev.loat.web_socket_console.logging.Logger; |
| 4 | +import org.json.JSONException; |
| 5 | +import org.json.JSONObject; |
| 6 | +import org.json.JSONString; |
| 7 | + |
| 8 | +import java.util.*; |
| 9 | +import java.util.function.Consumer; |
| 10 | + |
| 11 | +public class Parser { |
| 12 | + private static final Map<String, List<Consumer<JSONObject>>> listeners = new HashMap<>(); |
| 13 | + |
| 14 | + /** |
| 15 | + * This function parses the message. |
| 16 | + * |
| 17 | + * @param message The message to parse |
| 18 | + */ |
| 19 | + public static void parse(String message) { |
| 20 | + JSONObject messageObject; |
| 21 | + String type; |
| 22 | + JSONObject payload; |
| 23 | + |
| 24 | + try { |
| 25 | + messageObject = new JSONObject(message); |
| 26 | + } catch (JSONException error) { |
| 27 | + Logger.error("Failed to parse message: {}", error.getMessage()); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + try { |
| 32 | + type = messageObject.getString("type"); |
| 33 | + } catch (JSONException error) { |
| 34 | + Logger.error("Failed to parse type: {}", error.getMessage()); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + try { |
| 39 | + payload = messageObject.getJSONObject("payload"); |
| 40 | + } catch (JSONException error) { |
| 41 | + Logger.error("Failed to parse payload: {}", error.getMessage()); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + Parser.listeners.getOrDefault(type, new ArrayList<>()).forEach((callback) -> { |
| 46 | + callback.accept(payload); |
| 47 | + }); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * This function allows to add listeners to specific message types. |
| 52 | + * |
| 53 | + * @param type The type of the message |
| 54 | + * @param callback The function to call when receiving the message |
| 55 | + */ |
| 56 | + public static void addListener( |
| 57 | + String type, |
| 58 | + Consumer<JSONObject> callback |
| 59 | + ) { |
| 60 | + var callbacks = Parser.listeners.computeIfAbsent(type, (empty) -> new ArrayList<>()); |
| 61 | + |
| 62 | + callbacks.add(callback); |
| 63 | + } |
| 64 | +} |
0 commit comments