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

pl.atom.spring.cqs.query.QueryHandlerProvider Maven / Gradle / Ivy

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

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

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

/**
 * QueryHandlers provider for DefaultQueryBus Registers all QueryHandlers with their matching Queries Only one
 * QueryHandler is possible for one Query
 *
 * @author Artur Tomaszewski arttom
 */
class QueryHandlerProvider {

    private final Map>, QueryHandler>> queryHandlers;

    @SuppressWarnings("unchecked")
    QueryHandlerProvider(ApplicationContext context) {
        queryHandlers = context.getBeansOfType(QueryHandler.class)
            .values()
            .stream()
            .map(handler -> Map.entry(resolveQuery(handler), handler))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    }

    @SuppressWarnings("unchecked")
    private > Class resolveQuery(QueryHandler handler) {
        Class[] parameters = GenericTypeResolver.resolveTypeArguments(handler.getClass(), QueryHandler.class);
        if (parameters == null) {
            throw new WrongQueryHandlerImplementationException(handler);
        }
        return (Class) parameters[1];
    }

    @SuppressWarnings("unchecked")
    > Optional> getQueryHandler(Q query) {
        return Optional.ofNullable(queryHandlers.get(query.getClass()))
            .map(handler -> (QueryHandler) handler);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy