|
| 1 | +package shortbus; |
| 2 | + |
| 3 | +import java.lang.reflect.InvocationTargetException; |
| 4 | +import java.lang.reflect.Method; |
| 5 | +import java.lang.reflect.ParameterizedType; |
| 6 | +import java.lang.reflect.Type; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Map.Entry; |
| 9 | + |
| 10 | +import org.springframework.context.ApplicationContext; |
| 11 | + |
| 12 | +public class MediatorImpl implements Mediator { |
| 13 | + |
| 14 | + private ApplicationContext ctx; |
| 15 | + |
| 16 | + public MediatorImpl(ApplicationContext ctx) { |
| 17 | + this.ctx = ctx; |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public <T> Response<T> request(Request<T> request) { |
| 22 | + Response<T> response = new Response<>(); |
| 23 | + try { |
| 24 | + MediatorPlan<T> plan = new MediatorPlan<>(RequestHandler.class, "handle", request.getClass(), ctx); |
| 25 | + response.data = plan.invoke(request); |
| 26 | + } catch (Exception e) { |
| 27 | + response.exception = e; |
| 28 | + } |
| 29 | + return response; |
| 30 | + } |
| 31 | + |
| 32 | + class MediatorPlan<T> { |
| 33 | + Method handleMethod; |
| 34 | + Object handlerInstanceBuilder; |
| 35 | + |
| 36 | + public MediatorPlan(Class<?> handlerType, String handlerMethodName, Class<?> messageType, |
| 37 | + ApplicationContext context) throws NoSuchMethodException, SecurityException, ClassNotFoundException { |
| 38 | + handlerInstanceBuilder = getBean(handlerType, messageType, context); |
| 39 | + handleMethod = handlerInstanceBuilder.getClass().getDeclaredMethod(handlerMethodName, messageType); |
| 40 | + } |
| 41 | + |
| 42 | + private Object getBean(Class<?> handlerType, Class<?> messageType, ApplicationContext context) |
| 43 | + throws ClassNotFoundException { |
| 44 | + Map<String, ?> beans = context.getBeansOfType(handlerType); |
| 45 | + for (Entry<String, ?> entry : beans.entrySet()) { |
| 46 | + Class<?> clazz = entry.getValue().getClass(); |
| 47 | + Type[] interfaces = clazz.getGenericInterfaces(); |
| 48 | + for (Type interace : interfaces) { |
| 49 | + Type parameterType = ((ParameterizedType) interace).getActualTypeArguments()[0]; |
| 50 | + if (parameterType.equals(messageType)) { |
| 51 | + return entry.getValue(); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + throw new ClassNotFoundException("Handler not found. Did you forget to register this?"); |
| 57 | + } |
| 58 | + |
| 59 | + public T invoke(Request<T> request) |
| 60 | + throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { |
| 61 | + return (T) handleMethod.invoke(handlerInstanceBuilder, request); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments