代码设计:从Socket到自定义处理程序类

时间:2017-03-02 12:03:29

标签: java json generics gson guice

我有一个Java的Socket-Server。此套接字将接收具有特定结构的json字符串。

{
    "command": "test",
    "name": "Hallo Welt"
}

我无法改变这种结构。 "命令"的值将声明内容的类型。

从socket接收到这个之后,我想调用不同的处理程序来处理这些不同的命令:

  • 命令"测试" > TestHandler实现了CommandHandler
  • 命令" foo" > FooHandler实现了CommandHandler

如何将json转换为对象并将对象绑定到特定处理程序?

这是我目前的做法: 我有一个名为BaseCommand的模型类,它包含一个枚举命令字段。

class BaseCommand {
    public CommandType command;
}

class TestCommand extends BaseCommand {
    public String name;
}

使用GSON,我将JSON解析为BaseCommand类。 之后我可以读取命令类型。

我声明一个ENUM将命令类型映射到处理程序:

enum CommandType {
    test(TestHandler.class),
    foo(FooHandler.class);

    public final Class<? extends CommandHandler> handlerClass;        

    public CommandTypes(Class<? extends CommandHandler> handlerClass) {
        this.handlerClass = handlerClass;
    }
}

我的处理程序正在实现此界面:

public interface CommandHandler<T extends BaseCommand> {
    void handle(T command);
}

现在我有命令类型枚举,并通过Google Guices MapBinder我可以让Handler实例来处理请求。这工作

// in class ...
private final Map<CommandType, CommandHandler> handlers;

@Inject ClassName(Map<CommandType, CommandHandler> handlers) {
    this.handlers = handlers;
}

// in converter method
private void convert(String json) {
    BaseCommand baseCommand = GSONHelper().fromJson(json, BaseCommand.class);

    // How can I get the CommandModel? 
    // If the commandType is "test" how can I parse TestCommand automatically?

    ??? commandModel = GSONHelper().fromJson(json, ???);

    handlers.get(baseCommand.command).handle(commandModel);
}

有谁知道我的问题的解决方案? 或者完全不同的方法呢?

最好的问候,迈克尔

1 个答案:

答案 0 :(得分:1)

  

我如何获得CommandModel?
  如果commandType是&#34; test&#34;我该如何自动解析TestCommand?

您可以使用TypeAdapterFactory以最准确,最灵活的方式获取最合适的类型适配器。下面的示例与您的类命名略有不同,但我认为这对您来说不是一个大问题。所以,让我们假设你有以下命令参数DTO声明:

abstract class AbstractCommandDto {

    final String command = null;

}
final class HelloCommandDto
        extends AbstractCommandDto {

    final String name = null;

}

现在,您可以创建一个特殊的TypeAdapterFactory来进行预测,以通过命令参数name确定传入的命令。它可能看起来很复杂,但实际上TypeAdapterFactory并不难实现。请注意,JsonDeserializer可能是您的另一个选项,但除非您将其deserialize()方法委托给另一个支持Gson实例,否则您将失去自动反序列化。

