pl.atom.spring.cqs.query.QueryHandlerProvider Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cqs-spring-boot-starter Show documentation
Show all versions of cqs-spring-boot-starter Show documentation
Easy way to follow CQS principle with spring-boot
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, ? extends Query>>> 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, Q> 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, Q>) handler);
}
}