migrated to jackson
parent
2484dec68a
commit
c75cf03762
@ -0,0 +1,10 @@
|
|||||||
|
val implementation by configurations
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(Jackson.databind)
|
||||||
|
implementation(Jackson.module_parameter_names)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType<JavaCompile> {
|
||||||
|
options.compilerArgs.add("-parameters")
|
||||||
|
}
|
@ -1,273 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (C) 2011 Google Inc.
|
|
||||||
*
|
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
* you may not use this file except in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing, software
|
|
||||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
* See the License for the specific language governing permissions and
|
|
||||||
* limitations under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
package com.google.gson.typeadapters;
|
|
||||||
|
|
||||||
import com.google.gson.*;
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
|
||||||
import com.google.gson.stream.JsonReader;
|
|
||||||
import com.google.gson.stream.JsonWriter;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.LinkedHashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adapts values whose runtime type may differ from their declaration type. This
|
|
||||||
* is necessary when a field's type is not the same type that GSON should create
|
|
||||||
* when deserializing that field. For example, consider these types:
|
|
||||||
* <pre> {@code
|
|
||||||
* abstract class Shape {
|
|
||||||
* int x;
|
|
||||||
* int y;
|
|
||||||
* }
|
|
||||||
* class Circle extends Shape {
|
|
||||||
* int radius;
|
|
||||||
* }
|
|
||||||
* class Rectangle extends Shape {
|
|
||||||
* int width;
|
|
||||||
* int height;
|
|
||||||
* }
|
|
||||||
* class Diamond extends Shape {
|
|
||||||
* int width;
|
|
||||||
* int height;
|
|
||||||
* }
|
|
||||||
* class Drawing {
|
|
||||||
* Shape bottomShape;
|
|
||||||
* Shape topShape;
|
|
||||||
* }
|
|
||||||
* }</pre>
|
|
||||||
* <p>Without additional type information, the serialized JSON is ambiguous. Is
|
|
||||||
* the bottom shape in this drawing a rectangle or a diamond? <pre> {@code
|
|
||||||
* {
|
|
||||||
* "bottomShape": {
|
|
||||||
* "width": 10,
|
|
||||||
* "height": 5,
|
|
||||||
* "x": 0,
|
|
||||||
* "y": 0
|
|
||||||
* },
|
|
||||||
* "topShape": {
|
|
||||||
* "radius": 2,
|
|
||||||
* "x": 4,
|
|
||||||
* "y": 1
|
|
||||||
* }
|
|
||||||
* }}</pre>
|
|
||||||
* This class addresses this problem by adding type information to the
|
|
||||||
* serialized JSON and honoring that type information when the JSON is
|
|
||||||
* deserialized: <pre> {@code
|
|
||||||
* {
|
|
||||||
* "bottomShape": {
|
|
||||||
* "type": "Diamond",
|
|
||||||
* "width": 10,
|
|
||||||
* "height": 5,
|
|
||||||
* "x": 0,
|
|
||||||
* "y": 0
|
|
||||||
* },
|
|
||||||
* "topShape": {
|
|
||||||
* "type": "Circle",
|
|
||||||
* "radius": 2,
|
|
||||||
* "x": 4,
|
|
||||||
* "y": 1
|
|
||||||
* }
|
|
||||||
* }}</pre>
|
|
||||||
* Both the type field name ({@code "type"}) and the type labels ({@code
|
|
||||||
* "Rectangle"}) are configurable.
|
|
||||||
*
|
|
||||||
* <h3>Registering Types</h3>
|
|
||||||
* Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field
|
|
||||||
* name to the {@link #of} factory method. If you don't supply an explicit type
|
|
||||||
* field name, {@code "type"} will be used. <pre> {@code
|
|
||||||
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory
|
|
||||||
* = RuntimeTypeAdapterFactory.of(Shape.class, "type");
|
|
||||||
* }</pre>
|
|
||||||
* Next register all of your subtypes. Every subtype must be explicitly
|
|
||||||
* registered. This protects your application from injection attacks. If you
|
|
||||||
* don't supply an explicit type label, the type's simple name will be used.
|
|
||||||
* <pre> {@code
|
|
||||||
* shapeAdapterFactory.registerSubtype(Rectangle.class, "Rectangle");
|
|
||||||
* shapeAdapterFactory.registerSubtype(Circle.class, "Circle");
|
|
||||||
* shapeAdapterFactory.registerSubtype(Diamond.class, "Diamond");
|
|
||||||
* }</pre>
|
|
||||||
* Finally, register the type adapter factory in your application's GSON builder:
|
|
||||||
* <pre> {@code
|
|
||||||
* Gson gson = new GsonBuilder()
|
|
||||||
* .registerTypeAdapterFactory(shapeAdapterFactory)
|
|
||||||
* .create();
|
|
||||||
* }</pre>
|
|
||||||
* Like {@code GsonBuilder}, this API supports chaining: <pre> {@code
|
|
||||||
* RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class)
|
|
||||||
* .registerSubtype(Rectangle.class)
|
|
||||||
* .registerSubtype(Circle.class)
|
|
||||||
* .registerSubtype(Diamond.class);
|
|
||||||
* }</pre>
|
|
||||||
*
|
|
||||||
* <h3>Serialization and deserialization</h3>
|
|
||||||
* In order to serialize and deserialize a polymorphic object,
|
|
||||||
* you must specify the base type explicitly.
|
|
||||||
* <pre> {@code
|
|
||||||
* Diamond diamond = new Diamond();
|
|
||||||
* String json = gson.toJson(diamond, Shape.class);
|
|
||||||
* }</pre>
|
|
||||||
* And then:
|
|
||||||
* <pre> {@code
|
|
||||||
* Shape shape = gson.fromJson(json, Shape.class);
|
|
||||||
* }</pre>
|
|
||||||
*/
|
|
||||||
@SuppressWarnings("ALL")
|
|
||||||
public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
|
|
||||||
private final Class<?> baseType;
|
|
||||||
private final String typeFieldName;
|
|
||||||
private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<>();
|
|
||||||
private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<>();
|
|
||||||
private final boolean maintainType;
|
|
||||||
|
|
||||||
private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName, boolean maintainType) {
|
|
||||||
if (typeFieldName == null || baseType == null) {
|
|
||||||
throw new NullPointerException();
|
|
||||||
}
|
|
||||||
this.baseType = baseType;
|
|
||||||
this.typeFieldName = typeFieldName;
|
|
||||||
this.maintainType = maintainType;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new runtime type adapter using for {@code baseType} using {@code
|
|
||||||
* typeFieldName} as the type field name. Type field names are case sensitive.
|
|
||||||
* {@code maintainType} flag decide if the type will be stored in pojo or not.
|
|
||||||
*/
|
|
||||||
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName, boolean maintainType) {
|
|
||||||
return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, maintainType);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new runtime type adapter using for {@code baseType} using {@code
|
|
||||||
* typeFieldName} as the type field name. Type field names are case sensitive.
|
|
||||||
*/
|
|
||||||
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) {
|
|
||||||
return new RuntimeTypeAdapterFactory<>(baseType, typeFieldName, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new runtime type adapter for {@code baseType} using {@code "type"} as
|
|
||||||
* the type field name.
|
|
||||||
*/
|
|
||||||
public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) {
|
|
||||||
return new RuntimeTypeAdapterFactory<>(baseType, "type", false);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registers {@code type} identified by {@code label}. Labels are case
|
|
||||||
* sensitive.
|
|
||||||
*
|
|
||||||
* @throws IllegalArgumentException if either {@code type} or {@code label}
|
|
||||||
* have already been registered on this type adapter.
|
|
||||||
*/
|
|
||||||
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) {
|
|
||||||
if (type == null || label == null) {
|
|
||||||
throw new NullPointerException();
|
|
||||||
}
|
|
||||||
if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) {
|
|
||||||
throw new IllegalArgumentException("types and labels must be unique");
|
|
||||||
}
|
|
||||||
labelToSubtype.put(label, type);
|
|
||||||
subtypeToLabel.put(type, label);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Registers {@code type} identified by its {@link Class#getSimpleName simple
|
|
||||||
* name}. Labels are case sensitive.
|
|
||||||
*
|
|
||||||
* @throws IllegalArgumentException if either {@code type} or its simple name
|
|
||||||
* have already been registered on this type adapter.
|
|
||||||
*/
|
|
||||||
public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
|
|
||||||
return registerSubtype(type, type.getSimpleName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
|
|
||||||
if (type.getRawType() != baseType) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class);
|
|
||||||
final Map<String, TypeAdapter<?>> labelToDelegate
|
|
||||||
= new LinkedHashMap<>();
|
|
||||||
final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate
|
|
||||||
= new LinkedHashMap<>();
|
|
||||||
for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
|
|
||||||
TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
|
|
||||||
labelToDelegate.put(entry.getKey(), delegate);
|
|
||||||
subtypeToDelegate.put(entry.getValue(), delegate);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new TypeAdapter<R>() {
|
|
||||||
@Override public R read(JsonReader in) throws IOException {
|
|
||||||
JsonElement jsonElement = jsonElementAdapter.read(in);
|
|
||||||
JsonElement labelJsonElement;
|
|
||||||
if (maintainType) {
|
|
||||||
labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
|
|
||||||
} else {
|
|
||||||
labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (labelJsonElement == null) {
|
|
||||||
throw new JsonParseException("cannot deserialize " + baseType
|
|
||||||
+ " because it does not define a field named " + typeFieldName);
|
|
||||||
}
|
|
||||||
String label = labelJsonElement.getAsString();
|
|
||||||
@SuppressWarnings("unchecked") // registration requires that subtype extends T
|
|
||||||
TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
|
|
||||||
if (delegate == null) {
|
|
||||||
throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
|
|
||||||
+ label + "; did you forget to register a subtype?");
|
|
||||||
}
|
|
||||||
return delegate.fromJsonTree(jsonElement);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override public void write(JsonWriter out, R value) throws IOException {
|
|
||||||
Class<?> srcType = value.getClass();
|
|
||||||
String label = subtypeToLabel.get(srcType);
|
|
||||||
@SuppressWarnings("unchecked") // registration requires that subtype extends T
|
|
||||||
TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
|
|
||||||
if (delegate == null) {
|
|
||||||
throw new JsonParseException("cannot serialize " + srcType.getName()
|
|
||||||
+ "; did you forget to register a subtype?");
|
|
||||||
}
|
|
||||||
JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
|
|
||||||
|
|
||||||
if (maintainType) {
|
|
||||||
jsonElementAdapter.write(out, jsonObject);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonObject clone = new JsonObject();
|
|
||||||
|
|
||||||
if (jsonObject.has(typeFieldName)) {
|
|
||||||
throw new JsonParseException("cannot serialize " + srcType.getName()
|
|
||||||
+ " because it already defines a field named " + typeFieldName);
|
|
||||||
}
|
|
||||||
clone.add(typeFieldName, new JsonPrimitive(label));
|
|
||||||
|
|
||||||
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
|
|
||||||
clone.add(e.getKey(), e.getValue());
|
|
||||||
}
|
|
||||||
jsonElementAdapter.write(out, clone);
|
|
||||||
}
|
|
||||||
}.nullSafe();
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,7 @@
|
|||||||
|
package eu.jonahbauer.wizard.common.messages;
|
||||||
|
|
||||||
|
public class ParseException extends RuntimeException {
|
||||||
|
public ParseException(Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
}
|
@ -1,25 +1,23 @@
|
|||||||
package eu.jonahbauer.wizard.common.messages.client;
|
package eu.jonahbauer.wizard.common.messages.client;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.google.gson.GsonBuilder;
|
import eu.jonahbauer.wizard.common.messages.ParseException;
|
||||||
import com.google.gson.JsonParseException;
|
|
||||||
import eu.jonahbauer.wizard.common.messages.player.PlayerMessage;
|
import eu.jonahbauer.wizard.common.messages.player.PlayerMessage;
|
||||||
import eu.jonahbauer.wizard.common.util.SealedClassTypeAdapterFactory;
|
import eu.jonahbauer.wizard.common.util.SerializationUtil;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.SneakyThrows;
|
||||||
|
|
||||||
@EqualsAndHashCode
|
@EqualsAndHashCode
|
||||||
public abstract sealed class ClientMessage permits CreateSessionMessage, InteractionMessage, JoinSessionMessage, LeaveSessionMessage, ReadyMessage, RejoinMessage {
|
public abstract sealed class ClientMessage permits CreateSessionMessage, InteractionMessage, JoinSessionMessage, LeaveSessionMessage, ReadyMessage, RejoinMessage {
|
||||||
private static final Gson GSON = new GsonBuilder()
|
private static final ObjectMapper MAPPER = SerializationUtil.newObjectMapper(ClientMessage.class, PlayerMessage.class);
|
||||||
.registerTypeAdapterFactory(SealedClassTypeAdapterFactory.of(ClientMessage.class, "Message"))
|
|
||||||
.registerTypeAdapterFactory(SealedClassTypeAdapterFactory.of(PlayerMessage.class, "Message"))
|
|
||||||
.create();
|
|
||||||
|
|
||||||
public static ClientMessage parse(String json) throws JsonParseException {
|
public static ClientMessage parse(String json) throws ParseException {
|
||||||
return GSON.fromJson(json, ClientMessage.class);
|
return SerializationUtil.parse(json, MAPPER, ClientMessage.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@SneakyThrows
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return GSON.toJson(this, ClientMessage.class);
|
return MAPPER.writeValueAsString(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,23 +1,22 @@
|
|||||||
package eu.jonahbauer.wizard.common.messages.observer;
|
package eu.jonahbauer.wizard.common.messages.observer;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.google.gson.GsonBuilder;
|
import eu.jonahbauer.wizard.common.messages.ParseException;
|
||||||
import com.google.gson.JsonParseException;
|
import eu.jonahbauer.wizard.common.util.SerializationUtil;
|
||||||
import eu.jonahbauer.wizard.common.util.SealedClassTypeAdapterFactory;
|
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.SneakyThrows;
|
||||||
|
|
||||||
@EqualsAndHashCode
|
@EqualsAndHashCode
|
||||||
public abstract sealed class ObserverMessage permits CardMessage, HandMessage, PredictionMessage, ScoreMessage, StateMessage, TimeoutMessage, TrickMessage, TrumpMessage, UserInputMessage {
|
public abstract sealed class ObserverMessage permits CardMessage, HandMessage, PredictionMessage, ScoreMessage, StateMessage, TimeoutMessage, TrickMessage, TrumpMessage, UserInputMessage {
|
||||||
private static final Gson GSON = new GsonBuilder()
|
private static final ObjectMapper MAPPER = SerializationUtil.newObjectMapper(ObserverMessage.class);
|
||||||
.registerTypeAdapterFactory(SealedClassTypeAdapterFactory.of(ObserverMessage.class, "Message"))
|
|
||||||
.create();
|
|
||||||
|
|
||||||
public static ObserverMessage parse(String json) throws JsonParseException {
|
public static ObserverMessage parse(String json) throws ParseException {
|
||||||
return GSON.fromJson(json, ObserverMessage.class);
|
return SerializationUtil.parse(json, MAPPER, ObserverMessage.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@SneakyThrows
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return GSON.toJson(this, ObserverMessage.class);
|
return MAPPER.writeValueAsString(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,23 +1,22 @@
|
|||||||
package eu.jonahbauer.wizard.common.messages.player;
|
package eu.jonahbauer.wizard.common.messages.player;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.google.gson.GsonBuilder;
|
import eu.jonahbauer.wizard.common.messages.ParseException;
|
||||||
import com.google.gson.JsonParseException;
|
import eu.jonahbauer.wizard.common.util.SerializationUtil;
|
||||||
import eu.jonahbauer.wizard.common.util.SealedClassTypeAdapterFactory;
|
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.SneakyThrows;
|
||||||
|
|
||||||
@EqualsAndHashCode
|
@EqualsAndHashCode
|
||||||
public abstract sealed class PlayerMessage permits ContinueMessage, JuggleMessage, PickTrumpMessage, PlayCardMessage, PredictMessage {
|
public abstract sealed class PlayerMessage permits ContinueMessage, JuggleMessage, PickTrumpMessage, PlayCardMessage, PredictMessage {
|
||||||
private static final Gson GSON = new GsonBuilder()
|
private static final ObjectMapper MAPPER = SerializationUtil.newObjectMapper(PlayerMessage.class);
|
||||||
.registerTypeAdapterFactory(SealedClassTypeAdapterFactory.of(PlayerMessage.class, "Message"))
|
|
||||||
.create();
|
|
||||||
|
|
||||||
public static PlayerMessage parse(String json) throws JsonParseException {
|
public static PlayerMessage parse(String json) throws ParseException {
|
||||||
return GSON.fromJson(json, PlayerMessage.class);
|
return SerializationUtil.parse(json, MAPPER, PlayerMessage.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@SneakyThrows
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return GSON.toJson(this);
|
return MAPPER.writeValueAsString(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,25 +1,23 @@
|
|||||||
package eu.jonahbauer.wizard.common.messages.server;
|
package eu.jonahbauer.wizard.common.messages.server;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.google.gson.GsonBuilder;
|
import eu.jonahbauer.wizard.common.messages.ParseException;
|
||||||
import com.google.gson.JsonParseException;
|
|
||||||
import eu.jonahbauer.wizard.common.messages.observer.ObserverMessage;
|
import eu.jonahbauer.wizard.common.messages.observer.ObserverMessage;
|
||||||
import eu.jonahbauer.wizard.common.util.SealedClassTypeAdapterFactory;
|
import eu.jonahbauer.wizard.common.util.SerializationUtil;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
import lombok.SneakyThrows;
|
||||||
|
|
||||||
@EqualsAndHashCode
|
@EqualsAndHashCode
|
||||||
public abstract sealed class ServerMessage permits AckMessage, GameMessage, KickVotedMessage, KickedMessage, NackMessage, PlayerLeftMessage, PlayerModifiedMessage, SessionJoinedMessage, SessionListMessage, SessionModifiedMessage, SessionRemovedMessage, StartingGameMessage {
|
public abstract sealed class ServerMessage permits AckMessage, GameMessage, KickVotedMessage, KickedMessage, NackMessage, PlayerLeftMessage, PlayerModifiedMessage, SessionJoinedMessage, SessionListMessage, SessionModifiedMessage, SessionRemovedMessage, StartingGameMessage {
|
||||||
private static final Gson GSON = new GsonBuilder()
|
private static final ObjectMapper MAPPER = SerializationUtil.newObjectMapper(ServerMessage.class, ObserverMessage.class);
|
||||||
.registerTypeAdapterFactory(SealedClassTypeAdapterFactory.of(ServerMessage.class, "Message"))
|
|
||||||
.registerTypeAdapterFactory(SealedClassTypeAdapterFactory.of(ObserverMessage.class, "Message"))
|
|
||||||
.create();
|
|
||||||
|
|
||||||
public static ServerMessage parse(String json) throws JsonParseException {
|
public static ServerMessage parse(String json) throws ParseException {
|
||||||
return GSON.fromJson(json, ServerMessage.class);
|
return SerializationUtil.parse(json, MAPPER, ServerMessage.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@SneakyThrows
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return GSON.toJson(this, ServerMessage.class);
|
return MAPPER.writeValueAsString(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,62 +0,0 @@
|
|||||||
package eu.jonahbauer.wizard.common.util;
|
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
|
||||||
import com.google.gson.TypeAdapter;
|
|
||||||
import com.google.gson.TypeAdapterFactory;
|
|
||||||
import com.google.gson.reflect.TypeToken;
|
|
||||||
import com.google.gson.typeadapters.RuntimeTypeAdapterFactory;
|
|
||||||
import org.jetbrains.annotations.Nullable;
|
|
||||||
|
|
||||||
import java.lang.reflect.Modifier;
|
|
||||||
import java.util.Locale;
|
|
||||||
|
|
||||||
public final class SealedClassTypeAdapterFactory<T> implements TypeAdapterFactory {
|
|
||||||
private final RuntimeTypeAdapterFactory<T> factory;
|
|
||||||
|
|
||||||
public static <T> SealedClassTypeAdapterFactory<T> of(Class<T> clazz) {
|
|
||||||
return new SealedClassTypeAdapterFactory<>(clazz, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static <T> SealedClassTypeAdapterFactory<T> of(Class<T> clazz, @Nullable String suffix) {
|
|
||||||
return new SealedClassTypeAdapterFactory<>(clazz, suffix);
|
|
||||||
}
|
|
||||||
|
|
||||||
private SealedClassTypeAdapterFactory(Class<T> clazz, @Nullable String suffix) {
|
|
||||||
factory = RuntimeTypeAdapterFactory.of(clazz);
|
|
||||||
register(clazz, suffix);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void register(Class<? extends T> clazz, String suffix) {
|
|
||||||
for (Class<?> subclass : clazz.getPermittedSubclasses()) {
|
|
||||||
int modifiers = subclass.getModifiers();
|
|
||||||
if (Modifier.isFinal(modifiers) || subclass.isSealed() && !Modifier.isAbstract(modifiers)) {
|
|
||||||
String name = subclass.getSimpleName();
|
|
||||||
|
|
||||||
// remove suffix
|
|
||||||
if (suffix != null) {
|
|
||||||
if (name.endsWith(suffix)) name = name.substring(0, name.length() - suffix.length());
|
|
||||||
}
|
|
||||||
|
|
||||||
// transform camelCast to snake_case
|
|
||||||
name = name.replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase(Locale.ROOT);
|
|
||||||
|
|
||||||
factory.registerSubtype(subclass.asSubclass(clazz), name);
|
|
||||||
}
|
|
||||||
if (subclass.isSealed()) {
|
|
||||||
register(subclass.asSubclass(clazz), suffix);
|
|
||||||
} else if (!Modifier.isFinal(modifiers)) {
|
|
||||||
//subclass is non-sealed
|
|
||||||
throw new IllegalArgumentException(
|
|
||||||
"SealedClassTypeAdapterFactory does not support a type hierarchy that contains non-sealed classes. " +
|
|
||||||
"Found non-sealed class " + subclass.getName()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public <S> TypeAdapter<S> create(Gson gson, TypeToken<S> type) {
|
|
||||||
return factory.create(gson, type);
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,87 @@
|
|||||||
|
package eu.jonahbauer.wizard.common.util;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.cfg.MapperConfig;
|
||||||
|
import com.fasterxml.jackson.databind.introspect.*;
|
||||||
|
import com.fasterxml.jackson.databind.jsontype.NamedType;
|
||||||
|
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||||
|
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
|
||||||
|
import eu.jonahbauer.wizard.common.messages.ParseException;
|
||||||
|
import lombok.experimental.UtilityClass;
|
||||||
|
|
||||||
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
@UtilityClass
|
||||||
|
public class SerializationUtil {
|
||||||
|
public static ObjectMapper newObjectMapper(Class<?>...classes) {
|
||||||
|
var mapper = new ObjectMapper()
|
||||||
|
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES))
|
||||||
|
.registerModule(new SimpleModule() {
|
||||||
|
@Override
|
||||||
|
public void setupModule(SetupContext context) {
|
||||||
|
super.setupModule(context);
|
||||||
|
for (Class<?> clazz : classes) {
|
||||||
|
context.setMixInAnnotations(clazz, Mixin.class);
|
||||||
|
}
|
||||||
|
context.insertAnnotationIntrospector(new NopAnnotationIntrospector() {
|
||||||
|
@Override
|
||||||
|
public JsonCreator.Mode findCreatorAnnotation(MapperConfig<?> config, Annotated ann) {
|
||||||
|
if (ann instanceof AnnotatedConstructor con) {
|
||||||
|
var declaringClass = con.getDeclaringClass();
|
||||||
|
for (Class<?> clazz : classes) {
|
||||||
|
if (clazz.isAssignableFrom(declaringClass)) {
|
||||||
|
return JsonCreator.Mode.PROPERTIES;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.findCreatorAnnotation(config, ann);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
for (Class<?> clazz : classes) {
|
||||||
|
registerSubtypes(mapper, clazz);
|
||||||
|
}
|
||||||
|
|
||||||
|
return mapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void registerSubtypes(ObjectMapper objectMapper, Class<?> clazz) {
|
||||||
|
if (!clazz.isSealed()) throw new IllegalArgumentException();
|
||||||
|
|
||||||
|
var suffix = "Message";
|
||||||
|
for (Class<?> subclass : clazz.getPermittedSubclasses()) {
|
||||||
|
int modifiers = subclass.getModifiers();
|
||||||
|
|
||||||
|
if (Modifier.isFinal(modifiers) || subclass.isSealed() && !Modifier.isAbstract(modifiers)) {
|
||||||
|
var name = subclass.getSimpleName();
|
||||||
|
if (name.endsWith(suffix)) name = name.substring(0, name.length() - suffix.length());
|
||||||
|
name = name.replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase(Locale.ROOT);
|
||||||
|
|
||||||
|
objectMapper.registerSubtypes(new NamedType(subclass, name));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subclass.isSealed()) {
|
||||||
|
registerSubtypes(objectMapper, subclass);
|
||||||
|
} else if (!Modifier.isFinal(modifiers)) {
|
||||||
|
throw new IllegalArgumentException("Non-sealed classes are not supported.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T parse(String json, ObjectMapper objectMapper, Class<T> clazz) throws ParseException {
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, clazz);
|
||||||
|
} catch (JsonProcessingException e) {
|
||||||
|
throw new ParseException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
|
||||||
|
private static class Mixin {}
|
||||||
|
}
|
Loading…
Reference in New Issue