final class AbstractCommandDtoTypeAdapterFactory
        implements TypeAdapterFactory {

    // The factory handles no state and can be instantiated once    
    private static final TypeAdapterFactory abstractCommandDtoTypeAdapterFactory = new AbstractCommandDtoTypeAdapterFactory();

    // Type tokens are used to define type information and are perfect value types so they can be instantiated once as well
    private static final TypeToken<CommandProbingDto> abstractCommandProbingDtoTypeToken = new TypeToken<CommandProbingDto>() {
    };

    private static final TypeToken<HelloCommandDto> helloCommandDtoTypeToken = new TypeToken<HelloCommandDto>() {
    };

    private AbstractCommandDtoTypeAdapterFactory() {
    }

    static TypeAdapterFactory getAbstractCommandDtoTypeAdapterFactory() {
        return abstractCommandDtoTypeAdapterFactory;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        // First, check if the incoming type is AbstractCommandDto
        if ( AbstractCommandDto.class.isAssignableFrom(typeToken.getRawType()) ) {
            // If yes, then build a special type adapter for the concrete type
            final TypeAdapter<AbstractCommandDto> abstractCommandDtoTypeAdapter = new AbstractCommandDtoTypeAdapter(
                    gson,
                    gson.getDelegateAdapter(this, abstractCommandProbingDtoTypeToken),
                    (commandName, jsonObject) -> deserialize(gson, commandName, jsonObject),
                    dto -> getTypeAdapter(gson, dto)
            );
            // Some cheating for javac...
            @SuppressWarnings("unchecked")
            final TypeAdapter<T> typeAdapter = (TypeAdapter<T>) abstractCommandDtoTypeAdapter;
            return typeAdapter;
        }
        // If it's something else, just let Gson pick up the next type adapter
        return null;
    }

    // Create an AbstractCommandDto instance out of a ready to use JsonObject (see the disadvantages about JSON trees below)
    private AbstractCommandDto deserialize(final Gson gson, final String commandName, final JsonObject jsonObject) {
        @SuppressWarnings("unchecked")
        final TypeToken<AbstractCommandDto> typeToken = (TypeToken<AbstractCommandDto>) resolve(commandName);
        final TypeAdapter<AbstractCommandDto> typeAdapter = gson.getDelegateAdapter(this, typeToken);
        return typeAdapter.fromJsonTree(jsonObject);
    }

    private TypeAdapter<AbstractCommandDto> getTypeAdapter(final Gson gson, final AbstractCommandDto dto) {
        @SuppressWarnings("unchecked")
        final Class<AbstractCommandDto> clazz = (Class<AbstractCommandDto>) dto.getClass();
        return gson.getDelegateAdapter(this, TypeToken.get(clazz));
    }

    // Or any other way to resolve the class. This is just for simplicity and can be even extract elsewhere from the type adapter factory class
    private static TypeToken<? extends AbstractCommandDto> resolve(final String commandName)
            throws IllegalArgumentException {
        switch ( commandName ) {
        case "hello":
            return helloCommandDtoTypeToken;
        default:
            throw new IllegalArgumentException("Cannot handle " + commandName);
        }
    }

    private static final class AbstractCommandDtoTypeAdapter
            extends TypeAdapter<AbstractCommandDto> {

        private final Gson gson;
        private final TypeAdapter<CommandProbingDto> probingTypeAdapter;
        private final BiFunction<? super String, ? super JsonObject, ? extends AbstractCommandDto> commandNameToCommand;
        private final Function<? super AbstractCommandDto, ? extends TypeAdapter<AbstractCommandDto>> commandToTypeAdapter;

        private AbstractCommandDtoTypeAdapter(
                final Gson gson,
                final TypeAdapter<CommandProbingDto> probingTypeAdapter,
                final BiFunction<? super String, ? super JsonObject, ? extends AbstractCommandDto> commandNameToCommand,
                final Function<? super AbstractCommandDto, ? extends TypeAdapter<AbstractCommandDto>> commandToTypeAdapter
        ) {
            this.gson = gson;
            this.probingTypeAdapter = probingTypeAdapter;
            this.commandNameToCommand = commandNameToCommand;
            this.commandToTypeAdapter = commandToTypeAdapter;
        }

        @Override
        public void write(final JsonWriter out, final AbstractCommandDto dto)
                throws IOException {
            // Just pick up a delegated type adapter factory and use it
            // Or just throw an UnsupportedOperationException if you're not going to serialize command arguments
            final TypeAdapter<AbstractCommandDto> typeAdapter = commandToTypeAdapter.apply(dto);
            typeAdapter.write(out, dto);
        }

        @Override
        public AbstractCommandDto read(final JsonReader in) {
            // Here you can two ways:
            // * Either "cache" the whole JSON tree into memory (JsonElement, etc,) and simplify the command peeking
            // * Or analyze the JSON token stream in a more efficient and sophisticated way
            final JsonObject jsonObject = gson.fromJson(in, JsonObject.class);
            final CommandProbingDto commandProbingDto = probingTypeAdapter.fromJsonTree(jsonObject);
            // Or just jsonObject.get("command") and even throw abstractCommandDto, AbstractCommandProbingDto and all of it gets away
            final String commandName = commandProbingDto.command;
            return commandNameToCommand.apply(commandName, jsonObject);
        }

    }

    // A synthetic class just to obtain the command field
    // Gson cannot instantiate abstract classes like what AbstractCommandDto is 
    private static final class CommandProbingDto
            extends AbstractCommandDto {
    }

}

它是如何使用的:

public static void main(final String... args) {
    // Build a command DTO-aware Gson instance
    final Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(getAbstractCommandDtoTypeAdapterFactory())
            .create();
    // Build command registry
    final Map<Class<?>, Consumer<?>> commandRegistry = new LinkedHashMap<>();
    commandRegistry.put(HelloCommandDto.class, new HelloCommand());
    // Simulate and accept a request
    final AbstractCommandDto abstractCommandDto = gson.fromJson("{\"command\":\"hello\",\"name\":\"Welt\"}", AbstractCommandDto.class);
    // Resolve a command
    final Consumer<?> command = commandRegistry.get(abstractCommandDto.getClass());
    if ( command == null ) {
        throw new IllegalArgumentException("Cannot handle " + abstractCommandDto.command);
    }
    // Dispatch
    @SuppressWarnings("unchecked")
    final Consumer<AbstractCommandDto> castCommand = (Consumer<AbstractCommandDto>) command;
    castCommand.accept(abstractCommandDto);
    // Simulate a response
    System.out.println(gson.toJson(abstractCommandDto));
}

private static final class HelloCommand
        implements Consumer<HelloCommandDto> {

    @Override
    public void accept(final HelloCommandDto helloCommandDto) {
        System.out.println("Hallo " + helloCommandDto.name);
    }

}

输出:

  Hallo Welt