All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pl.atom.spring.cqs.command.CommandHandlerProvider Maven / Gradle / Ivy

The newest version!
package pl.atom.spring.cqs.command;

import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;

import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * CommandHandlers provider for DefaultCommandBus Registers all CommandHandlers with their matching Commands Only one
 * CommandHandler is possible for one Command
 *
 * @author Artur Tomaszewski arttom
 */
class CommandHandlerProvider {

    private final Map, CommandHandler> commandHandlers;

    @SuppressWarnings("unchecked")
    CommandHandlerProvider(ApplicationContext context) {
        commandHandlers = context.getBeansOfType(CommandHandler.class)
            .values()
            .stream()
        .map(handler -> Map.entry(resolveCommand(handler), handler))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    }

    private void throwDuplicate(CommandHandler first, CommandHandler second) {
    }

    @SuppressWarnings("unchecked")
    private  Class resolveCommand(CommandHandler handler) {
        Class command = GenericTypeResolver.resolveTypeArgument(handler.getClass(), CommandHandler.class);
        return (Class) command;
    }

    @SuppressWarnings("unchecked")
     Optional> getCommandHandler(C command) {
        return Optional.ofNullable(commandHandlers.get(command.getClass()))
            .map(handler -> (CommandHandler) handler);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy