🎨 优化部分代码

This commit is contained in:
Binary Wang 2020-09-20 00:21:08 +08:00
parent 7261f23689
commit e00320dd1c
12 changed files with 200 additions and 228 deletions

View File

@ -27,13 +27,16 @@ public interface WxCpTpService {
* @param timestamp 时间戳 * @param timestamp 时间戳
* @param nonce 随机数 * @param nonce 随机数
* @param data 微信传输过来的数据有可能是echoStr有可能是xml消息 * @param data 微信传输过来的数据有可能是echoStr有可能是xml消息
* @return the boolean
*/ */
boolean checkSignature(String msgSignature, String timestamp, String nonce, String data); boolean checkSignature(String msgSignature, String timestamp, String nonce, String data);
/** /**
* 获取suite_access_token, 不强制刷新suite_access_token * 获取suite_access_token, 不强制刷新suite_access_token
* *
* @see #getSuiteAccessToken(boolean) * @return the suite access token
* @throws WxErrorException the wx error exception
* @see #getSuiteAccessToken(boolean) #getSuiteAccessToken(boolean)
*/ */
String getSuiteAccessToken() throws WxErrorException; String getSuiteAccessToken() throws WxErrorException;
@ -47,13 +50,17 @@ public interface WxCpTpService {
* </pre> * </pre>
* *
* @param forceRefresh 强制刷新 * @param forceRefresh 强制刷新
* @return the suite access token
* @throws WxErrorException the wx error exception
*/ */
String getSuiteAccessToken(boolean forceRefresh) throws WxErrorException; String getSuiteAccessToken(boolean forceRefresh) throws WxErrorException;
/** /**
* 获得suite_ticket,不强制刷新suite_ticket * 获得suite_ticket,不强制刷新suite_ticket
* *
* @see #getSuiteTicket(boolean) * @return the suite ticket
* @throws WxErrorException the wx error exception
* @see #getSuiteTicket(boolean) #getSuiteTicket(boolean)
*/ */
String getSuiteTicket() throws WxErrorException; String getSuiteTicket() throws WxErrorException;
@ -66,6 +73,8 @@ public interface WxCpTpService {
* </pre> * </pre>
* *
* @param forceRefresh 强制刷新 * @param forceRefresh 强制刷新
* @return the suite ticket
* @throws WxErrorException the wx error exception
*/ */
String getSuiteTicket(boolean forceRefresh) throws WxErrorException; String getSuiteTicket(boolean forceRefresh) throws WxErrorException;
@ -73,6 +82,8 @@ public interface WxCpTpService {
* 小程序登录凭证校验 * 小程序登录凭证校验
* *
* @param jsCode 登录时获取的 code * @param jsCode 登录时获取的 code
* @return the wx cp ma js code 2 session result
* @throws WxErrorException the wx error exception
*/ */
WxCpMaJsCode2SessionResult jsCode2Session(String jsCode) throws WxErrorException; WxCpMaJsCode2SessionResult jsCode2Session(String jsCode) throws WxErrorException;
@ -81,6 +92,8 @@ public interface WxCpTpService {
* *
* @param authCorpid 授权方corpid * @param authCorpid 授权方corpid
* @param permanentCode 永久授权码通过get_permanent_code获取 * @param permanentCode 永久授权码通过get_permanent_code获取
* @return the corp token
* @throws WxErrorException the wx error exception
*/ */
WxAccessToken getCorpToken(String authCorpid, String permanentCode) throws WxErrorException; WxAccessToken getCorpToken(String authCorpid, String permanentCode) throws WxErrorException;
@ -88,7 +101,8 @@ public interface WxCpTpService {
* 获取企业永久授权码 . * 获取企业永久授权码 .
* *
* @param authCode . * @param authCode .
* @return . * @return . permanent code
* @throws WxErrorException the wx error exception
*/ */
@Deprecated @Deprecated
WxCpTpCorp getPermanentCode(String authCode) throws WxErrorException; WxCpTpCorp getPermanentCode(String authCode) throws WxErrorException;
@ -99,13 +113,11 @@ public interface WxCpTpService {
* 原来的方法实现不全 * 原来的方法实现不全
* </pre> * </pre>
* *
* @param authCode * @param authCode the auth code
* @return * @return permanent code info
* * @throws WxErrorException the wx error exception
* @author yuan * @author yuan
* @since 2020-03-18 * @since 2020 -03-18
*
* @throws WxErrorException
*/ */
WxCpTpPermanentCodeInfo getPermanentCodeInfo(String authCode) throws WxErrorException; WxCpTpPermanentCodeInfo getPermanentCodeInfo(String authCode) throws WxErrorException;
@ -113,28 +125,31 @@ public interface WxCpTpService {
* <pre> * <pre>
* 获取预授权链接 * 获取预授权链接
* </pre> * </pre>
*
* @param redirectUri 授权完成后的回调网址 * @param redirectUri 授权完成后的回调网址
* @param state a-zA-Z0-9的参数值不超过128个字节用于第三方自行校验session防止跨域攻击 * @param state a-zA-Z0-9的参数值不超过128个字节用于第三方自行校验session防止跨域攻击
* @return * @return pre auth url
* @throws WxErrorException * @throws WxErrorException the wx error exception
*/ */
String getPreAuthUrl(String redirectUri,String state) throws WxErrorException; String getPreAuthUrl(String redirectUri, String state) throws WxErrorException;
/** /**
* 获取企业的授权信息 * 获取企业的授权信息
* *
* @param authCorpId 授权企业的corpId * @param authCorpId 授权企业的corpId
* @param permanentCode 授权企业的永久授权码 * @param permanentCode 授权企业的永久授权码
* @return * @return auth info
* @throws WxErrorException * @throws WxErrorException the wx error exception
*/ */
WxCpTpAuthInfo getAuthInfo(String authCorpId,String permanentCode) throws WxErrorException; WxCpTpAuthInfo getAuthInfo(String authCorpId, String permanentCode) throws WxErrorException;
/** /**
* 当本Service没有实现某个API的时候可以用这个针对所有微信API中的GET请求. * 当本Service没有实现某个API的时候可以用这个针对所有微信API中的GET请求.
* *
* @param url 接口地址 * @param url 接口地址
* @param queryParam 请求参数 * @param queryParam 请求参数
* @return the string
* @throws WxErrorException the wx error exception
*/ */
String get(String url, String queryParam) throws WxErrorException; String get(String url, String queryParam) throws WxErrorException;
@ -143,6 +158,8 @@ public interface WxCpTpService {
* *
* @param url 接口地址 * @param url 接口地址
* @param postData 请求body字符串 * @param postData 请求body字符串
* @return the string
* @throws WxErrorException the wx error exception
*/ */
String post(String url, String postData) throws WxErrorException; String post(String url, String postData) throws WxErrorException;
@ -153,11 +170,13 @@ public interface WxCpTpService {
* 可以参考{@link MediaUploadRequestExecutor}的实现方法 * 可以参考{@link MediaUploadRequestExecutor}的实现方法
* </pre> * </pre>
* *
* @param <T> 请求值类型
* @param <E> 返回值类型
* @param executor 执行器 * @param executor 执行器
* @param uri 请求地址 * @param uri 请求地址
* @param data 参数 * @param data 参数
* @param <T> 请求值类型 * @return the t
* @param <E> 返回值类型 * @throws WxErrorException the wx error exception
*/ */
<T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException; <T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws WxErrorException;
@ -189,7 +208,7 @@ public interface WxCpTpService {
/** /**
* 获取WxMpConfigStorage 对象. * 获取WxMpConfigStorage 对象.
* *
* @return WxMpConfigStorage * @return WxMpConfigStorage wx cp tp config storage
*/ */
WxCpTpConfigStorage getWxCpTpConfigStorage(); WxCpTpConfigStorage getWxCpTpConfigStorage();
@ -202,6 +221,8 @@ public interface WxCpTpService {
/** /**
* http请求对象. * http请求对象.
*
* @return the request http
*/ */
RequestHttp<?, ?> getRequestHttp(); RequestHttp<?, ?> getRequestHttp();

View File

@ -4,8 +4,8 @@ import com.google.common.base.Joiner;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.enums.WxType;
import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.enums.WxType;
import me.chanjar.weixin.common.error.WxCpErrorMsgEnum; import me.chanjar.weixin.common.error.WxCpErrorMsgEnum;
import me.chanjar.weixin.common.error.WxError; import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxErrorException;
@ -127,7 +127,7 @@ public abstract class BaseWxCpTpServiceImpl<H, P> implements WxCpTpService, Requ
} }
@Override @Override
public WxCpTpPermanentCodeInfo getPermanentCodeInfo(String authCode) throws WxErrorException{ public WxCpTpPermanentCodeInfo getPermanentCodeInfo(String authCode) throws WxErrorException {
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("auth_code", authCode); jsonObject.addProperty("auth_code", authCode);
String result = post(configStorage.getApiUrl(GET_PERMANENT_CODE), jsonObject.toString()); String result = post(configStorage.getApiUrl(GET_PERMANENT_CODE), jsonObject.toString());
@ -136,18 +136,19 @@ public abstract class BaseWxCpTpServiceImpl<H, P> implements WxCpTpService, Requ
@Override @Override
@SneakyThrows @SneakyThrows
public String getPreAuthUrl(String redirectUri,String state) throws WxErrorException{ public String getPreAuthUrl(String redirectUri, String state) throws WxErrorException {
String result = get(configStorage.getApiUrl(GET_PREAUTH_CODE),null); String result = get(configStorage.getApiUrl(GET_PREAUTH_CODE), null);
WxCpTpPreauthCode preauthCode = WxCpTpPreauthCode.fromJson(result); WxCpTpPreauthCode preAuthCode = WxCpTpPreauthCode.fromJson(result);
String preAuthUrl = "https://open.work.weixin.qq.com/3rdapp/install?suite_id="+configStorage.getSuiteId()+ String preAuthUrl = "https://open.work.weixin.qq.com/3rdapp/install?suite_id=" + configStorage.getSuiteId() +
"&pre_auth_code="+preauthCode.getPreAuthCode()+"&redirect_uri="+ URLEncoder.encode(redirectUri,"utf-8"); "&pre_auth_code=" + preAuthCode.getPreAuthCode() + "&redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8");
if(StringUtils.isNotBlank(state)) if (StringUtils.isNotBlank(state)) {
preAuthUrl += "&state="+state; preAuthUrl += "&state=" + state;
}
return preAuthUrl; return preAuthUrl;
} }
@Override @Override
public WxCpTpAuthInfo getAuthInfo(String authCorpId, String permanentCode) throws WxErrorException{ public WxCpTpAuthInfo getAuthInfo(String authCorpId, String permanentCode) throws WxErrorException {
JsonObject jsonObject = new JsonObject(); JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("auth_corpid", authCorpId); jsonObject.addProperty("auth_corpid", authCorpId);
jsonObject.addProperty("permanent_code", permanentCode); jsonObject.addProperty("permanent_code", permanentCode);

View File

@ -16,11 +16,14 @@ import java.util.Map;
public interface WxCpMessageHandler { public interface WxCpMessageHandler {
/** /**
* @param wxMessage * Handle wx cp xml out message.
*
* @param wxMessage the wx message
* @param context 上下文如果handler或interceptor之间有信息要传递可以用这个 * @param context 上下文如果handler或interceptor之间有信息要传递可以用这个
* @param wxCpService * @param wxCpService the wx cp service
* @param sessionManager * @param sessionManager the session manager
* @return xml格式的消息如果在异步规则里处理的话可以返回null * @return xml格式的消息 如果在异步规则里处理的话可以返回null
* @throws WxErrorException the wx error exception
*/ */
WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage,
Map<String, Object> context, Map<String, Object> context,

View File

@ -17,11 +17,12 @@ public interface WxCpMessageInterceptor {
/** /**
* 拦截微信消息 * 拦截微信消息
* *
* @param wxMessage * @param wxMessage the wx message
* @param context 上下文如果handler或interceptor之间有信息要传递可以用这个 * @param context 上下文如果handler或interceptor之间有信息要传递可以用这个
* @param wxCpService * @param wxCpService the wx cp service
* @param sessionManager * @param sessionManager the session manager
* @return true代表OKfalse代表不OK * @return true代表OK false代表不OK
* @throws WxErrorException the wx error exception
*/ */
boolean intercept(WxCpXmlMessage wxMessage, boolean intercept(WxCpXmlMessage wxMessage,
Map<String, Object> context, Map<String, Object> context,

View File

@ -4,11 +4,16 @@ import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
/** /**
* 消息匹配器用在消息路由的时候 * 消息匹配器用在消息路由的时候
*
* @author Daniel Qian
*/ */
public interface WxCpMessageMatcher { public interface WxCpMessageMatcher {
/** /**
* 消息是否匹配某种模式 * 消息是否匹配某种模式
*
* @param message the message
* @return the boolean
*/ */
boolean match(WxCpXmlMessage message); boolean match(WxCpXmlMessage message);

View File

@ -1,15 +1,6 @@
package me.chanjar.weixin.cp.message; package me.chanjar.weixin.cp.message;
import java.util.*; import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.api.WxMessageDuplicateChecker; import me.chanjar.weixin.common.api.WxMessageDuplicateChecker;
import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
@ -20,6 +11,16 @@ import me.chanjar.weixin.common.util.LogExceptionHandler;
import me.chanjar.weixin.cp.api.WxCpService; import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage; import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/** /**
* <pre> * <pre>
@ -49,9 +50,9 @@ import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
* *
* @author Daniel Qian * @author Daniel Qian
*/ */
@Slf4j
public class WxCpMessageRouter { public class WxCpMessageRouter {
private static final int DEFAULT_THREAD_POOL_SIZE = 100; private static final int DEFAULT_THREAD_POOL_SIZE = 100;
private final Logger log = LoggerFactory.getLogger(WxCpMessageRouter.class);
private final List<WxCpMessageRouterRule> rules = new ArrayList<>(); private final List<WxCpMessageRouterRule> rules = new ArrayList<>();
private final WxCpService wxCpService; private final WxCpService wxCpService;
@ -156,37 +157,31 @@ public class WxCpMessageRouter {
// 返回最后一个非异步的rule的执行结果 // 返回最后一个非异步的rule的执行结果
if (rule.isAsync()) { if (rule.isAsync()) {
futures.add( futures.add(
this.executorService.submit(new Runnable() { this.executorService.submit(() -> {
@Override rule.service(wxMessage, context, WxCpMessageRouter.this.wxCpService, WxCpMessageRouter.this.sessionManager, WxCpMessageRouter.this.exceptionHandler);
public void run() {
rule.service(wxMessage, context, WxCpMessageRouter.this.wxCpService, WxCpMessageRouter.this.sessionManager, WxCpMessageRouter.this.exceptionHandler);
}
}) })
); );
} else { } else {
res = rule.service(wxMessage, context, this.wxCpService, this.sessionManager, this.exceptionHandler); res = rule.service(wxMessage, context, this.wxCpService, this.sessionManager, this.exceptionHandler);
// 在同步操作结束session访问结束 // 在同步操作结束session访问结束
this.log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName()); log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName());
sessionEndAccess(wxMessage); sessionEndAccess(wxMessage);
} }
} }
if (futures.size() > 0) { if (futures.size() > 0) {
this.executorService.submit(new Runnable() { this.executorService.submit(() -> {
@Override for (Future future : futures) {
public void run() { try {
for (Future future : futures) { future.get();
try { log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName());
future.get(); // 异步操作结束session访问结束
WxCpMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName()); sessionEndAccess(wxMessage);
// 异步操作结束session访问结束 } catch (InterruptedException e) {
sessionEndAccess(wxMessage); log.error("Error happened when wait task finish", e);
} catch (InterruptedException e) { Thread.currentThread().interrupt();
WxCpMessageRouter.this.log.error("Error happened when wait task finish", e); } catch (ExecutionException e) {
Thread.currentThread().interrupt(); log.error("Error happened when wait task finish", e);
} catch (ExecutionException e) {
WxCpMessageRouter.this.log.error("Error happened when wait task finish", e);
}
} }
} }
}); });
@ -198,7 +193,7 @@ public class WxCpMessageRouter {
* 处理微信消息. * 处理微信消息.
*/ */
public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) { public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) {
return this.route(wxMessage, new HashMap<String, Object>(2)); return this.route(wxMessage, new HashMap<>(2));
} }
private boolean isMsgDuplicated(WxCpXmlMessage wxMessage) { private boolean isMsgDuplicated(WxCpXmlMessage wxMessage) {

View File

@ -1,5 +1,6 @@
package me.chanjar.weixin.cp.message; package me.chanjar.weixin.cp.message;
import lombok.Data;
import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.common.session.WxSessionManager;
@ -8,14 +9,16 @@ import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage; import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/**
* The type Wx cp message router rule.
*
* @author Daniel Qian
*/
@Data
public class WxCpMessageRouterRule { public class WxCpMessageRouterRule {
private final WxCpMessageRouter routerBuilder; private final WxCpMessageRouter routerBuilder;
private boolean async = true; private boolean async = true;
@ -44,6 +47,11 @@ public class WxCpMessageRouterRule {
private List<WxCpMessageInterceptor> interceptors = new ArrayList<>(); private List<WxCpMessageInterceptor> interceptors = new ArrayList<>();
/**
* Instantiates a new Wx cp message router rule.
*
* @param routerBuilder the router builder
*/
protected WxCpMessageRouterRule(WxCpMessageRouter routerBuilder) { protected WxCpMessageRouterRule(WxCpMessageRouter routerBuilder) {
this.routerBuilder = routerBuilder; this.routerBuilder = routerBuilder;
} }
@ -51,7 +59,8 @@ public class WxCpMessageRouterRule {
/** /**
* 设置是否异步执行默认是true * 设置是否异步执行默认是true
* *
* @param async * @param async the async
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule async(boolean async) { public WxCpMessageRouterRule async(boolean async) {
this.async = async; this.async = async;
@ -61,7 +70,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果agentId匹配 * 如果agentId匹配
* *
* @param agentId * @param agentId the agent id
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule agentId(Integer agentId) { public WxCpMessageRouterRule agentId(Integer agentId) {
this.agentId = agentId; this.agentId = agentId;
@ -71,7 +81,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果msgType等于某值 * 如果msgType等于某值
* *
* @param msgType * @param msgType the msg type
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule msgType(String msgType) { public WxCpMessageRouterRule msgType(String msgType) {
this.msgType = msgType; this.msgType = msgType;
@ -81,7 +92,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果event等于某值 * 如果event等于某值
* *
* @param event * @param event the event
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule event(String event) { public WxCpMessageRouterRule event(String event) {
this.event = event; this.event = event;
@ -91,7 +103,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果eventKey等于某值 * 如果eventKey等于某值
* *
* @param eventKey * @param eventKey the event key
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule eventKey(String eventKey) { public WxCpMessageRouterRule eventKey(String eventKey) {
this.eventKey = eventKey; this.eventKey = eventKey;
@ -100,6 +113,9 @@ public class WxCpMessageRouterRule {
/** /**
* 如果eventKey匹配该正则表达式 * 如果eventKey匹配该正则表达式
*
* @param regex the regex
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule eventKeyRegex(String regex) { public WxCpMessageRouterRule eventKeyRegex(String regex) {
this.eventKeyRegex = regex; this.eventKeyRegex = regex;
@ -109,7 +125,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果content等于某值 * 如果content等于某值
* *
* @param content * @param content the content
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule content(String content) { public WxCpMessageRouterRule content(String content) {
this.content = content; this.content = content;
@ -119,7 +136,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果content匹配该正则表达式 * 如果content匹配该正则表达式
* *
* @param regex * @param regex the regex
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule rContent(String regex) { public WxCpMessageRouterRule rContent(String regex) {
this.rContent = regex; this.rContent = regex;
@ -129,7 +147,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果fromUser等于某值 * 如果fromUser等于某值
* *
* @param fromUser * @param fromUser the from user
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule fromUser(String fromUser) { public WxCpMessageRouterRule fromUser(String fromUser) {
this.fromUser = fromUser; this.fromUser = fromUser;
@ -139,7 +158,8 @@ public class WxCpMessageRouterRule {
/** /**
* 如果消息匹配某个matcher用在用户需要自定义更复杂的匹配规则的时候 * 如果消息匹配某个matcher用在用户需要自定义更复杂的匹配规则的时候
* *
* @param matcher * @param matcher the matcher
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule matcher(WxCpMessageMatcher matcher) { public WxCpMessageRouterRule matcher(WxCpMessageMatcher matcher) {
this.matcher = matcher; this.matcher = matcher;
@ -149,7 +169,8 @@ public class WxCpMessageRouterRule {
/** /**
* 设置微信消息拦截器 * 设置微信消息拦截器
* *
* @param interceptor * @param interceptor the interceptor
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule interceptor(WxCpMessageInterceptor interceptor) { public WxCpMessageRouterRule interceptor(WxCpMessageInterceptor interceptor) {
return interceptor(interceptor, (WxCpMessageInterceptor[]) null); return interceptor(interceptor, (WxCpMessageInterceptor[]) null);
@ -158,15 +179,14 @@ public class WxCpMessageRouterRule {
/** /**
* 设置微信消息拦截器 * 设置微信消息拦截器
* *
* @param interceptor * @param interceptor the interceptor
* @param otherInterceptors * @param otherInterceptors the other interceptors
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule interceptor(WxCpMessageInterceptor interceptor, WxCpMessageInterceptor... otherInterceptors) { public WxCpMessageRouterRule interceptor(WxCpMessageInterceptor interceptor, WxCpMessageInterceptor... otherInterceptors) {
this.interceptors.add(interceptor); this.interceptors.add(interceptor);
if (otherInterceptors != null && otherInterceptors.length > 0) { if (otherInterceptors != null && otherInterceptors.length > 0) {
for (WxCpMessageInterceptor i : otherInterceptors) { Collections.addAll(this.interceptors, otherInterceptors);
this.interceptors.add(i);
}
} }
return this; return this;
} }
@ -174,7 +194,8 @@ public class WxCpMessageRouterRule {
/** /**
* 设置微信消息处理器 * 设置微信消息处理器
* *
* @param handler * @param handler the handler
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule handler(WxCpMessageHandler handler) { public WxCpMessageRouterRule handler(WxCpMessageHandler handler) {
return handler(handler, (WxCpMessageHandler[]) null); return handler(handler, (WxCpMessageHandler[]) null);
@ -183,21 +204,22 @@ public class WxCpMessageRouterRule {
/** /**
* 设置微信消息处理器 * 设置微信消息处理器
* *
* @param handler * @param handler the handler
* @param otherHandlers * @param otherHandlers the other handlers
* @return the wx cp message router rule
*/ */
public WxCpMessageRouterRule handler(WxCpMessageHandler handler, WxCpMessageHandler... otherHandlers) { public WxCpMessageRouterRule handler(WxCpMessageHandler handler, WxCpMessageHandler... otherHandlers) {
this.handlers.add(handler); this.handlers.add(handler);
if (otherHandlers != null && otherHandlers.length > 0) { if (otherHandlers != null && otherHandlers.length > 0) {
for (WxCpMessageHandler i : otherHandlers) { Collections.addAll(this.handlers, otherHandlers);
this.handlers.add(i);
}
} }
return this; return this;
} }
/** /**
* 规则结束代表如果一个消息匹配该规则那么它将不再会进入其他规则 * 规则结束代表如果一个消息匹配该规则那么它将不再会进入其他规则
*
* @return the wx cp message router
*/ */
public WxCpMessageRouter end() { public WxCpMessageRouter end() {
this.routerBuilder.getRules().add(this); this.routerBuilder.getRules().add(this);
@ -206,12 +228,20 @@ public class WxCpMessageRouterRule {
/** /**
* 规则结束但是消息还会进入其他规则 * 规则结束但是消息还会进入其他规则
*
* @return the wx cp message router
*/ */
public WxCpMessageRouter next() { public WxCpMessageRouter next() {
this.reEnter = true; this.reEnter = true;
return end(); return end();
} }
/**
* Test boolean.
*
* @param wxMessage the wx message
* @return the boolean
*/
protected boolean test(WxCpXmlMessage wxMessage) { protected boolean test(WxCpXmlMessage wxMessage) {
return return
(this.fromUser == null || this.fromUser.equals(wxMessage.getFromUserName())) (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUserName()))
@ -237,7 +267,11 @@ public class WxCpMessageRouterRule {
/** /**
* 处理微信推送过来的消息 * 处理微信推送过来的消息
* *
* @param wxMessage * @param wxMessage the wx message
* @param context the context
* @param wxCpService the wx cp service
* @param sessionManager the session manager
* @param exceptionHandler the exception handler
* @return true 代表继续执行别的routerfalse 代表停止执行别的router * @return true 代表继续执行别的routerfalse 代表停止执行别的router
*/ */
protected WxCpXmlOutMessage service(WxCpXmlMessage wxMessage, protected WxCpXmlOutMessage service(WxCpXmlMessage wxMessage,
@ -274,60 +308,5 @@ public class WxCpMessageRouterRule {
} }
public void setFromUser(String fromUser) {
this.fromUser = fromUser;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public void setEvent(String event) {
this.event = event;
}
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
public void setContent(String content) {
this.content = content;
}
public void setrContent(String rContent) {
this.rContent = rContent;
}
public void setMatcher(WxCpMessageMatcher matcher) {
this.matcher = matcher;
}
public void setAgentId(Integer agentId) {
this.agentId = agentId;
}
public void setHandlers(List<WxCpMessageHandler> handlers) {
this.handlers = handlers;
}
public void setInterceptors(List<WxCpMessageInterceptor> interceptors) {
this.interceptors = interceptors;
}
public boolean isAsync() {
return this.async;
}
public void setAsync(boolean async) {
this.async = async;
}
public boolean isReEnter() {
return this.reEnter;
}
public void setReEnter(boolean reEnter) {
this.reEnter = reEnter;
}
} }

View File

@ -1,24 +1,19 @@
package me.chanjar.weixin.cp.demo; package me.chanjar.weixin.cp.demo;
import java.io.IOException; import me.chanjar.weixin.cp.api.WxCpService;
import java.io.InputStream; import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import java.util.Map; import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutTextMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler; import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.servlet.ServletHolder;
import me.chanjar.weixin.common.error.WxErrorException; import java.io.IOException;
import me.chanjar.weixin.common.session.WxSessionManager; import java.io.InputStream;
import me.chanjar.weixin.cp.constant.WxCpConsts;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutTextMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
public class WxCpDemoServer { public class WxCpDemoServer {
@ -54,30 +49,20 @@ public class WxCpDemoServer {
wxCpService = new WxCpServiceImpl(); wxCpService = new WxCpServiceImpl();
wxCpService.setWxCpConfigStorage(config); wxCpService.setWxCpConfigStorage(config);
WxCpMessageHandler handler = new WxCpMessageHandler() { WxCpMessageHandler handler = (wxMessage, context, wxService, sessionManager) -> {
@Override WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("测试加密消息")
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, .fromUser(wxMessage.getToUserName())
Map<String, Object> context, WxCpService wxService, .toUser(wxMessage.getFromUserName()).build();
WxSessionManager sessionManager) { return m;
WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("测试加密消息")
.fromUser(wxMessage.getToUserName())
.toUser(wxMessage.getFromUserName()).build();
return m;
}
}; };
WxCpMessageHandler oauth2handler = new WxCpMessageHandler() { WxCpMessageHandler oauth2handler = (wxMessage, context, wxService, sessionManager) -> {
@Override String href = "<a href=\""
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, + wxService.getOauth2Service().buildAuthorizationUrl(wxCpConfigStorage.getOauth2redirectUri(), null)
Map<String, Object> context, WxCpService wxService, + "\">测试oauth2</a>";
WxSessionManager sessionManager) { return WxCpXmlOutMessage.TEXT().content(href)
String href = "<a href=\"" .fromUser(wxMessage.getToUserName())
+ wxService.getOauth2Service().buildAuthorizationUrl(wxCpConfigStorage.getOauth2redirectUri(), null) .toUser(wxMessage.getFromUserName()).build();
+ "\">测试oauth2</a>";
return WxCpXmlOutMessage.TEXT().content(href)
.fromUser(wxMessage.getToUserName())
.toUser(wxMessage.getFromUserName()).build();
}
}; };
wxCpMessageRouter = new WxCpMessageRouter(wxCpService); wxCpMessageRouter = new WxCpMessageRouter(wxCpService);
@ -93,12 +78,9 @@ public class WxCpDemoServer {
.end() .end()
.rule() .rule()
.event(WxCpConsts.EventType.CHANGE_CONTACT) .event(WxCpConsts.EventType.CHANGE_CONTACT)
.handler(new WxCpMessageHandler() { .handler((wxMessage, context, wxCpService, sessionManager) -> {
@Override System.out.println("通讯录发生变更");
public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map<String, Object> context, WxCpService wxCpService, WxSessionManager sessionManager) throws WxErrorException { return null;
System.out.println("通讯录发生变更");
return null;
}
}) })
.end(); .end();

View File

@ -61,7 +61,6 @@ public class WxCpEndpointServlet extends HttpServlet {
response.getWriter().write(outMessage.toEncryptedXml(this.wxCpConfigStorage)); response.getWriter().write(outMessage.toEncryptedXml(this.wxCpConfigStorage));
} }
return;
} }
} }

View File

@ -45,7 +45,7 @@ public class WxMaMessageRouter {
this.wxMaService = wxMaService; this.wxMaService = wxMaService;
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("WxMaMessageRouter-pool-%d").build(); ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("WxMaMessageRouter-pool-%d").build();
this.executorService = new ThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE, this.executorService = new ThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE, DEFAULT_THREAD_POOL_SIZE,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), namedThreadFactory); 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), namedThreadFactory);
this.sessionManager = new StandardSessionManager(); this.sessionManager = new StandardSessionManager();
this.exceptionHandler = new LogExceptionHandler(); this.exceptionHandler = new LogExceptionHandler();
this.messageDuplicateChecker = new WxMessageInMemoryDuplicateChecker(); this.messageDuplicateChecker = new WxMessageInMemoryDuplicateChecker();
@ -88,11 +88,8 @@ public class WxMaMessageRouter {
// 返回最后一个非异步的rule的执行结果 // 返回最后一个非异步的rule的执行结果
if (rule.isAsync()) { if (rule.isAsync()) {
futures.add( futures.add(
this.executorService.submit(new Runnable() { this.executorService.submit(() -> {
@Override rule.service(wxMessage, context, WxMaMessageRouter.this.wxMaService, WxMaMessageRouter.this.sessionManager, WxMaMessageRouter.this.exceptionHandler);
public void run() {
rule.service(wxMessage, context, WxMaMessageRouter.this.wxMaService, WxMaMessageRouter.this.sessionManager, WxMaMessageRouter.this.exceptionHandler);
}
}) })
); );
} else { } else {
@ -104,18 +101,15 @@ public class WxMaMessageRouter {
} }
if (futures.size() > 0) { if (futures.size() > 0) {
this.executorService.submit(new Runnable() { this.executorService.submit(() -> {
@Override for (Future<?> future : futures) {
public void run() { try {
for (Future<?> future : futures) { future.get();
try { WxMaMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUser());
future.get(); // 异步操作结束session访问结束
WxMaMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUser()); sessionEndAccess(wxMessage);
// 异步操作结束session访问结束 } catch (InterruptedException | ExecutionException e) {
sessionEndAccess(wxMessage); WxMaMessageRouter.this.log.error("Error happened when wait task finish", e);
} catch (InterruptedException | ExecutionException e) {
WxMaMessageRouter.this.log.error("Error happened when wait task finish", e);
}
} }
} }
}); });
@ -124,7 +118,7 @@ public class WxMaMessageRouter {
} }
public WxMaXmlOutMessage route(final WxMaMessage wxMessage) { public WxMaXmlOutMessage route(final WxMaMessage wxMessage) {
return this.route(wxMessage, new HashMap<String, Object>(2)); return this.route(wxMessage, new HashMap<>(2));
} }
private boolean isMsgDuplicated(WxMaMessage wxMessage) { private boolean isMsgDuplicated(WxMaMessage wxMessage) {

View File

@ -6,10 +6,7 @@ import me.chanjar.weixin.common.api.WxErrorExceptionHandler;
import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.common.session.WxSessionManager;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
@ -135,9 +132,7 @@ public class WxMaMessageRouterRule {
public WxMaMessageRouterRule interceptor(WxMaMessageInterceptor interceptor, WxMaMessageInterceptor... otherInterceptors) { public WxMaMessageRouterRule interceptor(WxMaMessageInterceptor interceptor, WxMaMessageInterceptor... otherInterceptors) {
this.interceptors.add(interceptor); this.interceptors.add(interceptor);
if (otherInterceptors != null && otherInterceptors.length > 0) { if (otherInterceptors != null && otherInterceptors.length > 0) {
for (WxMaMessageInterceptor i : otherInterceptors) { Collections.addAll(this.interceptors, otherInterceptors);
this.interceptors.add(i);
}
} }
return this; return this;
} }
@ -155,9 +150,7 @@ public class WxMaMessageRouterRule {
public WxMaMessageRouterRule handler(WxMaMessageHandler handler, WxMaMessageHandler... otherHandlers) { public WxMaMessageRouterRule handler(WxMaMessageHandler handler, WxMaMessageHandler... otherHandlers) {
this.handlers.add(handler); this.handlers.add(handler);
if (otherHandlers != null && otherHandlers.length > 0) { if (otherHandlers != null && otherHandlers.length > 0) {
for (WxMaMessageHandler i : otherHandlers) { Collections.addAll(this.handlers, otherHandlers);
this.handlers.add(i);
}
} }
return this; return this;
} }

View File

@ -1,9 +1,8 @@
package me.chanjar.weixin.open.api.impl; package me.chanjar.weixin.open.api.impl;
import me.chanjar.weixin.common.error.WxErrorException; import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.open.api.WxOpenComponentService; import me.chanjar.weixin.open.api.WxOpenComponentService;
/** /**