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