From 99e1de14bcefa66c66e3957cdbfd934469c5d56c Mon Sep 17 00:00:00 2001 From: Yannik Bretschneider Date: Thu, 3 Jun 2021 16:36:50 +0200 Subject: [PATCH] feat: completed MessageDeserializer --- .../json/login/MessageDeserializer.java | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/main/java/uulm/teamname/marvelous/gamelibrary/json/login/MessageDeserializer.java b/src/main/java/uulm/teamname/marvelous/gamelibrary/json/login/MessageDeserializer.java index d33d411..fc65cac 100644 --- a/src/main/java/uulm/teamname/marvelous/gamelibrary/json/login/MessageDeserializer.java +++ b/src/main/java/uulm/teamname/marvelous/gamelibrary/json/login/MessageDeserializer.java @@ -1,2 +1,48 @@ -package uulm.teamname.marvelous.gamelibrary.json.login;public class MessageDeserializer { +package uulm.teamname.marvelous.gamelibrary.json.login; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.ObjectCodec; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; +import uulm.teamname.marvelous.gamelibrary.messages.*; + +import java.io.IOException; +import java.util.Optional; + +public class MessageDeserializer extends JsonDeserializer { + @Override + public BasicMessage deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { + ObjectCodec codec = p.getCodec(); + JsonNode node = codec.readTree(p); + + var type = Optional.of(node.get("messageType")) + .map(JsonNode::textValue) + .map(MessageType::valueOf); + if (type.isEmpty()) { + throw new IOException("MessageType does not exist"); + } + + BasicMessage message; + + switch (type.get()) { + case HELLO_CLIENT -> message = p.readValueAs(HelloClientMessage.class); + case HELLO_SERVER -> message = p.readValueAs(HelloServerMessage.class); + case ERROR -> message = p.readValueAs(ErrorMessage.class); + case PLAYER_READY -> message = p.readValueAs(PlayerReadyMessage.class); + case RECONNECT -> message = p.readValueAs(ReconnectMessage.class); + case GAME_ASSIGNMENT -> message = p.readValueAs(GameAssignmentMessage.class); + case GENERAL_ASSIGNMENT -> message = p.readValueAs(GeneralAssignmentMessage.class); + case CHARACTER_SELECTION -> message = p.readValueAs(CharacterSelectionMessage.class); + case CONFIRM_SELECTION -> message = p.readValueAs(ConfirmSelectionMessage.class); + case GAME_STRUCTURE -> message = p.readValueAs(GameStructureMessage.class); + case EVENTS -> message = p.readValueAs(EventMessage.class); + case REQUESTS -> message = p.readValueAs(RequestMessage.class); + case GOODBYE_CLIENT -> message = p.readValueAs(GoodbyeClientMessage.class); + default -> throw new IllegalStateException("No MessageType given, which should be impossible"); + } + + return message; + } }