1 package com.foxinmy.weixin4j.dispatcher;
2
3 import com.foxinmy.weixin4j.handler.WeixinMessageHandler;
4 import com.foxinmy.weixin4j.interceptor.WeixinMessageInterceptor;
5 import com.foxinmy.weixin4j.request.WeixinMessage;
6 import com.foxinmy.weixin4j.request.WeixinRequest;
7 import com.foxinmy.weixin4j.response.WeixinResponse;
8
9 import io.netty.channel.ChannelHandlerContext;
10 import io.netty.util.internal.logging.InternalLogger;
11 import io.netty.util.internal.logging.InternalLoggerFactory;
12
13
14
15
16
17
18
19
20
21
22
23 public class MessageHandlerExecutor {
24
25 private final InternalLogger logger = InternalLoggerFactory
26 .getInstance(getClass());
27
28
29
30 private final WeixinMessageHandler messageHandler;
31
32
33
34
35 private final WeixinMessageInterceptor[] messageInterceptors;
36
37
38
39 private final ChannelHandlerContext context;
40
41 private int interceptorIndex = -1;
42
43 public MessageHandlerExecutor(ChannelHandlerContext context,
44 WeixinMessageHandler messageHandler,
45 WeixinMessageInterceptor[] messageInterceptors) {
46 this.context = context;
47 this.messageHandler = messageHandler;
48 this.messageInterceptors = messageInterceptors;
49 }
50
51 public WeixinMessageHandler getMessageHandler() {
52 return messageHandler;
53 }
54
55
56
57
58
59
60
61
62
63
64
65 public boolean applyPreHandle(WeixinRequest request, WeixinMessage message){
66 if (messageInterceptors != null) {
67 for (int i = 0; i < messageInterceptors.length; i++) {
68 WeixinMessageInterceptor interceptor = messageInterceptors[i];
69 if (!interceptor.preHandle(context, request, message,
70 messageHandler)) {
71 triggerAfterCompletion(request, null, message, null);
72 return false;
73 }
74 this.interceptorIndex = i;
75 }
76 }
77 return true;
78 }
79
80
81
82
83
84
85
86
87
88
89
90
91 public void applyPostHandle(WeixinRequest request, WeixinResponse response,
92 WeixinMessage message){
93 if (messageInterceptors == null) {
94 return;
95 }
96 for (int i = messageInterceptors.length - 1; i >= 0; i--) {
97 WeixinMessageInterceptor interceptor = messageInterceptors[i];
98 interceptor.postHandle(context, request, response, message,
99 messageHandler);
100 }
101 }
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116 public void triggerAfterCompletion(WeixinRequest request,
117 WeixinResponse response, WeixinMessage message, Exception exception)
118 {
119 if (messageInterceptors == null) {
120 return;
121 }
122 for (int i = this.interceptorIndex; i >= 0; i--) {
123 WeixinMessageInterceptor interceptor = messageInterceptors[i];
124 try {
125 interceptor.afterCompletion(context, request, response,
126 message, messageHandler, exception);
127 } catch (Exception e) {
128 logger.error(
129 "MessageInterceptor.afterCompletion threw exception", e);
130 }
131 }
132 }
133 }