diff --git a/libLauncher/src/main/java/ru/gravit/utils/ProviderMap.java b/libLauncher/src/main/java/ru/gravit/utils/ProviderMap.java new file mode 100644 index 00000000..ce32eef1 --- /dev/null +++ b/libLauncher/src/main/java/ru/gravit/utils/ProviderMap.java @@ -0,0 +1,34 @@ +package ru.gravit.utils; + +import ru.gravit.utils.helper.VerifyHelper; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +public class ProviderMap { + protected final Map> PROVIDERS = new ConcurrentHashMap<>(4); + protected boolean registredProviders = false; + + + public void registerProvider(String name, Class adapter) { + VerifyHelper.verifyIDName(name); + VerifyHelper.putIfAbsent(PROVIDERS, name, Objects.requireNonNull(adapter, "adapter"), + String.format("Protect handler has been already registered: '%s'", name)); + } + + public Class getProviderClass(String name) { + return PROVIDERS.get(name); + } + + public String getProviderName(Class clazz) { + for (Map.Entry> e : PROVIDERS.entrySet()) { + if (e.getValue().equals(clazz)) return e.getKey(); + } + return null; + } + public Class unregisterProvider(String name) + { + return PROVIDERS.remove(name); + } +} diff --git a/libLauncher/src/main/java/ru/gravit/utils/UniversalJsonAdapter.java b/libLauncher/src/main/java/ru/gravit/utils/UniversalJsonAdapter.java new file mode 100644 index 00000000..4cd66670 --- /dev/null +++ b/libLauncher/src/main/java/ru/gravit/utils/UniversalJsonAdapter.java @@ -0,0 +1,41 @@ +package ru.gravit.utils; + +import com.google.gson.*; +import ru.gravit.utils.helper.LogHelper; + +import java.lang.reflect.Type; + +public class UniversalJsonAdapter implements JsonSerializer, JsonDeserializer { + public ProviderMap providerMap; + public String PROP_NAME = "type"; + + public UniversalJsonAdapter(ProviderMap providerMap) { + this.providerMap = providerMap; + } + + public UniversalJsonAdapter(ProviderMap providerMap, String PROP_NAME) { + this.providerMap = providerMap; + this.PROP_NAME = PROP_NAME; + } + + public R deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + String typename = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString(); + Class cls = providerMap.getProviderClass(typename); + if (cls == null) { + LogHelper.error("AuthHandler %s not found", typename); + return null; + } + return context.deserialize(json, cls); + } + + @Override + public JsonElement serialize(R src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject jo = context.serialize(src).getAsJsonObject(); + + @SuppressWarnings("unchecked") + String classPath = providerMap.getProviderName((Class) src.getClass()); + jo.add(PROP_NAME, new JsonPrimitive(classPath)); + + return jo; + } +}