diff --git a/.gitignore b/.gitignore index 66e4038250..dd377af1aa 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ test-output hs_err_pid* target +bin .project .classpath .settings @@ -21,3 +22,7 @@ sw-pom.xml *.iml test-config.xml .idea +/.gradle/ +/gradle/ +*.bat +/gradlew diff --git a/README.md b/README.md index 57119c7b30..b40876ec71 100644 --- a/README.md +++ b/README.md @@ -8,22 +8,7 @@ #### 由于本次更新涉及接口调整比较大,主要是公众号的调整,企业号无过多调整,主要是为了解决主接口类过于庞大不方便管理的问题,将接口实现代码按模块进行拆分。因此版本号直接从1.X.X直接升级到2.0.0,所以如果习惯于1.X.X版本的同学不想做过多更改的话,请慎重考虑升级到最新版本。 --- -#### 本项目主要存放在github上,地址为 : -* https://github.com/wechat-group/weixin-java-tools -* ===========但同时会在其他几个网站同步更新,地址分别是: -* https://bitbucket.org/binarywang/weixin-java-tools -* http://git.oschina.net/binary/weixin-java-tools -* https://git.coding.net/binarywang/weixin-java-tools.git - ### 详细开发文档请看 [wiki](https://github.com/chanjarster/weixin-java-tools/wiki)。 - -## 目前可参考的Demo项目: -* https://github.com/wechat-group/weixin-java-tools-springmvc -* https://github.com/wechat-group/weixin-mp-demo -* ===========以下为备份仓库,会保持跟主仓库同步 -* http://git.oschina.net/binary/weixin-mp-demo -* https://bitbucket.org/binarywang/weixin-mp-demo - =========== ## 开发交流工具: * QQ群:343954419 [![Join QQ Group](http://pub.idqqimg.com/wpa/images/group.png)](http://shang.qq.com/wpa/qunwpa?idkey=078f7a153d243853e24cf2b542e7a6ccbf2a592bc138080f84d11297f736ec46) @@ -40,10 +25,9 @@ - [【企业号】](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.github.binarywang%22%20AND%20a%3A%22weixin-java-cp%22) -## Quick Start - -* 如果要开发公众号(订阅号、服务号)应用,在你的maven项目中添加: +## Maven & Gradle +* 公众号(订阅号、服务号): ```xml com.github.binarywang @@ -52,8 +36,11 @@ ``` -* 如果要开发企业号应用,在你的maven项目中添加: +```groovy +compile 'com.github.binarywang:weixin-java-mp:2.0.0' +``` +* 企业号: ```xml com.github.binarywang @@ -62,6 +49,25 @@ ``` +```groovy +compile 'com.github.binarywang:weixin-java-cp:2.0.0' +``` + +#### 本项目主要存放在github上,地址为 : +* https://github.com/wechat-group/weixin-java-tools +* ===========但同时会在其他几个网站同步更新,地址分别是: +* https://bitbucket.org/binarywang/weixin-java-tools +* http://git.oschina.net/binary/weixin-java-tools +* https://git.coding.net/binarywang/weixin-java-tools.git + + +## 目前可参考的Demo项目: +* https://github.com/wechat-group/weixin-java-tools-springmvc +* https://github.com/wechat-group/weixin-mp-demo +* ===========以下为备份仓库,会保持跟主仓库同步 +* http://git.oschina.net/binary/weixin-mp-demo +* https://bitbucket.org/binarywang/weixin-mp-demo + ## 关于代码贡献 * 非常欢迎和感谢对本项目发起Pull Request的同学,本项目可以采用两种方式接受代码贡献: diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..cb727c469d --- /dev/null +++ b/build.gradle @@ -0,0 +1,34 @@ +allprojects { + apply plugin: 'maven' + + group = 'com.github.binarywang' + version = '2.1.0-SNAPSHOT' +} + +subprojects { + apply plugin: 'java' + sourceCompatibility = 1.7 + targetCompatibility = 1.7 + + + repositories { + mavenLocal() + + maven { url "http://maven.aliyun.com/nexus/content/groups/public" } + } + + + dependencies { + compile group: 'org.slf4j', name: 'slf4j-api', version:'1.7.10' + compile group: 'org.apache.httpcomponents', name: 'fluent-hc', version:'4.5' + compile group: 'org.apache.httpcomponents', name: 'httpmime', version:'4.5' + compile group: 'org.jodd', name: 'jodd-http', version:'3.6.7' + compile group: 'com.google.code.gson', name: 'gson', version:'2.7' + compile group: 'commons-codec', name: 'commons-codec', version:'1.10' + compile group: 'commons-io', name: 'commons-io', version:'2.5' + compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.4' + compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version:'2.8.0' + compile group: 'redis.clients', name: 'jedis', version:'2.9.0' + testCompile group: 'ch.qos.logback', name: 'logback-classic', version:'1.1.2' + } +} diff --git a/pom.xml b/pom.xml index a6cfb54b16..dded0cabed 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ 4.0.0 com.github.binarywang weixin-java-parent - 2.0.0 + 2.1.0 pom WeiXin Java Tools - Parent 微信公众号、企业号上级POM @@ -50,6 +50,7 @@ 1.1.2 3.6.7 2.8.0 + 2.9.0 2.7 3.4 2.5 @@ -110,8 +111,13 @@ jackson-databind ${jackson.version} + + redis.clients + jedis + ${jedis.version} + - + diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000000..1c0e0214c4 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +rootProject.name = 'weixin-java-parent' +include ':weixin-java-common' +include ':weixin-java-cp' +include ':weixin-java-mp' + +project(':weixin-java-common').projectDir = "$rootDir/weixin-java-common" as File +project(':weixin-java-cp').projectDir = "$rootDir/weixin-java-cp" as File +project(':weixin-java-mp').projectDir = "$rootDir/weixin-java-mp" as File \ No newline at end of file diff --git a/weixin-java-common/build.gradle b/weixin-java-common/build.gradle new file mode 100644 index 0000000000..07b5036aa7 --- /dev/null +++ b/weixin-java-common/build.gradle @@ -0,0 +1,12 @@ + +description = 'WeiXin Java Tools - Common' +dependencies { + compile group: 'com.thoughtworks.xstream', name: 'xstream', version:'1.4.7' + testCompile group: 'junit', name: 'junit', version:'4.11' + testCompile group: 'org.testng', name: 'testng', version:'6.8.7' + testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' + testCompile group: 'com.google.inject', name: 'guice', version:'3.0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version:'9.3.0.M0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version:'9.3.0.M0' +} +test.useTestNG() diff --git a/weixin-java-common/pom.xml b/weixin-java-common/pom.xml index eb8e757294..b916ccfa5b 100644 --- a/weixin-java-common/pom.xml +++ b/weixin-java-common/pom.xml @@ -6,7 +6,7 @@ com.github.binarywang weixin-java-parent - 2.0.0 + 2.1.0 weixin-java-common diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java index 0c9661d2f0..e45643b774 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxConsts.java @@ -19,7 +19,7 @@ public class WxConsts { public static final String XML_MSG_LINK = "link"; public static final String XML_MSG_EVENT = "event"; public static final String XML_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service"; - + /////////////////////// // 主动发送消息(即客服消息)的消息类型 /////////////////////// @@ -33,7 +33,7 @@ public class WxConsts { public static final String CUSTOM_MSG_TRANSFER_CUSTOMER_SERVICE = "transfer_customer_service"; public static final String CUSTOM_MSG_SAFE_NO = "0"; public static final String CUSTOM_MSG_SAFE_YES = "1"; - + /////////////////////// // 群发消息的消息类型 /////////////////////// @@ -42,7 +42,7 @@ public class WxConsts { public static final String MASS_MSG_VOICE = "voice"; public static final String MASS_MSG_IMAGE = "image"; public static final String MASS_MSG_VIDEO = "mpvideo"; - + /////////////////////// // 群发消息后微信端推送给服务器的反馈消息 /////////////////////// @@ -57,25 +57,11 @@ public class WxConsts { public static final String MASS_ST_涉嫌版权 = "err(20013)"; public static final String MASS_ST_涉嫌互推_互相宣传 = "err(22000)"; public static final String MASS_ST_涉嫌其他 = "err(21000)"; - + /** * 群发反馈消息代码所对应的文字描述 */ public static final Map MASS_ST_2_DESC = new HashMap(); - static { - MASS_ST_2_DESC.put(MASS_ST_SUCCESS, "发送成功"); - MASS_ST_2_DESC.put(MASS_ST_FAIL, "发送失败"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌广告, "涉嫌广告"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌政治, "涉嫌政治"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌社会, "涉嫌社会"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌色情, "涉嫌色情"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌违法犯罪, "涉嫌违法犯罪"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌欺诈, "涉嫌欺诈"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌版权, "涉嫌版权"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌互推_互相宣传, "涉嫌互推_互相宣传"); - MASS_ST_2_DESC.put(MASS_ST_涉嫌其他, "涉嫌其他"); - } - /////////////////////// // 微信端推送过来的事件类型 /////////////////////// @@ -103,11 +89,9 @@ public class WxConsts { public static final String EVT_USER_VIEW_CARD = "user_view_card"; public static final String EVT_USER_ENTER_SESSION_FROM_CARD = "user_enter_session_from_card"; public static final String EVT_CARD_SKU_REMIND = "card_sku_remind"; // 库存报警 - public static final String EVT_KF_CREATE_SESSION = "kf_create_session"; // 客服接入会话 public static final String EVT_KF_CLOSE_SESSION = "kf_close_session"; // 客服关闭会话 public static final String EVT_KF_SWITCH_SESSION = "kf_switch_session"; // 客服转接会话 - /////////////////////// // 上传多媒体文件的类型 /////////////////////// @@ -116,7 +100,6 @@ public class WxConsts { public static final String MEDIA_VIDEO = "video"; public static final String MEDIA_THUMB = "thumb"; public static final String MEDIA_FILE = "file"; - /////////////////////// // 文件类型 /////////////////////// @@ -124,40 +107,63 @@ public class WxConsts { public static final String FILE_MP3 = "mp3"; public static final String FILE_AMR = "amr"; public static final String FILE_MP4 = "mp4"; + /** + * 点击推事件 + */ + public static final String BUTTON_CLICK = "click"; /////////////////////// // 自定义菜单的按钮类型 /////////////////////// - /** 点击推事件 */ - public static final String BUTTON_CLICK = "click"; - /** 跳转URL */ + /** + * 跳转URL + */ public static final String BUTTON_VIEW = "view"; - /** 扫码推事件 */ + /** + * 扫码推事件 + */ public static final String BUTTON_SCANCODE_PUSH = "scancode_push"; - /** 扫码推事件且弹出“消息接收中”提示框 */ + /** + * 扫码推事件且弹出“消息接收中”提示框 + */ public static final String BUTTON_SCANCODE_WAITMSG = "scancode_waitmsg"; - /** 弹出系统拍照发图 */ + /** + * 弹出系统拍照发图 + */ public static final String BUTTON_PIC_SYSPHOTO = "pic_sysphoto"; - /** 弹出拍照或者相册发图 */ + /** + * 弹出拍照或者相册发图 + */ public static final String BUTTON_PIC_PHOTO_OR_ALBUM = "pic_photo_or_album"; - /** 弹出微信相册发图器 */ + /** + * 弹出微信相册发图器 + */ public static final String BUTTON_PIC_WEIXIN = "pic_weixin"; - /** 弹出地理位置选择器 */ + /** + * 弹出地理位置选择器 + */ public static final String BUTTON_LOCATION_SELECT = "location_select"; - /** 下发消息(除文本消息) */ + /** + * 下发消息(除文本消息) + */ public static final String BUTTON_MEDIA_ID = "media_id"; - /** 跳转图文消息URL */ + /** + * 跳转图文消息URL + */ public static final String BUTTON_VIEW_LIMITED = "view_limited"; + /** + * 不弹出授权页面,直接跳转,只能获取用户openid + */ + public static final String OAUTH2_SCOPE_BASE = "snsapi_base"; /////////////////////// // oauth2网页授权的scope /////////////////////// - /** 不弹出授权页面,直接跳转,只能获取用户openid */ - public static final String OAUTH2_SCOPE_BASE = "snsapi_base"; - /** 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息 */ + /** + * 弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息 + */ public static final String OAUTH2_SCOPE_USER_INFO = "snsapi_userinfo"; - /////////////////////// // 永久素材类型 /////////////////////// @@ -165,4 +171,18 @@ public class WxConsts { public static final String MATERIAL_VOICE = "voice"; public static final String MATERIAL_IMAGE = "image"; public static final String MATERIAL_VIDEO = "video"; + + static { + MASS_ST_2_DESC.put(MASS_ST_SUCCESS, "发送成功"); + MASS_ST_2_DESC.put(MASS_ST_FAIL, "发送失败"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌广告, "涉嫌广告"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌政治, "涉嫌政治"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌社会, "涉嫌社会"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌色情, "涉嫌色情"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌违法犯罪, "涉嫌违法犯罪"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌欺诈, "涉嫌欺诈"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌版权, "涉嫌版权"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌互推_互相宣传, "涉嫌互推_互相宣传"); + MASS_ST_2_DESC.put(MASS_ST_涉嫌其他, "涉嫌其他"); + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageDuplicateChecker.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageDuplicateChecker.java index 2bcc98f8e2..831458a443 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageDuplicateChecker.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageDuplicateChecker.java @@ -10,15 +10,16 @@ public interface WxMessageDuplicateChecker { /** *

公众号的排重方式

- * + *

*

普通消息:关于重试的消息排重,推荐使用msgid排重。文档参考

*

事件消息:关于重试的消息排重,推荐使用FromUserName + CreateTime 排重。文档参考

- * + *

*

企业号的排重方式

- * + *

* 官方文档完全没有写,参照公众号的方式排重。 - * + *

*

或者可以采取更简单的方式,如果有MsgId就用MsgId排重,如果没有就用FromUserName+CreateTime排重

+ * * @param messageId messageId需要根据上面讲的方式构造 * @return 如果是重复消息,返回true,否则返回false */ diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java index 5b0f4e4e3f..e0d4d08cc4 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/api/WxMessageInMemoryDuplicateChecker.java @@ -46,7 +46,8 @@ public WxMessageInMemoryDuplicateChecker() { /** * WxMsgIdInMemoryDuplicateChecker构造函数 - * @param timeToLive 一个消息ID在内存的过期时间:毫秒 + * + * @param timeToLive 一个消息ID在内存的过期时间:毫秒 * @param clearPeriod 每隔多少周期检查消息ID是否过期:毫秒 */ public WxMessageInMemoryDuplicateChecker(Long timeToLive, Long clearPeriod) { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java index ce69a10462..eedecb8423 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxAccessToken.java @@ -8,9 +8,13 @@ public class WxAccessToken implements Serializable { private static final long serialVersionUID = 8709719312922168909L; private String accessToken; - + private int expiresIn = -1; + public static WxAccessToken fromJson(String json) { + return WxGsonBuilder.create().fromJson(json, WxAccessToken.class); + } + public String getAccessToken() { return accessToken; } @@ -27,8 +31,4 @@ public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } - public static WxAccessToken fromJson(String json) { - return WxGsonBuilder.create().fromJson(json, WxAccessToken.class); - } - } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java index 74f0b1b1ab..312860dfe3 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxJsapiSignature.java @@ -9,7 +9,7 @@ public class WxJsapiSignature implements Serializable { private static final long serialVersionUID = -1116808193154384804L; private String appid; - + private String noncestr; private long timestamp; @@ -51,11 +51,11 @@ public void setUrl(String url) { } public String getAppid() { - return appid; + return appid; } public void setAppid(String appid) { - this.appid = appid; + this.appid = appid; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxMenu.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxMenu.java deleted file mode 100644 index d236f62b3f..0000000000 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/WxMenu.java +++ /dev/null @@ -1,208 +0,0 @@ -package me.chanjar.weixin.common.bean; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -import me.chanjar.weixin.common.util.json.WxGsonBuilder; - -/** - * 企业号菜单 - * @author Daniel Qian - * - */ -public class WxMenu implements Serializable { - - private static final long serialVersionUID = -7083914585539687746L; - - private List buttons = new ArrayList(); - - private WxMenuRule matchRule; - - public List getButtons() { - return buttons; - } - - public void setButtons(List buttons) { - this.buttons = buttons; - } - - public WxMenuRule getMatchRule() { - return matchRule; - } - - public void setMatchRule(WxMenuRule matchRule) { - this.matchRule = matchRule; - } - - public String toJson() { - return WxGsonBuilder.create().toJson(this); - } - - /** - * 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化 - * 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式,外层多套了一个menu - */ - public static WxMenu fromJson(String json) { - return WxGsonBuilder.create().fromJson(json, WxMenu.class); - } - - /** - * 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化 - * 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式,外层多套了一个menu - */ - public static WxMenu fromJson(InputStream is) { - return WxGsonBuilder.create().fromJson(new InputStreamReader(is, StandardCharsets.UTF_8), WxMenu.class); - } - - @Override - public String toString() { - return "WxMenu{" + - "buttons=" + buttons + - '}'; - } - - public static class WxMenuButton { - - private String type; - private String name; - private String key; - private String url; - - private List subButtons = new ArrayList(); - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public List getSubButtons() { - return subButtons; - } - - public void setSubButtons(List subButtons) { - this.subButtons = subButtons; - } - - @Override - public String toString() { - return "WxMenuButton{" + - "type='" + type + '\'' + - ", name='" + name + '\'' + - ", key='" + key + '\'' + - ", url='" + url + '\'' + - ", subButtons=" + subButtons + - '}'; - } - } - - public static class WxMenuRule { - private String tagId; - private String sex; - private String country; - private String province; - private String city; - private String clientPlatformType; - private String language; - - public String getTagId() { - return tagId; - } - - public void setTagId(String tagId) { - this.tagId = tagId; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getProvince() { - return province; - } - - public void setProvince(String province) { - this.province = province; - } - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public String getClientPlatformType() { - return clientPlatformType; - } - - public void setClientPlatformType(String clientPlatformType) { - this.clientPlatformType = clientPlatformType; - } - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - @Override - public String toString() { - return "matchrule:{" + - "tag_id='" + tagId + '\'' + - ", sex='" + sex + '\'' + - ", country" + country + '\'' + - ", province" + province + '\'' + - ", city" + city + '\'' + - ", client_platform_type" + clientPlatformType + '\'' + - ", language" + language + '\'' + - "}"; - } - } - -} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java new file mode 100644 index 0000000000..7989b39a24 --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenu.java @@ -0,0 +1,69 @@ +package me.chanjar.weixin.common.bean.menu; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import me.chanjar.weixin.common.bean.menu.WxMenuButton; +import me.chanjar.weixin.common.util.json.WxGsonBuilder; + +/** + * 企业号菜单 + * + * @author Daniel Qian + */ +public class WxMenu implements Serializable { + + private static final long serialVersionUID = -7083914585539687746L; + + private List buttons = new ArrayList(); + + private WxMenuRule matchRule; + + /** + * 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化 + * 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式,外层多套了一个menu + */ + public static WxMenu fromJson(String json) { + return WxGsonBuilder.create().fromJson(json, WxMenu.class); + } + + /** + * 要用 http://mp.weixin.qq.com/wiki/16/ff9b7b85220e1396ffa16794a9d95adc.html 格式来反序列化 + * 相比 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html 的格式,外层多套了一个menu + */ + public static WxMenu fromJson(InputStream is) { + return WxGsonBuilder.create().fromJson(new InputStreamReader(is, StandardCharsets.UTF_8), WxMenu.class); + } + + public List getButtons() { + return buttons; + } + + public void setButtons(List buttons) { + this.buttons = buttons; + } + + public WxMenuRule getMatchRule() { + return matchRule; + } + + public void setMatchRule(WxMenuRule matchRule) { + this.matchRule = matchRule; + } + + public String toJson() { + return WxGsonBuilder.create().toJson(this); + } + + @Override + public String toString() { + return "WxMenu{" + + "buttons=" + buttons + + '}'; + } + +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java new file mode 100644 index 0000000000..88033400ac --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuButton.java @@ -0,0 +1,72 @@ +package me.chanjar.weixin.common.bean.menu; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class WxMenuButton { + + private String type; + private String name; + private String key; + private String url; + private String mediaId; + + private List subButtons = new ArrayList(); + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, + ToStringStyle.JSON_STYLE); + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public List getSubButtons() { + return subButtons; + } + + public void setSubButtons(List subButtons) { + this.subButtons = subButtons; + } + + public String getMediaId() { + return mediaId; + } + + public void setMediaId(String mediaId) { + this.mediaId = mediaId; + } +} \ No newline at end of file diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java new file mode 100644 index 0000000000..5cb9d8fedd --- /dev/null +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/menu/WxMenuRule.java @@ -0,0 +1,75 @@ +package me.chanjar.weixin.common.bean.menu; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class WxMenuRule { + private String tagId; + private String sex; + private String country; + private String province; + private String city; + private String clientPlatformType; + private String language; + + public String getTagId() { + return tagId; + } + + public void setTagId(String tagId) { + this.tagId = tagId; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getProvince() { + return province; + } + + public void setProvince(String province) { + this.province = province; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getClientPlatformType() { + return clientPlatformType; + } + + public void setClientPlatformType(String clientPlatformType) { + this.clientPlatformType = clientPlatformType; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(String language) { + this.language = language; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } +} \ No newline at end of file diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java index 66e22ee7f8..070ec72024 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxError.java @@ -6,19 +6,28 @@ /** * 微信错误码说明,请阅读: 全局返回码说明 - * @author Daniel Qian * + * @author Daniel Qian */ public class WxError implements Serializable { private static final long serialVersionUID = 7869786563361406291L; private int errorCode; - + private String errorMsg; private String json; - + + public static WxError fromJson(String json) { + WxError error = WxGsonBuilder.create().fromJson(json, WxError.class); + return error; + } + + public static Builder newBuilder() { + return new Builder(); + } + public int getErrorCode() { return errorCode; } @@ -43,40 +52,34 @@ public void setJson(String json) { this.json = json; } - public static WxError fromJson(String json) { - WxError error = WxGsonBuilder.create().fromJson(json, WxError.class); - return error; - } - @Override public String toString() { - return "微信错误: errcode=" + errorCode + ", errmsg=" + errorMsg + "\njson:" + json; + if (json != null) { + return json; + } + return "错误: Code=" + errorCode + ", Msg=" + errorMsg; } - public static Builder newBuilder(){ - return new Builder(); - } - - public static class Builder{ + public static class Builder { private int errorCode; private String errorMsg; - + public Builder setErrorCode(int errorCode) { this.errorCode = errorCode; return this; } - + public Builder setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; return this; } - - public WxError build(){ + + public WxError build() { WxError wxError = new WxError(); wxError.setErrorCode(this.errorCode); wxError.setErrorMsg(this.errorMsg); return wxError; } - + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java index 500dc0000a..2e4b5fcd37 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/bean/result/WxMediaUploadResult.java @@ -6,12 +6,16 @@ public class WxMediaUploadResult implements Serializable { private static final long serialVersionUID = 330834334738622341L; - + private String type; private String mediaId; private String thumbMediaId; private long createdAt; + public static WxMediaUploadResult fromJson(String json) { + return WxGsonBuilder.create().fromJson(json, WxMediaUploadResult.class); + } + public String getType() { return type; } @@ -44,14 +48,10 @@ public void setThumbMediaId(String thumbMediaId) { this.thumbMediaId = thumbMediaId; } - public static WxMediaUploadResult fromJson(String json) { - return WxGsonBuilder.create().fromJson(json, WxMediaUploadResult.class); - } - @Override public String toString() { return "WxUploadResult [type=" + type + ", media_id=" + mediaId + ", thumb_media_id=" + thumbMediaId - + ", created_at=" + createdAt + "]"; + + ", created_at=" + createdAt + "]"; } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java index d1dc569be5..7e2e19418e 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/exception/WxErrorException.java @@ -5,7 +5,7 @@ public class WxErrorException extends Exception { private static final long serialVersionUID = -6357149550353160810L; - + private WxError error; public WxErrorException(WxError error) { @@ -17,5 +17,5 @@ public WxError getError() { return error; } - + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/Constants.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/Constants.java index 33518f176b..f30a0ae0d0 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/Constants.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/Constants.java @@ -26,6 +26,6 @@ public class Constants { - public static final String Package = "me.chanjar.weixin.common.session"; + public static final String Package = "me.chanjar.weixin.common.session"; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSession.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSession.java index 283672af73..77d4d28291 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSession.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSession.java @@ -8,6 +8,11 @@ public interface InternalSession { */ WxSession getSession(); + /** + * Return the isValid flag for this session. + */ + boolean isValid(); + /** * Set the isValid flag for this session. * @@ -15,11 +20,6 @@ public interface InternalSession { */ void setValid(boolean isValid); - /** - * Return the isValid flag for this session. - */ - boolean isValid(); - /** * Return the session identifier for this session. */ diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSessionManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSessionManager.java index bb9a8dca58..a92e107154 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSessionManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/InternalSessionManager.java @@ -7,11 +7,10 @@ public interface InternalSessionManager { * specified session id (if any); otherwise return null. * * @param id The session id for the session to be returned - * - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason - * @exception java.io.IOException if an input/output error occurs while - * processing this request + * @throws IllegalStateException if a new session cannot be + * instantiated for any reason + * @throws java.io.IOException if an input/output error occurs while + * processing this request */ InternalSession findSession(String id); @@ -23,10 +22,10 @@ public interface InternalSessionManager { * null. * * @param sessionId The session id which should be used to create the - * new session; if null, a new session id will be - * generated - * @exception IllegalStateException if a new session cannot be - * instantiated for any reason + * new session; if null, a new session id will be + * generated + * @throws IllegalStateException if a new session cannot be + * instantiated for any reason */ InternalSession createSession(String sessionId); @@ -40,8 +39,8 @@ public interface InternalSessionManager { /** * Remove this Session from the active Sessions for this Manager. * - * @param session Session to be removed - * @param update Should the expiration statistics be updated + * @param session Session to be removed + * @param update Should the expiration statistics be updated */ void remove(InternalSession session, boolean update); @@ -59,6 +58,7 @@ public interface InternalSessionManager { * @return number of sessions active */ int getActiveSessions(); + /** * Get a session from the recycled ones or create a new empty one. * The PersistentManager manager does not need to create session data @@ -88,6 +88,7 @@ public interface InternalSessionManager { * 要和{@link #setBackgroundProcessorDelay(int)}联合起来看 * 如果把这个数字设置为6(默认),那么就是说manager要等待 6 * backgroundProcessorDay的时间才会清理过期session * + * * @param processExpiresFrequency the new manager checks frequency */ void setProcessExpiresFrequency(int processExpiresFrequency); @@ -97,6 +98,7 @@ public interface InternalSessionManager { * Set the manager background processor delay * 设置manager sleep几秒,尝试执行一次background操作(清理过期session) * + * * @param backgroundProcessorDelay */ void setBackgroundProcessorDelay(int backgroundProcessorDelay); @@ -106,6 +108,7 @@ public interface InternalSessionManager { * Set the maximum number of active Sessions allowed, or -1 for * no limit. * 设置最大活跃session数,默认无限 + * * @param max The new maximum number of sessions */ void setMaxActiveSessions(int max); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/LocalStrings.properties b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/LocalStrings.properties index ede528f739..d3ded84b8d 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/LocalStrings.properties +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/LocalStrings.properties @@ -12,7 +12,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - applicationSession.session.ise=invalid session state applicationSession.value.iae=null value fileStore.saving=Saving Session {0} to file {1} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java index b482c2b7c1..9212c619ec 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSession.java @@ -12,17 +12,68 @@ public class StandardSession implements WxSession, InternalSession { * The string manager for this package. */ protected static final StringManager sm = - StringManager.getManager(Constants.Package); - + StringManager.getManager(Constants.Package); + /** + * Type array. + */ + protected static final String EMPTY_ARRAY[] = new String[0]; // ------------------------------ WxSession protected Map attributes = new ConcurrentHashMap(); + /** + * The session identifier of this Session. + */ + protected String id = null; + /** + * Flag indicating whether this session is valid or not. + */ + protected volatile boolean isValid = false; + /** + * We are currently processing a session expiration, so bypass + * certain IllegalStateException tests. NOTE: This value is not + * included in the serialized version of this object. + */ + protected transient volatile boolean expiring = false; + /** + * The Manager with which this Session is associated. + */ + protected transient InternalSessionManager manager = null; + + // ------------------------------ InternalSession + /** + * The time this session was created, in milliseconds since midnight, + * January 1, 1970 GMT. + */ + protected long creationTime = 0L; + /** + * The current accessed time for this session. + */ + protected volatile long thisAccessedTime = creationTime; + /** + * The default maximum inactive interval for Sessions created by + * this Manager. + */ + protected int maxInactiveInterval = 30 * 60; + /** + * The facade associated with this session. NOTE: This value is not + * included in the serialized version of this object. + */ + protected transient StandardSessionFacade facade = null; + /** + * The access count for this session. + */ + protected transient AtomicInteger accessCount = null; + + public StandardSession(InternalSessionManager manager) { + this.manager = manager; + this.accessCount = new AtomicInteger(); + } @Override public Object getAttribute(String name) { if (!isValidInternal()) throw new IllegalStateException - (sm.getString("sessionImpl.getAttribute.ise")); + (sm.getString("sessionImpl.getAttribute.ise")); if (name == null) return null; @@ -33,7 +84,7 @@ public Object getAttribute(String name) { public Enumeration getAttributeNames() { if (!isValidInternal()) throw new IllegalStateException - (sm.getString("sessionImpl.getAttributeNames.ise")); + (sm.getString("sessionImpl.getAttributeNames.ise")); Set names = new HashSet(); names.addAll(attributes.keySet()); @@ -45,7 +96,7 @@ public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) throw new IllegalArgumentException - (sm.getString("sessionImpl.setAttribute.namenull")); + (sm.getString("sessionImpl.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { @@ -56,97 +107,32 @@ public void setAttribute(String name, Object value) { // Validate our current state if (!isValidInternal()) throw new IllegalStateException(sm.getString( - "sessionImpl.setAttribute.ise", getIdInternal())); + "sessionImpl.setAttribute.ise", getIdInternal())); attributes.put(name, value); } - @Override public void removeAttribute(String name) { removeAttributeInternal(name); } - @Override public void invalidate() { if (!isValidInternal()) throw new IllegalStateException - (sm.getString("sessionImpl.invalidate.ise")); + (sm.getString("sessionImpl.invalidate.ise")); // Cause this session to expire expire(); } - // ------------------------------ InternalSession - /** - * The session identifier of this Session. - */ - protected String id = null; - - /** - * Flag indicating whether this session is valid or not. - */ - protected volatile boolean isValid = false; - - /** - * We are currently processing a session expiration, so bypass - * certain IllegalStateException tests. NOTE: This value is not - * included in the serialized version of this object. - */ - protected transient volatile boolean expiring = false; - - /** - * The Manager with which this Session is associated. - */ - protected transient InternalSessionManager manager = null; - - /** - * Type array. - */ - protected static final String EMPTY_ARRAY[] = new String[0]; - - /** - * The time this session was created, in milliseconds since midnight, - * January 1, 1970 GMT. - */ - protected long creationTime = 0L; - - /** - * The current accessed time for this session. - */ - protected volatile long thisAccessedTime = creationTime; - - /** - * The default maximum inactive interval for Sessions created by - * this Manager. - */ - protected int maxInactiveInterval = 30 * 60; - - /** - * The facade associated with this session. NOTE: This value is not - * included in the serialized version of this object. - */ - protected transient StandardSessionFacade facade = null; - - /** - * The access count for this session. - */ - protected transient AtomicInteger accessCount = null; - - - public StandardSession(InternalSessionManager manager) { - this.manager = manager; - this.accessCount = new AtomicInteger(); - } - - @Override public WxSession getSession() { - if (facade == null){ + if (facade == null) { facade = new StandardSessionFacade(this); } return (facade); @@ -161,16 +147,6 @@ protected boolean isValidInternal() { return this.isValid; } - /** - * Set the isValid flag for this session. - * - * @param isValid The new value for the isValid flag - */ - @Override - public void setValid(boolean isValid) { - this.isValid = isValid; - } - @Override public boolean isValid() { if (!this.isValid) { @@ -197,6 +173,16 @@ public boolean isValid() { return this.isValid; } + /** + * Set the isValid flag for this session. + * + * @param isValid The new value for the isValid flag + */ + @Override + public void setValid(boolean isValid) { + this.isValid = isValid; + } + @Override public String getIdInternal() { return (this.id); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java index f3a0269582..cd14a1fd4a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/StandardSessionManager.java @@ -13,60 +13,26 @@ */ public class StandardSessionManager implements WxSessionManager, InternalSessionManager { - protected final Logger log = LoggerFactory.getLogger(StandardSessionManager.class); - protected static final StringManager sm = - StringManager.getManager(Constants.Package); - + StringManager.getManager(Constants.Package); /** - * The set of currently active Sessions for this Manager, keyed by - * session identifier. + * The descriptive name of this Manager implementation (for logging). */ - protected Map sessions = new ConcurrentHashMap(); - - @Override - public WxSession getSession(String sessionId) { - return getSession(sessionId, true); - } - - @Override - public WxSession getSession(String sessionId, boolean create) { - if (sessionId == null) { - throw new IllegalStateException - (sm.getString("sessionManagerImpl.getSession.ise")); - } - - InternalSession session = findSession(sessionId); - if ((session != null) && !session.isValid()) { - session = null; - } - if (session != null) { - session.access(); - return session.getSession(); - } - - // Create a new session if requested and the response is not committed - if (!create) { - return (null); - } - - session = createSession(sessionId); - - if (session == null) { - return null; - } - - session.access(); - return session.getSession(); - } + private static final String name = "SessionManagerImpl"; + protected final Logger log = LoggerFactory.getLogger(StandardSessionManager.class); + private final Object maxActiveUpdateLock = new Object(); + /** + * 后台清理线程是否已经开启 + */ + private final AtomicBoolean backgroundProcessStarted = new AtomicBoolean(false); // -------------------------------------- InternalSessionManager /** - * The descriptive name of this Manager implementation (for logging). + * The set of currently active Sessions for this Manager, keyed by + * session identifier. */ - private static final String name = "SessionManagerImpl"; - + protected Map sessions = new ConcurrentHashMap(); /** * The maximum number of active Sessions allowed, or -1 for no limit. */ @@ -84,22 +50,13 @@ public WxSession getSession(String sessionId, boolean create) { protected int maxInactiveInterval = 30 * 60; // Number of sessions created by this manager - protected long sessionCounter=0; - - protected volatile int maxActive=0; - - private final Object maxActiveUpdateLock = new Object(); + protected long sessionCounter = 0; + protected volatile int maxActive = 0; /** * Processing time during session expiration. */ protected long processingTime = 0; - - /** - * Iteration count for background processing. - */ - private int count = 0; - /** * Frequency of the session expiration, and related manager operations. * Manager operations will be done once for the specified amount of @@ -107,16 +64,50 @@ public WxSession getSession(String sessionId, boolean create) { * checks will occur). */ protected int processExpiresFrequency = 6; - /** * background processor delay in seconds */ protected int backgroundProcessorDelay = 10; - /** - * 后台清理线程是否已经开启 + * Iteration count for background processing. */ - private final AtomicBoolean backgroundProcessStarted = new AtomicBoolean(false); + private int count = 0; + + @Override + public WxSession getSession(String sessionId) { + return getSession(sessionId, true); + } + + @Override + public WxSession getSession(String sessionId, boolean create) { + if (sessionId == null) { + throw new IllegalStateException + (sm.getString("sessionManagerImpl.getSession.ise")); + } + + InternalSession session = findSession(sessionId); + if ((session != null) && !session.isValid()) { + session = null; + } + if (session != null) { + session.access(); + return session.getSession(); + } + + // Create a new session if requested and the response is not committed + if (!create) { + return (null); + } + + session = createSession(sessionId); + + if (session == null) { + return null; + } + + session.access(); + return session.getSession(); + } @Override public void remove(InternalSession session) { @@ -131,7 +122,6 @@ public void remove(InternalSession session, boolean update) { } - @Override public InternalSession findSession(String id) { @@ -145,15 +135,15 @@ public InternalSession findSession(String id) { public InternalSession createSession(String sessionId) { if (sessionId == null) { throw new IllegalStateException - (sm.getString("sessionManagerImpl.createSession.ise")); + (sm.getString("sessionManagerImpl.createSession.ise")); } if ((maxActiveSessions >= 0) && - (getActiveSessions() >= maxActiveSessions)) { + (getActiveSessions() >= maxActiveSessions)) { rejectedSessions++; throw new TooManyActiveSessionsException( - sm.getString("sessionManagerImpl.createSession.tmase"), - maxActiveSessions); + sm.getString("sessionManagerImpl.createSession.tmase"), + maxActiveSessions); } // Recycle or create a Session instance @@ -216,14 +206,14 @@ public void run() { sessions.put(session.getIdInternal(), session); int size = getActiveSessions(); - if( size > maxActive ) { - synchronized(maxActiveUpdateLock) { - if( size > maxActive ) { + if (size > maxActive) { + synchronized (maxActiveUpdateLock) { + if (size > maxActive) { maxActive = size; } } } - + } /** @@ -251,19 +241,19 @@ public void processExpires() { long timeNow = System.currentTimeMillis(); InternalSession sessions[] = findSessions(); - int expireHere = 0 ; + int expireHere = 0; - if(log.isDebugEnabled()) + if (log.isDebugEnabled()) log.debug("Start expire sessions {} at {} sessioncount {}", getName(), timeNow, sessions.length); for (int i = 0; i < sessions.length; i++) { - if (sessions[i]!=null && !sessions[i].isValid()) { + if (sessions[i] != null && !sessions[i].isValid()) { expireHere++; } } long timeEnd = System.currentTimeMillis(); - if(log.isDebugEnabled()) + if (log.isDebugEnabled()) log.debug("End expire sessions {} processingTime {} expired sessions: {}", getName(), timeEnd - timeNow, expireHere); - processingTime += ( timeEnd - timeNow ); + processingTime += (timeEnd - timeNow); } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java index bd0c0f2ba6..69fd89f80f 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/session/TooManyActiveSessionsException.java @@ -21,37 +21,34 @@ * reached and the server is refusing to create any new sessions. */ public class TooManyActiveSessionsException - extends IllegalStateException -{ - private static final long serialVersionUID = 1L; + extends IllegalStateException { + private static final long serialVersionUID = 1L; - /** - * The maximum number of active sessions the server will tolerate. - */ - private final int maxActiveSessions; + /** + * The maximum number of active sessions the server will tolerate. + */ + private final int maxActiveSessions; - /** - * Creates a new TooManyActiveSessionsException. - * - * @param message A description for the exception. - * @param maxActive The maximum number of active sessions allowed by the - * session manager. - */ - public TooManyActiveSessionsException(String message, - int maxActive) - { - super(message); - - maxActiveSessions = maxActive; - } - - /** - * Gets the maximum number of sessions allowed by the session manager. - * - * @return The maximum number of sessions allowed by the session manager. - */ - public int getMaxActiveSessions() - { - return maxActiveSessions; - } + /** + * Creates a new TooManyActiveSessionsException. + * + * @param message A description for the exception. + * @param maxActive The maximum number of active sessions allowed by the + * session manager. + */ + public TooManyActiveSessionsException(String message, + int maxActive) { + super(message); + + maxActiveSessions = maxActive; + } + + /** + * Gets the maximum number of sessions allowed by the session manager. + * + * @return The maximum number of sessions allowed by the session manager. + */ + public int getMaxActiveSessions() { + return maxActiveSessions; + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/StringUtils.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/StringUtils.java index 4234a8c8c9..49acaeeaf7 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/StringUtils.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/StringUtils.java @@ -7,7 +7,7 @@ public class StringUtils { /** *

Checks if a CharSequence is whitespace, empty ("") or null.

- * + *

*

    * StringUtils.isBlank(null)      = true
    * StringUtils.isBlank("")        = true
@@ -16,9 +16,8 @@ public class StringUtils {
    * StringUtils.isBlank("  bob  ") = false
    * 
* - * @param cs the CharSequence to check, may be null + * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace - * @since 2.0 * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) */ public static boolean isBlank(CharSequence cs) { @@ -36,7 +35,7 @@ public static boolean isBlank(CharSequence cs) { /** *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

- * + *

*

    * StringUtils.isNotBlank(null)      = false
    * StringUtils.isNotBlank("")        = false
@@ -45,10 +44,9 @@ public static boolean isBlank(CharSequence cs) {
    * StringUtils.isNotBlank("  bob  ") = true
    * 
* - * @param cs the CharSequence to check, may be null + * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is - * not empty and not null and not whitespace - * @since 2.0 + * not empty and not null and not whitespace * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) */ public static boolean isNotBlank(CharSequence cs) { @@ -57,7 +55,7 @@ public static boolean isNotBlank(CharSequence cs) { /** *

Checks if a CharSequence is empty ("") or null.

- * + *

*

    * StringUtils.isEmpty(null)      = true
    * StringUtils.isEmpty("")        = true
@@ -65,12 +63,12 @@ public static boolean isNotBlank(CharSequence cs) {
    * StringUtils.isEmpty("bob")     = false
    * StringUtils.isEmpty("  bob  ") = false
    * 
- * + *

*

NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().

* - * @param cs the CharSequence to check, may be null + * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) */ @@ -80,7 +78,7 @@ public static boolean isEmpty(CharSequence cs) { /** *

Checks if a CharSequence is not empty ("") and not null.

- * + *

*

    * StringUtils.isNotEmpty(null)      = false
    * StringUtils.isNotEmpty("")        = false
@@ -89,7 +87,7 @@ public static boolean isEmpty(CharSequence cs) {
    * StringUtils.isNotEmpty("  bob  ") = true
    * 
* - * @param cs the CharSequence to check, may be null + * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is not empty and not null * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence) */ diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java index de777dc9fa..6cd4a5efad 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/ByteGroup.java @@ -3,24 +3,24 @@ import java.util.ArrayList; public class ByteGroup { - ArrayList byteContainer = new ArrayList(); + ArrayList byteContainer = new ArrayList(); public byte[] toBytes() { - byte[] bytes = new byte[byteContainer.size()]; - for (int i = 0; i < byteContainer.size(); i++) { - bytes[i] = byteContainer.get(i); - } - return bytes; - } + byte[] bytes = new byte[byteContainer.size()]; + for (int i = 0; i < byteContainer.size(); i++) { + bytes[i] = byteContainer.get(i); + } + return bytes; + } - public ByteGroup addBytes(byte[] bytes) { - for (byte b : bytes) { - byteContainer.add(b); - } - return this; - } + public ByteGroup addBytes(byte[] bytes) { + for (byte b : bytes) { + byteContainer.add(b); + } + return this; + } - public int size() { - return byteContainer.size(); - } + public int size() { + return byteContainer.size(); + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java index 35771c471c..2a01aae07b 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/PKCS7Encoder.java @@ -1,6 +1,6 @@ /** * 对公众平台发送给公众账号的消息加解密示例代码. - * + * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ @@ -16,53 +16,53 @@ */ public class PKCS7Encoder { - private static final Charset CHARSET = Charset.forName("utf-8"); - private static final int BLOCK_SIZE = 32; + private static final Charset CHARSET = Charset.forName("utf-8"); + private static final int BLOCK_SIZE = 32; - /** - * 获得对明文进行补位填充的字节. - * - * @param count 需要进行填充补位操作的明文字节个数 - * @return 补齐用的字节数组 - */ - public static byte[] encode(int count) { - // 计算需要填充的位数 - int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); - if (amountToPad == 0) { - amountToPad = BLOCK_SIZE; - } - // 获得补位所用的字符 - char padChr = chr(amountToPad); - String tmp = new String(); - for (int index = 0; index < amountToPad; index++) { - tmp += padChr; - } - return tmp.getBytes(CHARSET); - } + /** + * 获得对明文进行补位填充的字节. + * + * @param count 需要进行填充补位操作的明文字节个数 + * @return 补齐用的字节数组 + */ + public static byte[] encode(int count) { + // 计算需要填充的位数 + int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); + if (amountToPad == 0) { + amountToPad = BLOCK_SIZE; + } + // 获得补位所用的字符 + char padChr = chr(amountToPad); + String tmp = new String(); + for (int index = 0; index < amountToPad; index++) { + tmp += padChr; + } + return tmp.getBytes(CHARSET); + } - /** - * 删除解密后明文的补位字符 - * - * @param decrypted 解密后的明文 - * @return 删除补位字符后的明文 - */ - public static byte[] decode(byte[] decrypted) { - int pad = (int) decrypted[decrypted.length - 1]; - if (pad < 1 || pad > 32) { - pad = 0; - } - return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); - } + /** + * 删除解密后明文的补位字符 + * + * @param decrypted 解密后的明文 + * @return 删除补位字符后的明文 + */ + public static byte[] decode(byte[] decrypted) { + int pad = (int) decrypted[decrypted.length - 1]; + if (pad < 1 || pad > 32) { + pad = 0; + } + return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); + } - /** - * 将数字转化成ASCII码对应的字符,用于对明文进行补码 - * - * @param a 需要转化的数字 - * @return 转化得到的字符 - */ - public static char chr(int a) { - byte target = (byte) (a & 0xFF); - return (char) target; - } + /** + * 将数字转化成ASCII码对应的字符,用于对明文进行补码 + * + * @param a 需要转化的数字 + * @return 转化得到的字符 + */ + public static char chr(int a) { + byte target = (byte) (a & 0xFF); + return (char) target; + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java index 38a6c28db6..4f7503c62b 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java @@ -1,10 +1,10 @@ package me.chanjar.weixin.common.util.crypto; +import org.apache.commons.codec.digest.DigestUtils; + import java.security.NoSuchAlgorithmException; import java.util.Arrays; -import org.apache.commons.codec.digest.DigestUtils; - /** * Created by Daniel Qian on 14/10/19. */ @@ -37,4 +37,4 @@ public static String genWithAmple(String... arr) throws NoSuchAlgorithmException } return DigestUtils.sha1Hex(sb.toString()); } - } +} diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java index 874133349f..c1341e7bc4 100755 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java @@ -2,6 +2,10 @@ * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. + *

+ * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi */ // ------------------------------------------------------------------------ @@ -62,12 +66,51 @@ public WxCryptUtil() { * @param appidOrCorpid 公众平台appid/corpid */ public WxCryptUtil(String token, String encodingAesKey, - String appidOrCorpid) { + String appidOrCorpid) { this.token = token; this.appidOrCorpid = appidOrCorpid; this.aesKey = Base64.decodeBase64(encodingAesKey + "="); } + /** + * 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3) + * @param packageParams 原始参数 + * @param signKey 加密Key(即 商户Key) + * @return 签名字符串 + */ + public static String createSign(Map packageParams, + String signKey) { + SortedMap sortedMap = new TreeMap(); + sortedMap.putAll(packageParams); + + List keys = new ArrayList(packageParams.keySet()); + Collections.sort(keys); + + StringBuffer toSign = new StringBuffer(); + for (String key : keys) { + String value = packageParams.get(key); + if (null != value && !"".equals(value) && !"sign".equals(key) + && !"key".equals(key)) { + toSign.append(key + "=" + value + "&"); + } + } + toSign.append("key=" + signKey); + String sign = DigestUtils.md5Hex(toSign.toString()).toUpperCase(); + return sign; + } + + static String extractEncryptPart(String xml) { + try { + DocumentBuilder db = builderLocal.get(); + Document document = db.parse(new InputSource(new StringReader(xml))); + + Element root = document.getDocumentElement(); + return root.getElementsByTagName("Encrypt").item(0).getTextContent(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + /** * 将公众平台回复用户的消息加密打包. *

    @@ -107,7 +150,7 @@ protected String encrypt(String randomStr, String plainText) { byte[] randomStringBytes = randomStr.getBytes(CHARSET); byte[] plainTextBytes = plainText.getBytes(CHARSET); byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder( - plainTextBytes.length); + plainTextBytes.length); byte[] appIdBytes = appidOrCorpid.getBytes(CHARSET); // randomStr + networkBytesOrder + text + appid @@ -157,7 +200,7 @@ protected String encrypt(String randomStr, String plainText) { * @return 解密后的原文 */ public String decrypt(String msgSignature, String timeStamp, String nonce, - String encryptedXml) { + String encryptedXml) { // 密钥,公众账号的app corpSecret // 提取密文 String cipherText = extractEncryptPart(encryptedXml); @@ -190,7 +233,7 @@ public String decrypt(String cipherText) { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); IvParameterSpec iv = new IvParameterSpec( - Arrays.copyOfRange(aesKey, 0, 16)); + Arrays.copyOfRange(aesKey, 0, 16)); cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); // 使用BASE64对密文进行解码 @@ -213,9 +256,9 @@ public String decrypt(String cipherText) { int xmlLength = bytesNetworkOrder2Number(networkOrder); xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), - CHARSET); + CHARSET); from_appid = new String( - Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET); + Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET); } catch (Exception e) { throw new RuntimeException(e); } @@ -229,33 +272,6 @@ public String decrypt(String cipherText) { } - /** - * 微信公众号支付签名算法(详见:http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=4_3) - * @param packageParams 原始参数 - * @param signKey 加密Key(即 商户Key) - * @return 签名字符串 - */ - public static String createSign(Map packageParams, - String signKey) { - SortedMap sortedMap = new TreeMap(); - sortedMap.putAll(packageParams); - - List keys = new ArrayList(packageParams.keySet()); - Collections.sort(keys); - - StringBuffer toSign = new StringBuffer(); - for (String key : keys) { - String value = packageParams.get(key); - if (null != value && !"".equals(value) && !"sign".equals(key) - && !"key".equals(key)) { - toSign.append(key + "=" + value + "&"); - } - } - toSign.append("key=" + signKey); - String sign = DigestUtils.md5Hex(toSign.toString()).toUpperCase(); - return sign; - } - /** * 将一个数字转换成生成4个字节的网络字节序bytes数组 * @@ -308,24 +324,12 @@ private String genRandomStr() { * @return 生成的xml字符串 */ private String generateXml(String encrypt, String signature, String timestamp, - String nonce) { + String nonce) { String format = "\n" + "\n" - + "\n" - + "%3$s\n" + "\n" - + ""; + + "\n" + + "%3$s\n" + "\n" + + ""; return String.format(format, encrypt, signature, timestamp, nonce); } - static String extractEncryptPart(String xml) { - try { - DocumentBuilder db = builderLocal.get(); - Document document = db.parse(new InputSource(new StringReader(xml))); - - Element root = document.getDocumentElement(); - return root.getElementsByTagName("Encrypt").item(0).getTextContent(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java index 35c50e3ff9..706ced399d 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java @@ -10,17 +10,18 @@ public class FileUtils { /** * 创建临时文件 + * * @param inputStream - * @param name 文件名 - * @param ext 扩展名 - * @param tmpDirFile 临时文件夹目录 + * @param name 文件名 + * @param ext 扩展名 + * @param tmpDirFile 临时文件夹目录 */ public static File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException { FileOutputStream fos = null; try { File tmpFile; if (tmpDirFile == null) { - tmpFile = File.createTempFile(name, '.' + ext); + tmpFile = File.createTempFile(name, '.' + ext); } else { tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile); } @@ -51,12 +52,13 @@ public static File createTmpFile(InputStream inputStream, String name, String ex /** * 创建临时文件 + * * @param inputStream - * @param name 文件名 - * @param ext 扩展名 + * @param name 文件名 + * @param ext 扩展名 */ public static File createTmpFile(InputStream inputStream, String name, String ext) throws IOException { return createTmpFile(inputStream, name, ext, null); } - + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpClientBuilder.java index c821d86c60..8bd900ca3d 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/ApacheHttpClientBuilder.java @@ -10,36 +10,42 @@ public interface ApacheHttpClientBuilder { /** * 构建httpclient实例 + * * @return new instance of CloseableHttpClient */ CloseableHttpClient build(); /** * 代理服务器地址 + * * @param httpProxyHost */ ApacheHttpClientBuilder httpProxyHost(String httpProxyHost); /** * 代理服务器端口 + * * @param httpProxyPort */ ApacheHttpClientBuilder httpProxyPort(int httpProxyPort); /** * 代理服务器用户名 + * * @param httpProxyUsername */ ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername); /** * 代理服务器密码 + * * @param httpProxyPassword */ ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword); /** * ssl连接socket工厂 + * * @param sslConnectionSocketFactory */ ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpHttpClientBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java similarity index 61% rename from weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpHttpClientBuilder.java rename to weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java index aa20fa0b40..4acc766215 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpHttpClientBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java @@ -28,12 +28,12 @@ * httpclient 连接管理器 */ @NotThreadSafe -public class DefaultApacheHttpHttpClientBuilder implements ApacheHttpClientBuilder { +public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder { private int connectionRequestTimeout = 3000; private int connectionTimeout = 5000; private int soTimeout = 5000; private int idleConnTimeout = 60000; - private int checkWaitTime = 5000; + private int checkWaitTime = 60000; private int maxConnPerHost = 10; private int maxTotalConn = 50; private String userAgent; @@ -51,109 +51,112 @@ public boolean retryRequest(IOException exception, int executionCount, HttpConte private String httpProxyUsername; private String httpProxyPassword; - /** - * 连接管理器 - */ - private PoolingHttpClientConnectionManager connectionManager; /** * 闲置连接监控线程 */ private IdleConnectionMonitorThread idleConnectionMonitorThread; - /** - * httpClientBuilder - */ private HttpClientBuilder httpClientBuilder; private boolean prepared = false; - private DefaultApacheHttpHttpClientBuilder() { + private DefaultApacheHttpClientBuilder() { } - public static DefaultApacheHttpHttpClientBuilder get() { - return new DefaultApacheHttpHttpClientBuilder(); + public static DefaultApacheHttpClientBuilder get() { + return new DefaultApacheHttpClientBuilder(); } + @Override public ApacheHttpClientBuilder httpProxyHost(String httpProxyHost) { this.httpProxyHost = httpProxyHost; return this; } + @Override public ApacheHttpClientBuilder httpProxyPort(int httpProxyPort) { this.httpProxyPort = httpProxyPort; return this; } + @Override public ApacheHttpClientBuilder httpProxyUsername(String httpProxyUsername) { this.httpProxyUsername = httpProxyUsername; return this; } + @Override public ApacheHttpClientBuilder httpProxyPassword(String httpProxyPassword) { this.httpProxyPassword = httpProxyPassword; return this; } - public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory){ + @Override + public ApacheHttpClientBuilder sslConnectionSocketFactory(SSLConnectionSocketFactory sslConnectionSocketFactory) { this.sslConnectionSocketFactory = sslConnectionSocketFactory; return this; } public IdleConnectionMonitorThread getIdleConnectionMonitorThread() { - return idleConnectionMonitorThread; + return this.idleConnectionMonitorThread; } - private void prepare(){ + private void prepare() { Registry registry = RegistryBuilder.create() - .register("http", plainConnectionSocketFactory) - .register("https", sslConnectionSocketFactory) - .build(); - connectionManager = new PoolingHttpClientConnectionManager(registry); - connectionManager.setMaxTotal(maxTotalConn); - connectionManager.setDefaultMaxPerRoute(maxConnPerHost); + .register("http", this.plainConnectionSocketFactory) + .register("https", this.sslConnectionSocketFactory) + .build(); + + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry); + connectionManager.setMaxTotal(this.maxTotalConn); + connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost); connectionManager.setDefaultSocketConfig( - SocketConfig.copy(SocketConfig.DEFAULT) - .setSoTimeout(soTimeout) - .build() + SocketConfig.copy(SocketConfig.DEFAULT) + .setSoTimeout(this.soTimeout) + .build() ); - idleConnectionMonitorThread = new IdleConnectionMonitorThread(connectionManager, idleConnTimeout, checkWaitTime); - idleConnectionMonitorThread.setDaemon(true); - idleConnectionMonitorThread.start(); - - httpClientBuilder = HttpClients.custom() - .setConnectionManager(connectionManager) - .setDefaultRequestConfig( - RequestConfig.custom() - .setSocketTimeout(soTimeout) - .setConnectTimeout(connectionTimeout) - .setConnectionRequestTimeout(connectionRequestTimeout) - .build() - ) - .setRetryHandler(httpRequestRetryHandler); - - if (StringUtils.isNotBlank(httpProxyHost) && StringUtils.isNotBlank(httpProxyUsername)) { + this.idleConnectionMonitorThread = new IdleConnectionMonitorThread( + connectionManager, this.idleConnTimeout, this.checkWaitTime); + this.idleConnectionMonitorThread.setDaemon(true); + this.idleConnectionMonitorThread.start(); + + this.httpClientBuilder = HttpClients.custom() + .setConnectionManager(connectionManager) + .setDefaultRequestConfig( + RequestConfig.custom() + .setSocketTimeout(this.soTimeout) + .setConnectTimeout(this.connectionTimeout) + .setConnectionRequestTimeout(this.connectionRequestTimeout) + .build() + ) + .setRetryHandler(this.httpRequestRetryHandler); + + if (StringUtils.isNotBlank(this.httpProxyHost) + && StringUtils.isNotBlank(this.httpProxyUsername)) { // 使用代理服务器 需要用户认证的代理服务器 - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials( - new AuthScope(httpProxyHost, httpProxyPort), - new UsernamePasswordCredentials(httpProxyUsername, httpProxyPassword)); - httpClientBuilder.setDefaultCredentialsProvider(credsProvider); + CredentialsProvider provider = new BasicCredentialsProvider(); + provider.setCredentials( + new AuthScope(this.httpProxyHost, this.httpProxyPort), + new UsernamePasswordCredentials(this.httpProxyUsername, + this.httpProxyPassword)); + this.httpClientBuilder.setDefaultCredentialsProvider(provider); } - if (StringUtils.isNotBlank(userAgent)) { - httpClientBuilder.setUserAgent(userAgent); + if (StringUtils.isNotBlank(this.userAgent)) { + this.httpClientBuilder.setUserAgent(this.userAgent); } } + @Override public CloseableHttpClient build() { - if(!prepared){ + if (!this.prepared) { prepare(); - prepared = true; + this.prepared = true; } - return httpClientBuilder.build(); + return this.httpClientBuilder.build(); } public static class IdleConnectionMonitorThread extends Thread { @@ -172,11 +175,12 @@ public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr, int idle @Override public void run() { try { - while (!shutdown) { + while (!this.shutdown) { synchronized (this) { - wait(checkWaitTime); - connMgr.closeExpiredConnections(); - connMgr.closeIdleConnections(idleConnTimeout, TimeUnit.MILLISECONDS); + wait(this.checkWaitTime); + this.connMgr.closeExpiredConnections(); + this.connMgr.closeIdleConnections(this.idleConnTimeout, + TimeUnit.MILLISECONDS); } } } catch (InterruptedException ignore) { @@ -190,7 +194,7 @@ public void trigger() { } public void shutdown() { - shutdown = true; + this.shutdown = true; synchronized (this) { notifyAll(); } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java index 1bf13b9c63..6433c472bd 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/InputStreamResponseHandler.java @@ -1,8 +1,5 @@ package me.chanjar.weixin.common.util.http; -import java.io.IOException; -import java.io.InputStream; - import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; @@ -10,10 +7,13 @@ import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; +import java.io.IOException; +import java.io.InputStream; + public class InputStreamResponseHandler implements ResponseHandler { public static final ResponseHandler INSTANCE = new InputStreamResponseHandler(); - + public InputStream handleResponse(final HttpResponse response) throws IOException { final StatusLine statusLine = response.getStatusLine(); final HttpEntity entity = response.getEntity(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java index 100113042d..a2ff7a561c 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java @@ -18,39 +18,39 @@ */ public class JoddGetRequestExecutor implements RequestExecutor { - @Override - public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String queryParam) throws WxErrorException, IOException { - if (queryParam != null) { - if (uri.indexOf('?') == -1) { - uri += '?'; - } - uri += uri.endsWith("?") ? queryParam : '&' + queryParam; - } - - SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider(); - - if (httpProxy != null) { - ProxyInfo proxyInfoObj = new ProxyInfo( - ProxyInfo.ProxyType.HTTP, - httpProxy.getHostName(), - httpProxy.getPort(), "", ""); - provider.useProxy(proxyInfoObj); - } - - HttpRequest request = HttpRequest.get(uri); - request.method("GET"); - request.charset("UTF-8"); - - HttpResponse response = request.open(provider).send(); - response.charset("UTF-8"); - String result = response.bodyText(); - - WxError error = WxError.fromJson(result); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return result; + @Override + public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, + String queryParam) throws WxErrorException, IOException { + if (queryParam != null) { + if (uri.indexOf('?') == -1) { + uri += '?'; + } + uri += uri.endsWith("?") ? queryParam : '&' + queryParam; } + SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider(); + + if (httpProxy != null) { + ProxyInfo proxyInfoObj = new ProxyInfo( + ProxyInfo.ProxyType.HTTP, + httpProxy.getHostName(), + httpProxy.getPort(), "", ""); + provider.useProxy(proxyInfoObj); + } + + HttpRequest request = HttpRequest.get(uri); + request.method("GET"); + request.charset("UTF-8"); + + HttpResponse response = request.open(provider).send(); + response.charset("UTF-8"); + String result = response.bodyText(); + + WxError error = WxError.fromJson(result); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return result; + } + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java index d054835b4e..771fb46e34 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java @@ -18,33 +18,33 @@ */ public class JoddPostRequestExecutor implements RequestExecutor { - @Override - public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, - String postEntity) throws WxErrorException, IOException { - SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider(); - - if (httpProxy != null) { - ProxyInfo proxyInfoObj = new ProxyInfo( - ProxyInfo.ProxyType.HTTP, - httpProxy.getAddress().getHostAddress(), - httpProxy.getPort(), "", ""); - provider.useProxy(proxyInfoObj); - } - - HttpRequest request = HttpRequest.get(uri); - request.method("POST"); - request.charset("UTF-8"); - request.bodyText(postEntity); - - HttpResponse response = request.open(provider).send(); - response.charset("UTF-8"); - String result = response.bodyText(); - - WxError error = WxError.fromJson(result); - if (error.getErrorCode() != 0) { - throw new WxErrorException(error); - } - return result; + @Override + public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, + String postEntity) throws WxErrorException, IOException { + SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider(); + + if (httpProxy != null) { + ProxyInfo proxyInfoObj = new ProxyInfo( + ProxyInfo.ProxyType.HTTP, + httpProxy.getAddress().getHostAddress(), + httpProxy.getPort(), "", ""); + provider.useProxy(proxyInfoObj); } + HttpRequest request = HttpRequest.get(uri); + request.method("POST"); + request.charset("UTF-8"); + request.bodyText(postEntity); + + HttpResponse response = request.open(provider).send(); + response.charset("UTF-8"); + String result = response.bodyText(); + + WxError error = WxError.fromJson(result); + if (error.getErrorCode() != 0) { + throw new WxErrorException(error); + } + return result; + } + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java index 306ac258ac..5ffac4bf57 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java @@ -6,7 +6,6 @@ import me.chanjar.weixin.common.util.fs.FileUtils; import org.apache.http.Header; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -21,11 +20,11 @@ /** * 下载媒体文件请求执行器,请求的参数是String, 返回的结果是File - * @author Daniel Qian * + * @author Daniel Qian */ public class MediaDownloadRequestExecutor implements RequestExecutor { - + private File tmpDirFile; public MediaDownloadRequestExecutor() { @@ -36,7 +35,7 @@ public MediaDownloadRequestExecutor(File tmpDirFile) { super(); this.tmpDirFile = tmpDirFile; } - + @Override public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String queryParam) throws WxErrorException, IOException { @@ -46,7 +45,7 @@ public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String u } uri += uri.endsWith("?") ? queryParam : '&' + queryParam; } - + HttpGet httpGet = new HttpGet(uri); if (httpProxy != null) { RequestConfig config = RequestConfig.custom().setProxy(httpProxy).build(); @@ -74,7 +73,7 @@ public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String u File localFile = FileUtils.createTmpFile(inputStream, name_ext[0], name_ext[1], tmpDirFile); return localFile; - }finally { + } finally { httpGet.releaseConnection(); } @@ -88,5 +87,5 @@ protected String getFileName(CloseableHttpResponse response) { String fileName = m.group(1); return fileName; } - + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java index b343b260d0..54ded05a7a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaUploadRequestExecutor.java @@ -5,7 +5,6 @@ import me.chanjar.weixin.common.exception.WxErrorException; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -19,8 +18,8 @@ /** * 上传媒体文件请求执行器,请求的参数是File, 返回的结果是String - * @author Daniel Qian * + * @author Daniel Qian */ public class MediaUploadRequestExecutor implements RequestExecutor { @@ -33,10 +32,10 @@ public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost http } if (file != null) { HttpEntity entity = MultipartEntityBuilder - .create() - .addBinaryBody("media", file) - .setMode(HttpMultipartMode.RFC6532) - .build(); + .create() + .addBinaryBody("media", file) + .setMode(HttpMultipartMode.RFC6532) + .build(); httpPost.setEntity(entity); httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString()); } @@ -47,7 +46,7 @@ public WxMediaUploadResult execute(CloseableHttpClient httpclient, HttpHost http throw new WxErrorException(error); } return WxMediaUploadResult.fromJson(responseContent); - }finally { + } finally { httpPost.releaseConnection(); } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java index 50f524680a..d625460df2 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/RequestExecutor.java @@ -1,12 +1,11 @@ package me.chanjar.weixin.common.util.http; -import java.io.IOException; - +import me.chanjar.weixin.common.exception.WxErrorException; import org.apache.http.HttpHost; import org.apache.http.client.ClientProtocolException; import org.apache.http.impl.client.CloseableHttpClient; -import me.chanjar.weixin.common.exception.WxErrorException; +import java.io.IOException; /** * http请求执行器 @@ -17,11 +16,10 @@ public interface RequestExecutor { /** - * * @param httpclient 传入的httpClient - * @param httpProxy http代理对象,如果没有配置代理则为空 - * @param uri uri - * @param data 数据 + * @param httpProxy http代理对象,如果没有配置代理则为空 + * @param uri uri + * @param data 数据 * @throws WxErrorException * @throws ClientProtocolException * @throws IOException diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java index 36852377c8..ec221e28b8 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimpleGetRequestExecutor.java @@ -3,7 +3,6 @@ import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -13,8 +12,8 @@ /** * 简单的GET请求执行器,请求的参数是String, 返回的结果也是String - * @author Daniel Qian * + * @author Daniel Qian */ public class SimpleGetRequestExecutor implements RequestExecutor { @@ -39,7 +38,7 @@ public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String throw new WxErrorException(error); } return responseContent; - }finally { + } finally { httpGet.releaseConnection(); } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java index e60ee06fe1..ad67bd51a5 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/SimplePostRequestExecutor.java @@ -4,7 +4,6 @@ import me.chanjar.weixin.common.exception.WxErrorException; import org.apache.http.Consts; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -15,8 +14,8 @@ /** * 简单的POST请求执行器,请求的参数是String, 返回的结果也是String - * @author Daniel Qian * + * @author Daniel Qian */ public class SimplePostRequestExecutor implements RequestExecutor { @@ -40,7 +39,7 @@ public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String throw new WxErrorException(error); } return responseContent; - }finally { + } finally { httpPost.releaseConnection(); } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java index 1ca1929aa4..1d1481b28b 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/Utf8ResponseHandler.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.common.util.http; -import java.io.IOException; - import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; @@ -10,15 +8,17 @@ import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; +import java.io.IOException; + /** * copy from {@link org.apache.http.impl.client.BasicResponseHandler} - * @author Daniel Qian * + * @author Daniel Qian */ public class Utf8ResponseHandler implements ResponseHandler { public static final ResponseHandler INSTANCE = new Utf8ResponseHandler(); - + public String handleResponse(final HttpResponse response) throws IOException { final StatusLine statusLine = response.getStatusLine(); final HttpEntity entity = response.getEntity(); diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java index 9c274569c6..3c106fbfbc 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/GsonHelper.java @@ -15,101 +15,101 @@ public class GsonHelper { - public static boolean isNull(JsonElement element) { - return element == null || element.isJsonNull(); - } - - public static boolean isNotNull(JsonElement element) { - return !isNull(element); - } - - public static Long getLong(JsonObject json, String property) { - return getAsLong(json.get(property)); - } - - public static long getPrimitiveLong(JsonObject json, String property) { - return getAsPrimitiveLong(json.get(property)); - } - - public static Integer getInteger(JsonObject json, String property) { - return getAsInteger(json.get(property)); - } - - public static int getPrimitiveInteger(JsonObject json, String property) { - return getAsPrimitiveInt(json.get(property)); - } - - public static Double getDouble(JsonObject json, String property) { - return getAsDouble(json.get(property)); - } - - public static double getPrimitiveDouble(JsonObject json, String property) { - return getAsPrimitiveDouble(json.get(property)); - } - - public static Float getFloat(JsonObject json, String property) { - return getAsFloat(json.get(property)); - } - - public static float getPrimitiveFloat(JsonObject json, String property) { - return getAsPrimitiveFloat(json.get(property)); - } - - public static Boolean getBoolean(JsonObject json, String property) { - return getAsBoolean(json.get(property)); - } - - public static String getString(JsonObject json, String property) { - return getAsString(json.get(property)); - } - - public static String getAsString(JsonElement element) { - return isNull(element) ? null : element.getAsString(); - } - - public static Long getAsLong(JsonElement element) { - return isNull(element) ? null : element.getAsLong(); - } - - public static long getAsPrimitiveLong(JsonElement element) { - Long r = getAsLong(element); - return r == null ? 0l : r; - } - - public static Integer getAsInteger(JsonElement element) { - return isNull(element) ? null : element.getAsInt(); - } - - public static int getAsPrimitiveInt(JsonElement element) { - Integer r = getAsInteger(element); - return r == null ? 0 : r; - } - - public static Boolean getAsBoolean(JsonElement element) { - return isNull(element) ? null : element.getAsBoolean(); - } - - public static boolean getAsPrimitiveBool(JsonElement element) { - Boolean r = getAsBoolean(element); - return r != null && r.booleanValue(); - } - - public static Double getAsDouble(JsonElement element) { - return isNull(element) ? null : element.getAsDouble(); - } - - public static double getAsPrimitiveDouble(JsonElement element) { - Double r = getAsDouble(element); - return r == null ? 0d : r; - } - - public static Float getAsFloat(JsonElement element) { - return isNull(element) ? null : element.getAsFloat(); - } - - public static float getAsPrimitiveFloat(JsonElement element) { - Float r = getAsFloat(element); - return r == null ? 0f : r; - } - + public static boolean isNull(JsonElement element) { + return element == null || element.isJsonNull(); + } + + public static boolean isNotNull(JsonElement element) { + return !isNull(element); + } + + public static Long getLong(JsonObject json, String property) { + return getAsLong(json.get(property)); + } + + public static long getPrimitiveLong(JsonObject json, String property) { + return getAsPrimitiveLong(json.get(property)); + } + + public static Integer getInteger(JsonObject json, String property) { + return getAsInteger(json.get(property)); + } + + public static int getPrimitiveInteger(JsonObject json, String property) { + return getAsPrimitiveInt(json.get(property)); + } + + public static Double getDouble(JsonObject json, String property) { + return getAsDouble(json.get(property)); + } + + public static double getPrimitiveDouble(JsonObject json, String property) { + return getAsPrimitiveDouble(json.get(property)); + } + + public static Float getFloat(JsonObject json, String property) { + return getAsFloat(json.get(property)); + } + + public static float getPrimitiveFloat(JsonObject json, String property) { + return getAsPrimitiveFloat(json.get(property)); + } + + public static Boolean getBoolean(JsonObject json, String property) { + return getAsBoolean(json.get(property)); + } + + public static String getString(JsonObject json, String property) { + return getAsString(json.get(property)); + } + + public static String getAsString(JsonElement element) { + return isNull(element) ? null : element.getAsString(); + } + + public static Long getAsLong(JsonElement element) { + return isNull(element) ? null : element.getAsLong(); + } + + public static long getAsPrimitiveLong(JsonElement element) { + Long r = getAsLong(element); + return r == null ? 0l : r; + } + + public static Integer getAsInteger(JsonElement element) { + return isNull(element) ? null : element.getAsInt(); + } + + public static int getAsPrimitiveInt(JsonElement element) { + Integer r = getAsInteger(element); + return r == null ? 0 : r; + } + + public static Boolean getAsBoolean(JsonElement element) { + return isNull(element) ? null : element.getAsBoolean(); + } + + public static boolean getAsPrimitiveBool(JsonElement element) { + Boolean r = getAsBoolean(element); + return r != null && r.booleanValue(); + } + + public static Double getAsDouble(JsonElement element) { + return isNull(element) ? null : element.getAsDouble(); + } + + public static double getAsPrimitiveDouble(JsonElement element) { + Double r = getAsDouble(element); + return r == null ? 0d : r; + } + + public static Float getAsFloat(JsonElement element) { + return isNull(element) ? null : element.getAsFloat(); + } + + public static float getAsPrimitiveFloat(JsonElement element) { + Float r = getAsFloat(element); + return r == null ? 0f : r; + } + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java index cfe4edb202..58be83accd 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxAccessTokenAdapter.java @@ -14,9 +14,7 @@ import java.lang.reflect.Type; /** - * * @author Daniel Qian - * */ public class WxAccessTokenAdapter implements JsonDeserializer { @@ -32,5 +30,5 @@ public WxAccessToken deserialize(JsonElement json, Type typeOfT, JsonDeserializa } return accessToken; } - + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java index 74b9ded8b5..30c3708d6c 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxErrorAdapter.java @@ -14,9 +14,7 @@ import java.lang.reflect.Type; /** - * * @author Daniel Qian - * */ public class WxErrorAdapter implements JsonDeserializer { @@ -33,5 +31,5 @@ public WxError deserialize(JsonElement json, Type typeOfT, JsonDeserializationCo wxError.setJson(json.toString()); return wxError; } - + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java index 7aa5696563..100ef52303 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxGsonBuilder.java @@ -2,9 +2,10 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import me.chanjar.weixin.common.bean.WxMenu; -import me.chanjar.weixin.common.bean.result.WxError; + import me.chanjar.weixin.common.bean.WxAccessToken; +import me.chanjar.weixin.common.bean.menu.WxMenu; +import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; public class WxGsonBuilder { diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java index 35eb18b4fb..16317a4063 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMediaUploadResultAdapter.java @@ -14,9 +14,7 @@ import java.lang.reflect.Type; /** - * * @author Daniel Qian - * */ public class WxMediaUploadResultAdapter implements JsonDeserializer { @@ -38,5 +36,5 @@ public WxMediaUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeser } return uploadResult; } - + } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java index 51a19fec94..744df7e12a 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/json/WxMenuGsonAdapter.java @@ -8,6 +8,8 @@ */ package me.chanjar.weixin.common.util.json; +import java.lang.reflect.Type; + import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; @@ -16,14 +18,14 @@ import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; -import me.chanjar.weixin.common.bean.WxMenu; -import java.lang.reflect.Type; +import me.chanjar.weixin.common.bean.menu.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenuButton; +import me.chanjar.weixin.common.bean.menu.WxMenuRule; + /** - * * @author Daniel Qian - * */ public class WxMenuGsonAdapter implements JsonSerializer, JsonDeserializer { @@ -31,28 +33,29 @@ public JsonElement serialize(WxMenu menu, Type typeOfSrc, JsonSerializationConte JsonObject json = new JsonObject(); JsonArray buttonArray = new JsonArray(); - for (WxMenu.WxMenuButton button : menu.getButtons()) { + for (WxMenuButton button : menu.getButtons()) { JsonObject buttonJson = convertToJson(button); buttonArray.add(buttonJson); } json.add("button", buttonArray); - + if (menu.getMatchRule() != null) { json.add("matchrule", convertToJson(menu.getMatchRule())); } - + return json; } - protected JsonObject convertToJson(WxMenu.WxMenuButton button) { + protected JsonObject convertToJson(WxMenuButton button) { JsonObject buttonJson = new JsonObject(); buttonJson.addProperty("type", button.getType()); buttonJson.addProperty("name", button.getName()); buttonJson.addProperty("key", button.getKey()); buttonJson.addProperty("url", button.getUrl()); + buttonJson.addProperty("media_id", button.getMediaId()); if (button.getSubButtons() != null && button.getSubButtons().size() > 0) { JsonArray buttonArray = new JsonArray(); - for (WxMenu.WxMenuButton sub_button : button.getSubButtons()) { + for (WxMenuButton sub_button : button.getSubButtons()) { buttonArray.add(convertToJson(sub_button)); } buttonJson.add("sub_button", buttonArray); @@ -60,15 +63,15 @@ protected JsonObject convertToJson(WxMenu.WxMenuButton button) { return buttonJson; } - protected JsonObject convertToJson(WxMenu.WxMenuRule menuRule){ + protected JsonObject convertToJson(WxMenuRule menuRule) { JsonObject matchRule = new JsonObject(); - matchRule.addProperty("tag_id",menuRule.getTagId()); - matchRule.addProperty("sex",menuRule.getSex()); - matchRule.addProperty("country",menuRule.getCountry()); - matchRule.addProperty("province",menuRule.getProvince()); - matchRule.addProperty("city",menuRule.getCity()); - matchRule.addProperty("client_platform_type",menuRule.getClientPlatformType()); - matchRule.addProperty("language",menuRule.getLanguage()); + matchRule.addProperty("tag_id", menuRule.getTagId()); + matchRule.addProperty("sex", menuRule.getSex()); + matchRule.addProperty("country", menuRule.getCountry()); + matchRule.addProperty("province", menuRule.getProvince()); + matchRule.addProperty("city", menuRule.getCity()); + matchRule.addProperty("client_platform_type", menuRule.getClientPlatformType()); + matchRule.addProperty("language", menuRule.getLanguage()); return matchRule; } @@ -83,7 +86,7 @@ public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationCon JsonArray buttonsJson = menuJson.get("button").getAsJsonArray(); for (int i = 0; i < buttonsJson.size(); i++) { JsonObject buttonJson = buttonsJson.get(i).getAsJsonObject(); - WxMenu.WxMenuButton button = convertFromJson(buttonJson); + WxMenuButton button = convertFromJson(buttonJson); menu.getButtons().add(button); if (buttonJson.get("sub_button") == null || buttonJson.get("sub_button").isJsonNull()) { continue; @@ -96,13 +99,14 @@ public WxMenu deserialize(JsonElement json, Type typeOfT, JsonDeserializationCon } return menu; } - - protected WxMenu.WxMenuButton convertFromJson(JsonObject json) { - WxMenu.WxMenuButton button = new WxMenu.WxMenuButton(); + + protected WxMenuButton convertFromJson(JsonObject json) { + WxMenuButton button = new WxMenuButton(); button.setName(GsonHelper.getString(json, "name")); button.setKey(GsonHelper.getString(json, "key")); button.setUrl(GsonHelper.getString(json, "url")); button.setType(GsonHelper.getString(json, "type")); + button.setMediaId(GsonHelper.getString(json, "media_id")); return button; } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java index 0abe4d89a0..94303fecf0 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/res/StringManager.java @@ -18,30 +18,24 @@ package me.chanjar.weixin.common.util.res; import java.text.MessageFormat; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.ResourceBundle; +import java.util.*; /** * An internationalization / localization helper class which reduces * the bother of handling ResourceBundles and takes care of the * common cases of message formating which otherwise require the * creation of Object arrays and such. - * + *

    *

    The StringManager operates on a package basis. One StringManager * per package can be created and accessed via the getManager method * call. - * + *

    *

    The StringManager will look for a ResourceBundle named by * the package name given plus the suffix of "LocalStrings". In * practice, this means that the localized information will be contained * in a LocalStrings.properties file located in the package * directory of the classpath. - * + *

    *

    Please see the documentation for java.util.ResourceBundle for * more information. * @@ -52,152 +46,80 @@ */ public class StringManager { - private static int LOCALE_CACHE_SIZE = 10; - - /** - * The ResourceBundle for this StringManager. - */ - private final ResourceBundle bundle; - private final Locale locale; - - /** - * Creates a new StringManager for a given package. This is a - * private method and all access to it is arbitrated by the - * static getManager method call so that only one StringManager - * per package will be created. - * - * @param packageName Name of package to create StringManager for. - */ - private StringManager(String packageName, Locale locale) { - String bundleName = packageName + ".LocalStrings"; - ResourceBundle bnd = null; + private static final Map> managers = + new Hashtable>(); + private static int LOCALE_CACHE_SIZE = 10; + /** + * The ResourceBundle for this StringManager. + */ + private final ResourceBundle bundle; + private final Locale locale; + + /** + * Creates a new StringManager for a given package. This is a + * private method and all access to it is arbitrated by the + * static getManager method call so that only one StringManager + * per package will be created. + * + * @param packageName Name of package to create StringManager for. + */ + private StringManager(String packageName, Locale locale) { + String bundleName = packageName + ".LocalStrings"; + ResourceBundle bnd = null; + try { + bnd = ResourceBundle.getBundle(bundleName, locale); + } catch (MissingResourceException ex) { + // Try from the current loader (that's the case for trusted apps) + // Should only be required if using a TC5 style classloader structure + // where common != shared != server + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl != null) { try { - bnd = ResourceBundle.getBundle(bundleName, locale); - } catch( MissingResourceException ex ) { - // Try from the current loader (that's the case for trusted apps) - // Should only be required if using a TC5 style classloader structure - // where common != shared != server - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - if( cl != null ) { - try { - bnd = ResourceBundle.getBundle(bundleName, locale, cl); - } catch(MissingResourceException ex2) { - // Ignore - } - } - } - bundle = bnd; - // Get the actual locale, which may be different from the requested one - if (bundle != null) { - Locale bundleLocale = bundle.getLocale(); - if (bundleLocale.equals(Locale.ROOT)) { - this.locale = Locale.ENGLISH; - } else { - this.locale = bundleLocale; - } - } else { - this.locale = null; + bnd = ResourceBundle.getBundle(bundleName, locale, cl); + } catch (MissingResourceException ex2) { + // Ignore } + } } - - /** - Get a string from the underlying resource bundle or return - null if the String is not found. - - @param key to desired resource String - @return resource String matching key from underlying - bundle or null if not found. - @throws IllegalArgumentException if key is null. - */ - public String getString(String key) { - if(key == null){ - String msg = "key may not have a null value"; - - throw new IllegalArgumentException(msg); - } - - String str = null; - - try { - // Avoid NPE if bundle is null and treat it like an MRE - if (bundle != null) { - str = bundle.getString(key); - } - } catch(MissingResourceException mre) { - //bad: shouldn't mask an exception the following way: - // str = "[cannot find message associated with key '" + key + - // "' due to " + mre + "]"; - // because it hides the fact that the String was missing - // from the calling code. - //good: could just throw the exception (or wrap it in another) - // but that would probably cause much havoc on existing - // code. - //better: consistent with container pattern to - // simply return null. Calling code can then do - // a null check. - str = null; - } - - return str; + bundle = bnd; + // Get the actual locale, which may be different from the requested one + if (bundle != null) { + Locale bundleLocale = bundle.getLocale(); + if (bundleLocale.equals(Locale.ROOT)) { + this.locale = Locale.ENGLISH; + } else { + this.locale = bundleLocale; + } + } else { + this.locale = null; } - - /** - * Get a string from the underlying resource bundle and format - * it with the given set of arguments. - * - * @param key - * @param args - */ - public String getString(final String key, final Object... args) { - String value = getString(key); - if (value == null) { - value = key; - } - - MessageFormat mf = new MessageFormat(value); - mf.setLocale(locale); - return mf.format(args, new StringBuffer(), null).toString(); - } - - /** - * Identify the Locale this StringManager is associated with - */ - public Locale getLocale() { - return locale; - } - - // -------------------------------------------------------------- - // STATIC SUPPORT METHODS - // -------------------------------------------------------------- - - private static final Map> managers = - new Hashtable>(); - - /** - * Get the StringManager for a particular package. If a manager for - * a package already exists, it will be reused, else a new - * StringManager will be created and returned. - * - * @param packageName The package name - */ - public static final synchronized StringManager getManager( - String packageName) { - return getManager(packageName, Locale.getDefault()); - } - - /** - * Get the StringManager for a particular package and Locale. If a manager - * for a package/Locale combination already exists, it will be reused, else - * a new StringManager will be created and returned. - * - * @param packageName The package name - * @param locale The Locale - */ - public static final synchronized StringManager getManager( - String packageName, Locale locale) { - - Map map = managers.get(packageName); - if (map == null) { + } + + /** + * Get the StringManager for a particular package. If a manager for + * a package already exists, it will be reused, else a new + * StringManager will be created and returned. + * + * @param packageName The package name + */ + public static final synchronized StringManager getManager( + String packageName) { + return getManager(packageName, Locale.getDefault()); + } + + /** + * Get the StringManager for a particular package and Locale. If a manager + * for a package/Locale combination already exists, it will be reused, else + * a new StringManager will be created and returned. + * + * @param packageName The package name + * @param locale The Locale + */ + public static final synchronized StringManager getManager( + String packageName, Locale locale) { + + Map map = managers.get(packageName); + if (map == null) { /* * Don't want the HashMap to be expanded beyond LOCALE_CACHE_SIZE. * Expansion occurs when size() exceeds capacity. Therefore keep @@ -206,43 +128,113 @@ public static final synchronized StringManager getManager( * for removal needs to use one less than the maximum desired size * */ - map = new LinkedHashMap(LOCALE_CACHE_SIZE, 1, true) { - private static final long serialVersionUID = 1L; - @Override - protected boolean removeEldestEntry( - Map.Entry eldest) { - return size() > (LOCALE_CACHE_SIZE - 1); - } - }; - managers.put(packageName, map); - } + map = new LinkedHashMap(LOCALE_CACHE_SIZE, 1, true) { + private static final long serialVersionUID = 1L; - StringManager mgr = map.get(locale); - if (mgr == null) { - mgr = new StringManager(packageName, locale); - map.put(locale, mgr); + @Override + protected boolean removeEldestEntry( + Map.Entry eldest) { + return size() > (LOCALE_CACHE_SIZE - 1); } - return mgr; + }; + managers.put(packageName, map); } - /** - * Retrieve the StringManager for a list of Locales. The first StringManager - * found will be returned. - * - * @param requestedLocales the list of Locales - * - * @return the found StringManager or the default StringManager - */ - public static StringManager getManager(String packageName, - Enumeration requestedLocales) { - while (requestedLocales.hasMoreElements()) { - Locale locale = requestedLocales.nextElement(); - StringManager result = getManager(packageName, locale); - if (result.getLocale().equals(locale)) { - return result; - } - } - // Return the default - return getManager(packageName); + StringManager mgr = map.get(locale); + if (mgr == null) { + mgr = new StringManager(packageName, locale); + map.put(locale, mgr); } + return mgr; + } + + // -------------------------------------------------------------- + // STATIC SUPPORT METHODS + // -------------------------------------------------------------- + + /** + * Retrieve the StringManager for a list of Locales. The first StringManager + * found will be returned. + * + * @param requestedLocales the list of Locales + * @return the found StringManager or the default StringManager + */ + public static StringManager getManager(String packageName, + Enumeration requestedLocales) { + while (requestedLocales.hasMoreElements()) { + Locale locale = requestedLocales.nextElement(); + StringManager result = getManager(packageName, locale); + if (result.getLocale().equals(locale)) { + return result; + } + } + // Return the default + return getManager(packageName); + } + + /** + * Get a string from the underlying resource bundle or return + * null if the String is not found. + * + * @param key to desired resource String + * @return resource String matching key from underlying + * bundle or null if not found. + * @throws IllegalArgumentException if key is null. + */ + public String getString(String key) { + if (key == null) { + String msg = "key may not have a null value"; + + throw new IllegalArgumentException(msg); + } + + String str = null; + + try { + // Avoid NPE if bundle is null and treat it like an MRE + if (bundle != null) { + str = bundle.getString(key); + } + } catch (MissingResourceException mre) { + //bad: shouldn't mask an exception the following way: + // str = "[cannot find message associated with key '" + key + + // "' due to " + mre + "]"; + // because it hides the fact that the String was missing + // from the calling code. + //good: could just throw the exception (or wrap it in another) + // but that would probably cause much havoc on existing + // code. + //better: consistent with container pattern to + // simply return null. Calling code can then do + // a null check. + str = null; + } + + return str; + } + + /** + * Get a string from the underlying resource bundle and format + * it with the given set of arguments. + * + * @param key + * @param args + */ + public String getString(final String key, final Object... args) { + String value = getString(key); + if (value == null) { + value = key; + } + + MessageFormat mf = new MessageFormat(value); + mf.setLocale(locale); + return mf.format(args, new StringBuffer(), null).toString(); + } + + /** + * Identify the Locale this StringManager is associated with + */ + public Locale getLocale() { + return locale; + } } diff --git a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java index 1caa0a068b..109acfc072 100644 --- a/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java +++ b/weixin-java-common/src/main/java/me/chanjar/weixin/common/util/xml/XStreamInitializer.java @@ -1,7 +1,5 @@ package me.chanjar.weixin.common.util.xml; -import java.io.Writer; - import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; @@ -10,6 +8,8 @@ import com.thoughtworks.xstream.security.NullPermission; import com.thoughtworks.xstream.security.PrimitiveTypePermission; +import java.io.Writer; + public class XStreamInitializer { public static XStream getInstance() { @@ -22,6 +22,7 @@ public HierarchicalStreamWriter createWriter(Writer out) { protected String SUFFIX_CDATA = "]]>"; protected String PREFIX_MEDIA_ID = ""; protected String SUFFIX_MEDIA_ID = ""; + @Override protected void writeText(QuickWriter writer, String text) { if (text.startsWith(PREFIX_CDATA) && text.endsWith(SUFFIX_CDATA)) { diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java index d236c63107..b2bc7fe7d1 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxAccessTokenTest.java @@ -14,5 +14,5 @@ public void testFromJson() { Assert.assertTrue(wxError.getExpiresIn() == 7200); } - + } diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java index 51e9dab362..3fe40795f3 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxErrorTest.java @@ -15,7 +15,7 @@ public void testFromJson() { Assert.assertEquals(wxError.getErrorMsg(), "invalid openid"); } - + public void testFromBadJson1() { String json = "{ \"errcode\": 40003, \"errmsg\": \"invalid openid\", \"media_id\": \"12323423dsfafsf232f\" }"; @@ -24,7 +24,7 @@ public void testFromBadJson1() { Assert.assertEquals(wxError.getErrorMsg(), "invalid openid"); } - + public void testFromBadJson2() { String json = "{\"access_token\":\"ACCESS_TOKEN\",\"expires_in\":7200}"; @@ -33,5 +33,5 @@ public void testFromBadJson2() { Assert.assertEquals(wxError.getErrorMsg(), null); } - + } diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java index 2ae12c2ccf..e2a0c2c1f8 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/bean/WxMenuTest.java @@ -1,58 +1,61 @@ package me.chanjar.weixin.common.bean; -import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import me.chanjar.weixin.common.bean.menu.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenuButton; +import me.chanjar.weixin.common.bean.menu.WxMenuRule; + @Test public class WxMenuTest { - @Test(dataProvider="wxReturnMenu") + @Test(dataProvider = "wxReturnMenu") public void testFromJson(String json) { WxMenu menu = WxMenu.fromJson(json); Assert.assertEquals(menu.getButtons().size(), 3); } - - @Test(dataProvider="wxPushMenu") + + @Test(dataProvider = "wxPushMenu") public void testToJson(String json) { WxMenu menu = new WxMenu(); WxMenuButton button1 = new WxMenuButton(); button1.setType("click"); button1.setName("今日歌曲"); button1.setKey("V1001_TODAY_MUSIC"); - + WxMenuButton button2 = new WxMenuButton(); button2.setType("click"); button2.setName("歌手简介"); button2.setKey("V1001_TODAY_SINGER"); - + WxMenuButton button3 = new WxMenuButton(); button3.setName("菜单"); - + menu.getButtons().add(button1); menu.getButtons().add(button2); menu.getButtons().add(button3); - + WxMenuButton button31 = new WxMenuButton(); button31.setType("view"); button31.setName("搜索"); button31.setUrl("http://www.soso.com/"); - + WxMenuButton button32 = new WxMenuButton(); button32.setType("view"); button32.setName("视频"); button32.setUrl("http://v.qq.com/"); - + WxMenuButton button33 = new WxMenuButton(); button33.setType("click"); button33.setName("赞一下我们"); button33.setKey("V1001_GOOD"); - + button3.getSubButtons().add(button31); button3.getSubButtons().add(button32); button3.getSubButtons().add(button33); - + Assert.assertEquals(menu.toJson(), json); } @@ -66,7 +69,7 @@ public void testAddConditionalToJson(String json) { menu.getButtons().add(button1); - WxMenu.WxMenuRule wxMenuRule = new WxMenu.WxMenuRule(); + WxMenuRule wxMenuRule = new WxMenuRule(); wxMenuRule.setTagId("2"); wxMenuRule.setSex("1"); wxMenuRule.setCountry("中国"); @@ -78,82 +81,82 @@ public void testAddConditionalToJson(String json) { Assert.assertEquals(menu.toJson(), json); } - + @DataProvider public Object[][] wxReturnMenu() { - Object[][] res = menuJson(); + Object[][] res = menuJson(); String json = "{ \"menu\" : " + res[0][0] + " }"; - return new Object[][] { - new Object[] { json } + return new Object[][]{ + new Object[]{json} }; } - - @DataProvider(name="wxPushMenu") + + @DataProvider(name = "wxPushMenu") public Object[][] menuJson() { - String json = - "{" - +"\"button\":[" - +"{" - +"\"type\":\"click\"," - +"\"name\":\"今日歌曲\"," - +"\"key\":\"V1001_TODAY_MUSIC\"" - +"}," - +"{" - +"\"type\":\"click\"," - +"\"name\":\"歌手简介\"," - +"\"key\":\"V1001_TODAY_SINGER\"" - +"}," - +"{" - +"\"name\":\"菜单\"," - +"\"sub_button\":[" - +"{" - +"\"type\":\"view\"," - +"\"name\":\"搜索\"," - +"\"url\":\"http://www.soso.com/\"" - +"}," - +"{" - +"\"type\":\"view\"," - +"\"name\":\"视频\"," - +"\"url\":\"http://v.qq.com/\"" - +"}," - +"{" - +"\"type\":\"click\"," - +"\"name\":\"赞一下我们\"," - +"\"key\":\"V1001_GOOD\"" - +"}" - +"]" - +"}" - +"]" - +"}"; - return new Object[][] { - new Object[] { json } + String json = + "{" + + "\"button\":[" + + "{" + + "\"type\":\"click\"," + + "\"name\":\"今日歌曲\"," + + "\"key\":\"V1001_TODAY_MUSIC\"" + + "}," + + "{" + + "\"type\":\"click\"," + + "\"name\":\"歌手简介\"," + + "\"key\":\"V1001_TODAY_SINGER\"" + + "}," + + "{" + + "\"name\":\"菜单\"," + + "\"sub_button\":[" + + "{" + + "\"type\":\"view\"," + + "\"name\":\"搜索\"," + + "\"url\":\"http://www.soso.com/\"" + + "}," + + "{" + + "\"type\":\"view\"," + + "\"name\":\"视频\"," + + "\"url\":\"http://v.qq.com/\"" + + "}," + + "{" + + "\"type\":\"click\"," + + "\"name\":\"赞一下我们\"," + + "\"key\":\"V1001_GOOD\"" + + "}" + + "]" + + "}" + + "]" + + "}"; + return new Object[][]{ + new Object[]{json} }; } @DataProvider(name = "wxAddConditionalMenu") - public Object[][] addConditionalMenuJson(){ + public Object[][] addConditionalMenuJson() { String json = - "{" - +"\"button\":[" - +"{" - +"\"type\":\"click\"," - +"\"name\":\"今日歌曲\"," - +"\"key\":\"V1001_TODAY_MUSIC\"" - +"}" - +"]," - +"\"matchrule\":{" - +"\"group_id\":\"2\"," - +"\"sex\":\"1\"," - +"\"country\":\"中国\"," - +"\"province\":\"广东\"," - +"\"city\":\"广州\"," - +"\"client_platform_type\":\"2\"," - +"\"language\":\"zh_CN\"" - +"}" - +"}"; + "{" + + "\"button\":[" + + "{" + + "\"type\":\"click\"," + + "\"name\":\"今日歌曲\"," + + "\"key\":\"V1001_TODAY_MUSIC\"" + + "}" + + "]," + + "\"matchrule\":{" + + "\"group_id\":\"2\"," + + "\"sex\":\"1\"," + + "\"country\":\"中国\"," + + "\"province\":\"广东\"," + + "\"city\":\"广州\"," + + "\"client_platform_type\":\"2\"," + + "\"language\":\"zh_CN\"" + + "}" + + "}"; return new Object[][]{ - new Object[]{json} + new Object[]{json} }; } - + } diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java index bcb029b191..ce2466361e 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java @@ -10,8 +10,8 @@ public class SessionTest { @DataProvider public Object[][] getSessionManager() { - return new Object[][] { - new Object[] { new StandardSessionManager() } + return new Object[][]{ + new Object[]{new StandardSessionManager()} }; } diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java index 7369d63715..a3a243a428 100644 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/WxMessageInMemoryDuplicateCheckerTest.java @@ -8,7 +8,7 @@ public class WxMessageInMemoryDuplicateCheckerTest { public void test() throws InterruptedException { - Long[] msgIds = new Long[] { 1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l }; + Long[] msgIds = new Long[]{1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l}; WxMessageInMemoryDuplicateChecker checker = new WxMessageInMemoryDuplicateChecker(2000l, 1000l); // 第一次检查 diff --git a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java index 15b08c2685..a5fa0c4199 100755 --- a/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java +++ b/weixin-java-common/src/test/java/me/chanjar/weixin/common/util/crypto/WxCryptUtilTest.java @@ -45,16 +45,24 @@ public void testNormal() throws ParserConfigurationException, SAXException, IOEx Element root = document.getDocumentElement(); String cipherText = root.getElementsByTagName("Encrypt").item(0).getTextContent(); + System.out.println(cipherText); + String msgSignature = root.getElementsByTagName("MsgSignature").item(0).getTextContent(); + System.out.println(msgSignature); + String timestamp = root.getElementsByTagName("TimeStamp").item(0).getTextContent(); + System.out.println(timestamp); + String nonce = root.getElementsByTagName("Nonce").item(0).getTextContent(); - + System.out.println(nonce); + String messageText = String.format(xmlFormat, cipherText); - + System.out.println(messageText); + // 第三方收到企业号平台发送的消息 String plainMessage = pc.decrypt(cipherText); - System.out.println(plainMessage); + assertEquals(plainMessage, replyMsg); } @@ -69,7 +77,7 @@ public void testAesEncrypt2() { } public void testValidateSignatureError() throws ParserConfigurationException, SAXException, - IOException { + IOException { try { WxCryptUtil pc = new WxCryptUtil(token, encodingAesKey, appId); String afterEncrpt = pc.encrypt(replyMsg); diff --git a/weixin-java-common/src/test/resources/logback-test.xml b/weixin-java-common/src/test/resources/logback-test.xml index c0d6fc3caa..2c421e49ab 100644 --- a/weixin-java-common/src/test/resources/logback-test.xml +++ b/weixin-java-common/src/test/resources/logback-test.xml @@ -1,5 +1,6 @@ + + - diff --git a/weixin-java-cp/build.gradle b/weixin-java-cp/build.gradle new file mode 100644 index 0000000000..f58703ca4b --- /dev/null +++ b/weixin-java-cp/build.gradle @@ -0,0 +1,12 @@ + +description = 'WeiXin Java Tools - CP' +dependencies { + compile project(':weixin-java-common') + testCompile group: 'junit', name: 'junit', version:'4.11' + testCompile group: 'org.testng', name: 'testng', version:'6.8.7' + testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' + testCompile group: 'com.google.inject', name: 'guice', version:'3.0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version:'9.3.0.M0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version:'9.3.0.M0' +} +test.useTestNG() diff --git a/weixin-java-cp/pom.xml b/weixin-java-cp/pom.xml index c8ab21c9e8..7b99625670 100644 --- a/weixin-java-cp/pom.xml +++ b/weixin-java-cp/pom.xml @@ -6,7 +6,7 @@ com.github.binarywang weixin-java-parent - 2.0.0 + 2.1.0 weixin-java-cp diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java index 2b2ccf1d08..4e4ab2386e 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpConfigStorage.java @@ -7,8 +7,8 @@ /** * 微信客户端配置存储 - * @author Daniel Qian * + * @author Daniel Qian */ public interface WxCpConfigStorage { @@ -36,12 +36,13 @@ public interface WxCpConfigStorage { /** * 应该是线程安全的 + * * @param jsapiTicket */ void updateJsapiTicket(String jsapiTicket, int expiresInSeconds); String getCorpId(); - + String getCorpSecret(); String getAgentId(); @@ -61,11 +62,12 @@ public interface WxCpConfigStorage { String getHttp_proxy_username(); String getHttp_proxy_password(); - + File getTmpDirFile(); /** * http client builder + * * @return ApacheHttpClientBuilder */ ApacheHttpClientBuilder getApacheHttpClientBuilder(); diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java index 5e0ba7774a..52d0c93bbe 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpInMemoryConfigStorage.java @@ -7,8 +7,8 @@ /** * 基于内存的微信配置provider,在实际生产环境中应该将这些配置持久化 - * @author Daniel Qian * + * @author Daniel Qian */ public class WxCpInMemoryConfigStorage implements WxCpConfigStorage { @@ -39,6 +39,10 @@ public String getAccessToken() { return this.accessToken; } + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + public boolean isAccessTokenExpired() { return System.currentTimeMillis() > this.expiresTime; } @@ -50,7 +54,7 @@ public void expireAccessToken() { public synchronized void updateAccessToken(WxAccessToken accessToken) { updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn()); } - + public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) { this.accessToken = accessToken; this.expiresTime = System.currentTimeMillis() + (expiresInSeconds - 200) * 1000l; @@ -91,28 +95,32 @@ public String getCorpId() { return this.corpId; } + public void setCorpId(String corpId) { + this.corpId = corpId; + } + public String getCorpSecret() { return this.corpSecret; } - public String getToken() { - return this.token; + public void setCorpSecret(String corpSecret) { + this.corpSecret = corpSecret; } - public long getExpiresTime() { - return this.expiresTime; + public String getToken() { + return this.token; } - public void setCorpId(String corpId) { - this.corpId = corpId; + public void setToken(String token) { + this.token = token; } - public void setCorpSecret(String corpSecret) { - this.corpSecret = corpSecret; + public long getExpiresTime() { + return this.expiresTime; } - public void setToken(String token) { - this.token = token; + public void setExpiresTime(long expiresTime) { + this.expiresTime = expiresTime; } public String getAesKey() { @@ -123,14 +131,6 @@ public void setAesKey(String aesKey) { this.aesKey = aesKey; } - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public void setExpiresTime(long expiresTime) { - this.expiresTime = expiresTime; - } - public String getAgentId() { return agentId; } @@ -183,21 +183,21 @@ public void setHttp_proxy_password(String http_proxy_password) { @Override public String toString() { return "WxCpInMemoryConfigStorage{" + - "corpId='" + corpId + '\'' + - ", corpSecret='" + corpSecret + '\'' + - ", token='" + token + '\'' + - ", accessToken='" + accessToken + '\'' + - ", aesKey='" + aesKey + '\'' + - ", agentId='" + agentId + '\'' + - ", expiresTime=" + expiresTime + - ", http_proxy_host='" + http_proxy_host + '\'' + - ", http_proxy_port=" + http_proxy_port + - ", http_proxy_username='" + http_proxy_username + '\'' + - ", http_proxy_password='" + http_proxy_password + '\'' + - ", jsapiTicket='" + jsapiTicket + '\'' + - ", jsapiTicketExpiresTime='" + jsapiTicketExpiresTime + '\'' + - ", tmpDirFile='" + tmpDirFile + '\'' + - '}'; + "corpId='" + corpId + '\'' + + ", corpSecret='" + corpSecret + '\'' + + ", token='" + token + '\'' + + ", accessToken='" + accessToken + '\'' + + ", aesKey='" + aesKey + '\'' + + ", agentId='" + agentId + '\'' + + ", expiresTime=" + expiresTime + + ", http_proxy_host='" + http_proxy_host + '\'' + + ", http_proxy_port=" + http_proxy_port + + ", http_proxy_username='" + http_proxy_username + '\'' + + ", http_proxy_password='" + http_proxy_password + '\'' + + ", jsapiTicket='" + jsapiTicket + '\'' + + ", jsapiTicketExpiresTime='" + jsapiTicketExpiresTime + '\'' + + ", tmpDirFile='" + tmpDirFile + '\'' + + '}'; } public File getTmpDirFile() { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java new file mode 100644 index 0000000000..8d3b6bbdb2 --- /dev/null +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpJedisConfigStorage.java @@ -0,0 +1,267 @@ +package me.chanjar.weixin.cp.api; + +import java.io.File; + +import me.chanjar.weixin.common.bean.WxAccessToken; +import me.chanjar.weixin.common.util.http.ApacheHttpClientBuilder; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +/** + * Jedis client implementor for wechat config storage + * + * @author gaigeshen + */ +public class WxCpJedisConfigStorage implements WxCpConfigStorage { + + /* Redis keys here */ + private static final String ACCESS_TOKEN_KEY = "WX_CP_ACCESS_TOKEN"; + private static final String ACCESS_TOKEN_EXPIRES_TIME_KEY = "WX_CP_ACCESS_TOKEN_EXPIRES_TIME"; + private static final String JS_API_TICKET_KEY = "WX_CP_JS_API_TICKET"; + private static final String JS_API_TICKET_EXPIRES_TIME_KEY = "WX_CP_JS_API_TICKET_EXPIRES_TIME"; + + private volatile String corpId; + private volatile String corpSecret; + + private volatile String token; + private volatile String aesKey; + private volatile String agentId; + + private volatile String oauth2redirectUri; + + private volatile String http_proxy_host; + private volatile int http_proxy_port; + private volatile String http_proxy_username; + private volatile String http_proxy_password; + + private volatile File tmpDirFile; + + private volatile ApacheHttpClientBuilder apacheHttpClientBuilder; + + /* Redis clients pool */ + private final JedisPool jedisPool; + + public WxCpJedisConfigStorage(String host, int port) { + this.jedisPool = new JedisPool(host, port); + } + + /** + * + * This method will be destroy jedis pool + */ + public void destroy() { + this.jedisPool.destroy(); + } + + @Override + public String getAccessToken() { + try (Jedis jedis = this.jedisPool.getResource()) { + return jedis.get(ACCESS_TOKEN_KEY); + } + } + + @Override + public boolean isAccessTokenExpired() { + try (Jedis jedis = this.jedisPool.getResource()) { + String expiresTimeStr = jedis.get(ACCESS_TOKEN_EXPIRES_TIME_KEY); + + if (expiresTimeStr != null) { + Long expiresTime = Long.parseLong(expiresTimeStr); + return System.currentTimeMillis() > expiresTime; + } + + return true; + + } + } + + @Override + public void expireAccessToken() { + try (Jedis jedis = this.jedisPool.getResource()) { + jedis.set(ACCESS_TOKEN_EXPIRES_TIME_KEY, "0"); + } + } + + @Override + public synchronized void updateAccessToken(WxAccessToken accessToken) { + this.updateAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn()); + } + + @Override + public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) { + try (Jedis jedis = this.jedisPool.getResource()) { + jedis.set(ACCESS_TOKEN_KEY, accessToken); + + jedis.set(ACCESS_TOKEN_EXPIRES_TIME_KEY, + (System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L) + ""); + } + } + + @Override + public String getJsapiTicket() { + try (Jedis jedis = this.jedisPool.getResource()) { + return jedis.get(JS_API_TICKET_KEY); + } + } + + @Override + public boolean isJsapiTicketExpired() { + + try (Jedis jedis = this.jedisPool.getResource()) { + String expiresTimeStr = jedis.get(JS_API_TICKET_EXPIRES_TIME_KEY); + + if (expiresTimeStr != null) { + Long expiresTime = Long.parseLong(expiresTimeStr); + return System.currentTimeMillis() > expiresTime; + } + + return true; + + } + } + + @Override + public void expireJsapiTicket() { + try (Jedis jedis = this.jedisPool.getResource()) { + jedis.set(JS_API_TICKET_EXPIRES_TIME_KEY, "0"); + } + } + + @Override + public synchronized void updateJsapiTicket(String jsapiTicket, int expiresInSeconds) { + + try (Jedis jedis = this.jedisPool.getResource()) { + jedis.set(JS_API_TICKET_KEY, jsapiTicket); + + jedis.set(JS_API_TICKET_EXPIRES_TIME_KEY, + (System.currentTimeMillis() + (expiresInSeconds - 200) * 1000L + "")); + } + + } + + @Override + public String getCorpId() { + return this.corpId; + } + + @Override + public String getCorpSecret() { + return this.corpSecret; + } + + @Override + public String getAgentId() { + return this.agentId; + } + + @Override + public String getToken() { + return this.token; + } + + @Override + public String getAesKey() { + return this.aesKey; + } + + @Override + public long getExpiresTime() { + try (Jedis jedis = this.jedisPool.getResource()) { + String expiresTimeStr = jedis.get(ACCESS_TOKEN_EXPIRES_TIME_KEY); + + if (expiresTimeStr != null) { + Long expiresTime = Long.parseLong(expiresTimeStr); + return expiresTime; + } + + return 0L; + + } + } + + @Override + public String getOauth2redirectUri() { + return this.oauth2redirectUri; + } + + @Override + public String getHttp_proxy_host() { + return this.http_proxy_host; + } + + @Override + public int getHttp_proxy_port() { + return this.http_proxy_port; + } + + @Override + public String getHttp_proxy_username() { + return this.http_proxy_username; + } + + @Override + public String getHttp_proxy_password() { + return this.http_proxy_password; + } + + @Override + public File getTmpDirFile() { + return this.tmpDirFile; + } + + @Override + public ApacheHttpClientBuilder getApacheHttpClientBuilder() { + return this.apacheHttpClientBuilder; + } + + public void setCorpId(String corpId) { + this.corpId = corpId; + } + + public void setCorpSecret(String corpSecret) { + this.corpSecret = corpSecret; + } + + public void setToken(String token) { + this.token = token; + } + + public void setAesKey(String aesKey) { + this.aesKey = aesKey; + } + + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + // ============================ Setters below + + public void setOauth2redirectUri(String oauth2redirectUri) { + this.oauth2redirectUri = oauth2redirectUri; + } + + public void setHttp_proxy_host(String http_proxy_host) { + this.http_proxy_host = http_proxy_host; + } + + public void setHttp_proxy_port(int http_proxy_port) { + this.http_proxy_port = http_proxy_port; + } + + public void setHttp_proxy_username(String http_proxy_username) { + this.http_proxy_username = http_proxy_username; + } + + public void setHttp_proxy_password(String http_proxy_password) { + this.http_proxy_password = http_proxy_password; + } + + public void setTmpDirFile(File tmpDirFile) { + this.tmpDirFile = tmpDirFile; + } + + public void setApacheHttpClientBuilder(ApacheHttpClientBuilder apacheHttpClientBuilder) { + this.apacheHttpClientBuilder = apacheHttpClientBuilder; + } + +} diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageHandler.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageHandler.java index 36649c46a2..9a3920a285 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageHandler.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageHandler.java @@ -1,7 +1,6 @@ package me.chanjar.weixin.cp.api; import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.common.session.WxSession; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.cp.bean.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java index f7e5286ba9..bdda1886cc 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouter.java @@ -1,13 +1,13 @@ package me.chanjar.weixin.cp.api; +import me.chanjar.weixin.common.api.WxErrorExceptionHandler; +import me.chanjar.weixin.common.api.WxMessageDuplicateChecker; +import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; import me.chanjar.weixin.common.session.InternalSession; import me.chanjar.weixin.common.session.InternalSessionManager; import me.chanjar.weixin.common.session.StandardSessionManager; import me.chanjar.weixin.common.session.WxSessionManager; import me.chanjar.weixin.common.util.LogExceptionHandler; -import me.chanjar.weixin.common.api.WxErrorExceptionHandler; -import me.chanjar.weixin.common.api.WxMessageDuplicateChecker; -import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker; import me.chanjar.weixin.cp.bean.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; import org.slf4j.Logger; @@ -45,15 +45,13 @@ * router.route(message); * * - * @author Daniel Qian * + * @author Daniel Qian */ public class WxCpMessageRouter { - protected final Logger log = LoggerFactory.getLogger(WxCpMessageRouter.class); - private static final int DEFAULT_THREAD_POOL_SIZE = 100; - + protected final Logger log = LoggerFactory.getLogger(WxCpMessageRouter.class); private final List rules = new ArrayList(); private final WxCpService wxCpService; @@ -79,6 +77,7 @@ public WxCpMessageRouter(WxCpService wxCpService) { * 设置自定义的 {@link ExecutorService} * 如果不调用该方法,默认使用 Executors.newFixedThreadPool(100) * + * * @param executorService */ public void setExecutorService(ExecutorService executorService) { @@ -90,6 +89,7 @@ public void setExecutorService(ExecutorService executorService) { * 设置自定义的 {@link me.chanjar.weixin.common.api.WxMessageDuplicateChecker} * 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker} * + * * @param messageDuplicateChecker */ public void setMessageDuplicateChecker(WxMessageDuplicateChecker messageDuplicateChecker) { @@ -101,6 +101,7 @@ public void setMessageDuplicateChecker(WxMessageDuplicateChecker messageDuplicat * 设置自定义的{@link me.chanjar.weixin.common.session.WxSessionManager} * 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.session.StandardSessionManager} * + * * @param sessionManager */ public void setSessionManager(WxSessionManager sessionManager) { @@ -112,6 +113,7 @@ public void setSessionManager(WxSessionManager sessionManager) { * 设置自定义的{@link me.chanjar.weixin.common.api.WxErrorExceptionHandler} * 如果不调用该方法,默认使用 {@link me.chanjar.weixin.common.util.LogExceptionHandler} * + * * @param exceptionHandler */ public void setExceptionHandler(WxErrorExceptionHandler exceptionHandler) { @@ -131,6 +133,7 @@ public WxCpMessageRouterRule rule() { /** * 处理微信消息 + * * @param wxMessage */ public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) { @@ -144,7 +147,7 @@ public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) { for (final WxCpMessageRouterRule rule : rules) { if (rule.test(wxMessage)) { matchRules.add(rule); - if(!rule.isReEnter()) { + if (!rule.isReEnter()) { break; } } @@ -158,13 +161,13 @@ public WxCpXmlOutMessage route(final WxCpXmlMessage wxMessage) { final List futures = new ArrayList(); for (final WxCpMessageRouterRule rule : matchRules) { // 返回最后一个非异步的rule的执行结果 - if(rule.isAsync()) { + if (rule.isAsync()) { futures.add( - executorService.submit(new Runnable() { - public void run() { - rule.service(wxMessage, wxCpService, sessionManager, exceptionHandler); - } - }) + executorService.submit(new Runnable() { + public void run() { + rule.service(wxMessage, wxCpService, sessionManager, exceptionHandler); + } + }) ); } else { res = rule.service(wxMessage, wxCpService, sessionManager, exceptionHandler); @@ -201,10 +204,10 @@ protected boolean isDuplicateMessage(WxCpXmlMessage wxMessage) { String messageId = ""; if (wxMessage.getMsgId() == null) { messageId = String.valueOf(wxMessage.getCreateTime()) - + "-" +String.valueOf(wxMessage.getAgentId() == null ? "" : wxMessage.getAgentId()) - + "-" + wxMessage.getFromUserName() - + "-" + String.valueOf(wxMessage.getEventKey() == null ? "" : wxMessage.getEventKey()) - + "-" + String.valueOf(wxMessage.getEvent() == null ? "" : wxMessage.getEvent()) + + "-" + String.valueOf(wxMessage.getAgentId() == null ? "" : wxMessage.getAgentId()) + + "-" + wxMessage.getFromUserName() + + "-" + String.valueOf(wxMessage.getEventKey() == null ? "" : wxMessage.getEventKey()) + + "-" + String.valueOf(wxMessage.getEvent() == null ? "" : wxMessage.getEvent()) ; } else { messageId = String.valueOf(wxMessage.getMsgId()); @@ -216,11 +219,12 @@ protected boolean isDuplicateMessage(WxCpXmlMessage wxMessage) { /** * 对session的访问结束 + * * @param wxMessage */ protected void sessionEndAccess(WxCpXmlMessage wxMessage) { - InternalSession session = ((InternalSessionManager)sessionManager).findSession(wxMessage.getFromUserName()); + InternalSession session = ((InternalSessionManager) sessionManager).findSession(wxMessage.getFromUserName()); if (session != null) { session.endAccess(); } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java index 6d68332309..a987841c05 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpMessageRouterRule.java @@ -1,8 +1,8 @@ package me.chanjar.weixin.cp.api; +import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.common.api.WxErrorExceptionHandler; import me.chanjar.weixin.cp.bean.WxCpXmlMessage; import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; @@ -186,7 +186,6 @@ public WxCpMessageRouterRule handler(WxCpMessageHandler handler, WxCpMessageHand /** * 规则结束,代表如果一个消息匹配该规则,那么它将不再会进入其他规则 - * */ public WxCpMessageRouter end() { this.routerBuilder.getRules().add(this); @@ -195,7 +194,6 @@ public WxCpMessageRouter end() { /** * 规则结束,但是消息还会进入其他规则 - * */ public WxCpMessageRouter next() { this.reEnter = true; @@ -204,24 +202,24 @@ public WxCpMessageRouter next() { protected boolean test(WxCpXmlMessage wxMessage) { return - (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUserName())) - && - (this.agentId == null || this.agentId.equals(wxMessage.getAgentId())) - && - (this.msgType == null || this.msgType.equals(wxMessage.getMsgType())) - && - (this.event == null || this.event.equals(wxMessage.getEvent())) - && - (this.eventKey == null || this.eventKey.equals(wxMessage.getEventKey())) - && - (this.content == null || this.content - .equals(wxMessage.getContent() == null ? null : wxMessage.getContent().trim())) - && - (this.rContent == null || Pattern - .matches(this.rContent, wxMessage.getContent() == null ? "" : wxMessage.getContent().trim())) - && - (this.matcher == null || this.matcher.match(wxMessage)) - ; + (this.fromUser == null || this.fromUser.equals(wxMessage.getFromUserName())) + && + (this.agentId == null || this.agentId.equals(wxMessage.getAgentId())) + && + (this.msgType == null || this.msgType.equals(wxMessage.getMsgType())) + && + (this.event == null || this.event.equals(wxMessage.getEvent())) + && + (this.eventKey == null || this.eventKey.equals(wxMessage.getEventKey())) + && + (this.content == null || this.content + .equals(wxMessage.getContent() == null ? null : wxMessage.getContent().trim())) + && + (this.rContent == null || Pattern + .matches(this.rContent, wxMessage.getContent() == null ? "" : wxMessage.getContent().trim())) + && + (this.matcher == null || this.matcher.match(wxMessage)) + ; } /** @@ -231,9 +229,9 @@ protected boolean test(WxCpXmlMessage wxMessage) { * @return true 代表继续执行别的router,false 代表停止执行别的router */ protected WxCpXmlOutMessage service(WxCpXmlMessage wxMessage, - WxCpService wxCpService, - WxSessionManager sessionManager, - WxErrorExceptionHandler exceptionHandler) { + WxCpService wxCpService, + WxSessionManager sessionManager, + WxErrorExceptionHandler exceptionHandler) { try { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java index 7cf9332a7e..e6f8f2ad2f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpService.java @@ -1,7 +1,7 @@ package me.chanjar.weixin.cp.api; import me.chanjar.weixin.common.bean.WxJsapiSignature; -import me.chanjar.weixin.common.bean.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.session.WxSession; @@ -47,8 +47,9 @@ public interface WxCpService { /** * 获取access_token, 不强制刷新access_token - * @see #getAccessToken(boolean) + * * @throws WxErrorException + * @see #getAccessToken(boolean) */ String getAccessToken() throws WxErrorException; @@ -60,6 +61,7 @@ public interface WxCpService { * 程序员在非必要情况下尽量不要主动调用此方法 * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=获取access_token * + * * @param forceRefresh 强制刷新 * @throws me.chanjar.weixin.common.exception.WxErrorException */ @@ -67,8 +69,9 @@ public interface WxCpService { /** * 获得jsapi_ticket,不强制刷新jsapi_ticket - * @see #getJsapiTicket(boolean) + * * @throws WxErrorException + * @see #getJsapiTicket(boolean) */ String getJsapiTicket() throws WxErrorException; @@ -79,6 +82,7 @@ public interface WxCpService { * * 详情请见:http://qydev.weixin.qq.com/wiki/index.php?title=微信JS接口#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95 * + * * @param forceRefresh 强制刷新 * @throws WxErrorException */ @@ -90,7 +94,8 @@ public interface WxCpService { * * 详情请见:http://qydev.weixin.qq.com/wiki/index.php?title=微信JS接口#.E9.99.84.E5.BD.951-JS-SDK.E4.BD.BF.E7.94.A8.E6.9D.83.E9.99.90.E7.AD.BE.E5.90.8D.E7.AE.97.E6.B3.95 * - * @param url url + * + * @param url url */ WxJsapiSignature createJsapiSignature(String url) throws WxErrorException; @@ -111,7 +116,7 @@ public interface WxCpService { * @throws WxErrorException */ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) - throws WxErrorException, IOException; + throws WxErrorException, IOException; /** * @param mediaType @@ -128,9 +133,9 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=上传下载多媒体文件 * * + * @param media_id * @return 保存到本地的临时文件 * @throws WxErrorException - * @param media_id */ File mediaDownload(String media_id) throws WxErrorException; @@ -152,10 +157,10 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法使用WxCpConfigStorage里的agentId * - * @see #menuCreate(String, me.chanjar.weixin.common.bean.WxMenu) * * @param menu * @throws WxErrorException + * @see #menuCreate(String, me.chanjar.weixin.common.bean.menu.WxMenu) */ void menuCreate(WxMenu menu) throws WxErrorException; @@ -166,11 +171,11 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法不使用WxCpConfigStorage里的agentId,需要开发人员自己给出 * - * @see #menuCreate(me.chanjar.weixin.common.bean.WxMenu) * * @param agentId 企业号应用的id * @param menu * @throws WxErrorException + * @see #menuCreate(me.chanjar.weixin.common.bean.menu.WxMenu) */ void menuCreate(String agentId, WxMenu menu) throws WxErrorException; @@ -181,9 +186,9 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法使用WxCpConfigStorage里的agentId * - * @see #menuDelete(String) * * @throws WxErrorException + * @see #menuDelete(String) */ void menuDelete() throws WxErrorException; @@ -194,10 +199,10 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法不使用WxCpConfigStorage里的agentId,需要开发人员自己给出 * - * @see #menuDelete() * * @param agentId 企业号应用的id * @throws WxErrorException + * @see #menuDelete() */ void menuDelete(String agentId) throws WxErrorException; @@ -208,9 +213,9 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法使用WxCpConfigStorage里的agentId * - * @see #menuGet(String) * * @throws WxErrorException + * @see #menuGet(String) */ WxMenu menuGet() throws WxErrorException; @@ -221,10 +226,10 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法不使用WxCpConfigStorage里的agentId,需要开发人员自己给出 * - * @see #menuGet() * * @param agentId 企业号应用的id * @throws WxErrorException + * @see #menuGet() */ WxMenu menuGet(String agentId) throws WxErrorException; @@ -279,9 +284,10 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * http://qydev.weixin.qq.com/wiki/index.php?title=管理成员#.E8.8E.B7.E5.8F.96.E9.83.A8.E9.97.A8.E6.88.90.E5.91.98.28.E8.AF.A6.E6.83.85.29 * - * @param departId 必填。部门id - * @param fetchChild 非必填。1/0:是否递归获取子部门下面的成员 - * @param status 非必填。0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加 + * + * @param departId 必填。部门id + * @param fetchChild 非必填。1/0:是否递归获取子部门下面的成员 + * @param status 非必填。0获取全部员工,1获取已关注成员列表,2获取禁用成员列表,4获取未关注成员列表。status可叠加 * @throws WxErrorException */ List userList(Integer departId, Boolean fetchChild, Integer status) throws WxErrorException; @@ -330,7 +336,8 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * http://qydev.weixin.qq.com/wiki/index.php?title=管理成员#.E6.89.B9.E9.87.8F.E5.88.A0.E9.99.A4.E6.88.90.E5.91.98 * - * @param userids 员工UserID列表。对应管理端的帐号 + * + * @param userids 员工UserID列表。对应管理端的帐号 * @throws WxErrorException */ void userDelete(String[] userids) throws WxErrorException; @@ -367,7 +374,6 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i /** * 获得标签列表 - * */ List tagGet() throws WxErrorException; @@ -386,11 +392,22 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i */ void tagAddUsers(String tagId, List userIds, List partyIds) throws WxErrorException; + /** + *

    +   * 构造oauth2授权的url连接
    +   * 
    + * + * @param state + * @return url + */ + String oauth2buildAuthorizationUrl(String state); + /** *
        * 构造oauth2授权的url连接
        * 详情请见: http://qydev.weixin.qq.com/wiki/index.php?title=企业获取code
        * 
    + * * @param redirectUri * @param state * @return url @@ -405,10 +422,10 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法使用WxCpConfigStorage里的agentId * - * @see #oauth2getUserInfo(String, String) * * @param code * @return [userid, deviceid] + * @see #oauth2getUserInfo(String, String) */ String[] oauth2getUserInfo(String code) throws WxErrorException; @@ -420,11 +437,11 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * * 注意: 这个方法不使用WxCpConfigStorage里的agentId,需要开发人员自己给出 * - * @see #oauth2getUserInfo(String) * * @param agentId 企业号应用的id * @param code * @return [userid, deviceid] + * @see #oauth2getUserInfo(String) */ String[] oauth2getUserInfo(String agentId, String code) throws WxErrorException; @@ -442,8 +459,9 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 邀请成员关注 * http://qydev.weixin.qq.com/wiki/index.php?title=管理成员#.E9.82.80.E8.AF.B7.E6.88.90.E5.91.98.E5.85.B3.E6.B3.A8 * - * @param userId 用户的userid - * @param inviteTips 推送到微信上的提示语(只有认证号可以使用)。当使用微信推送时,该字段默认为“请关注XXX企业号”,邮件邀请时,该字段无效。 + * + * @param userId 用户的userid + * @param inviteTips 推送到微信上的提示语(只有认证号可以使用)。当使用微信推送时,该字段默认为“请关注XXX企业号”,邮件邀请时,该字段无效。 * @return 1:微信邀请 2.邮件邀请 * @throws WxErrorException */ @@ -454,6 +472,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 获取微信服务器的ip段 * http://qydev.weixin.qq.com/wiki/index.php?title=回调模式#.E8.8E.B7.E5.8F.96.E5.BE.AE.E4.BF.A1.E6.9C.8D.E5.8A.A1.E5.99.A8.E7.9A.84ip.E6.AE.B5 * + * * @return { "ip_list": ["101.226.103.*", "101.226.62.*"] } * @throws WxErrorException */ @@ -461,6 +480,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i /** * 当本Service没有实现某个API的时候,可以用这个,针对所有微信API中的GET请求 + * * @param url * @param queryParam * @throws WxErrorException @@ -469,6 +489,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i /** * 当本Service没有实现某个API的时候,可以用这个,针对所有微信API中的POST请求 + * * @param url * @param postData * @throws WxErrorException @@ -481,6 +502,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 比{@link #get}和{@link #post}方法更灵活,可以自己构造RequestExecutor用来处理不同的参数和不同的返回类型。 * 可以参考,{@link me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor}的实现方法 * + * * @param executor * @param uri * @param data @@ -502,6 +524,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 设置当微信系统响应系统繁忙时,要等待多少 retrySleepMillis(ms) * 2^(重试次数 - 1) 再发起重试 * 默认:1000ms * + * * @param retrySleepMillis */ void setRetrySleepMillis(int retrySleepMillis); @@ -511,19 +534,22 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 设置当微信系统响应系统繁忙时,最大重试次数 * 默认:5次 * + * * @param maxRetryTimes */ void setMaxRetryTimes(int maxRetryTimes); /** * 获取某个sessionId对应的session,如果sessionId没有对应的session,则新建一个并返回。 + * * @param id id可以为任意字符串,建议使用FromUserName作为id */ WxSession getSession(String id); /** * 获取某个sessionId对应的session,如果sessionId没有对应的session,若create为true则新建一个,否则返回null。 - * @param id id可以为任意字符串,建议使用FromUserName作为id + * + * @param id id可以为任意字符串,建议使用FromUserName作为id * @param create */ WxSession getSession(String id, boolean create); @@ -533,12 +559,14 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i * 设置WxSessionManager,只有当需要使用个性化的WxSessionManager的时候才需要调用此方法, * WxCpService默认使用的是{@link me.chanjar.weixin.common.session.StandardSessionManager} * + * * @param sessionManager */ void setSessionManager(WxSessionManager sessionManager); /** * 上传部门列表覆盖企业号上的部门信息 + * * @param mediaId * @throws WxErrorException */ @@ -546,6 +574,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i /** * 上传用户列表覆盖企业号上的用户信息 + * * @param mediaId * @throws WxErrorException */ @@ -553,6 +582,7 @@ WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream i /** * 获取异步任务结果 + * * @param joinId * @throws WxErrorException */ diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java index 1cf517abd7..278fe6c8f6 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpServiceImpl.java @@ -9,7 +9,7 @@ import com.google.gson.stream.JsonReader; import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.WxJsapiSignature; -import me.chanjar.weixin.common.bean.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; import me.chanjar.weixin.common.exception.WxErrorException; @@ -64,17 +64,13 @@ public class WxCpServiceImpl implements WxCpService { protected CloseableHttpClient httpClient; protected HttpHost httpProxy; - - private int retrySleepMillis = 1000; - - private int maxRetryTimes = 5; - protected WxSessionManager sessionManager = new StandardSessionManager(); - /** * 临时文件目录 */ protected File tmpDirFile; + private int retrySleepMillis = 1000; + private int maxRetryTimes = 5; public boolean checkSignature(String msgSignature, String timestamp, String nonce, String data) { try { @@ -101,8 +97,8 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException { synchronized (globalAccessTokenRefreshLock) { if (wxCpConfigStorage.isAccessTokenExpired()) { String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?" - + "&corpid=" + wxCpConfigStorage.getCorpId() - + "&corpsecret=" + wxCpConfigStorage.getCorpSecret(); + + "&corpid=" + wxCpConfigStorage.getCorpId() + + "&corpsecret=" + wxCpConfigStorage.getCorpSecret(); try { HttpGet httpGet = new HttpGet(url); if (httpProxy != null) { @@ -113,7 +109,7 @@ public String getAccessToken(boolean forceRefresh) throws WxErrorException { String resultContent = null; try (CloseableHttpResponse response = httpclient.execute(httpGet)) { resultContent = new BasicResponseHandler().handleResponse(response); - }finally { + } finally { httpGet.releaseConnection(); } WxError error = WxError.fromJson(resultContent); @@ -163,16 +159,20 @@ public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException String jsapiTicket = getJsapiTicket(false); try { String signature = SHA1.genWithAmple( - "jsapi_ticket=" + jsapiTicket, - "noncestr=" + noncestr, - "timestamp=" + timestamp, - "url=" + url + "jsapi_ticket=" + jsapiTicket, + "noncestr=" + noncestr, + "timestamp=" + timestamp, + "url=" + url ); WxJsapiSignature jsapiSignature = new WxJsapiSignature(); jsapiSignature.setTimestamp(timestamp); jsapiSignature.setNoncestr(noncestr); jsapiSignature.setUrl(url); jsapiSignature.setSignature(signature); + + // Fixed bug + jsapiSignature.setAppid(this.wxCpConfigStorage.getCorpId()); + return jsapiSignature; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); @@ -227,7 +227,7 @@ public WxMenu menuGet(String agentId) throws WxErrorException { } public WxMediaUploadResult mediaUpload(String mediaType, String fileType, InputStream inputStream) - throws WxErrorException, IOException { + throws WxErrorException, IOException { return mediaUpload(mediaType, FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), fileType)); } @@ -245,9 +245,9 @@ public File mediaDownload(String media_id) throws WxErrorException { public Integer departCreate(WxCpDepart depart) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create"; String responseContent = execute( - new SimplePostRequestExecutor(), - url, - depart.toJson()); + new SimplePostRequestExecutor(), + url, + depart.toJson()); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return GsonHelper.getAsInteger(tmpJsonElement.getAsJsonObject().get("id")); } @@ -271,11 +271,11 @@ public List departGet() throws WxErrorException { */ JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() - .fromJson( - tmpJsonElement.getAsJsonObject().get("department"), - new TypeToken>() { - }.getType() - ); + .fromJson( + tmpJsonElement.getAsJsonObject().get("department"), + new TypeToken>() { + }.getType() + ); } @Override @@ -331,10 +331,11 @@ public List userList(Integer departId, Boolean fetchChild, Integer sta String responseContent = get(url, params); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() - .fromJson( - tmpJsonElement.getAsJsonObject().get("userlist"), - new TypeToken>() { }.getType() - ); + .fromJson( + tmpJsonElement.getAsJsonObject().get("userlist"), + new TypeToken>() { + }.getType() + ); } @Override @@ -353,10 +354,11 @@ public List departGetUsers(Integer departId, Boolean fetchChild, Integ String responseContent = get(url, params); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() - .fromJson( - tmpJsonElement.getAsJsonObject().get("userlist"), - new TypeToken>() { }.getType() - ); + .fromJson( + tmpJsonElement.getAsJsonObject().get("userlist"), + new TypeToken>() { + }.getType() + ); } @Override @@ -390,11 +392,11 @@ public List tagGet() throws WxErrorException { String responseContent = get(url, null); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() - .fromJson( - tmpJsonElement.getAsJsonObject().get("taglist"), - new TypeToken>() { - }.getType() - ); + .fromJson( + tmpJsonElement.getAsJsonObject().get("taglist"), + new TypeToken>() { + }.getType() + ); } @Override @@ -403,10 +405,11 @@ public List tagGetUsers(String tagId) throws WxErrorException { String responseContent = get(url, null); JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); return WxCpGsonBuilder.INSTANCE.create() - .fromJson( - tmpJsonElement.getAsJsonObject().get("userlist"), - new TypeToken>() { }.getType() - ); + .fromJson( + tmpJsonElement.getAsJsonObject().get("userlist"), + new TypeToken>() { + }.getType() + ); } @Override @@ -445,8 +448,16 @@ public void tagRemoveUsers(String tagId, List userIds) throws WxErrorExc } @Override + public String oauth2buildAuthorizationUrl(String state) { + return this.oauth2buildAuthorizationUrl( + this.wxCpConfigStorage.getOauth2redirectUri(), + state + ); + } + + @Override public String oauth2buildAuthorizationUrl(String redirectUri, String state) { - String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" ; + String url = "https://open.weixin.qq.com/connect/oauth2/authorize?"; url += "appid=" + wxCpConfigStorage.getCorpId(); url += "&redirect_uri=" + URIUtil.encodeURIComponent(redirectUri); url += "&response_type=code"; @@ -466,12 +477,12 @@ public String[] oauth2getUserInfo(String code) throws WxErrorException { @Override public String[] oauth2getUserInfo(String agentId, String code) throws WxErrorException { String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?" - + "code=" + code - + "&agendid=" + agentId; + + "code=" + code + + "&agendid=" + agentId; String responseText = get(url, null); JsonElement je = Streams.parse(new JsonReader(new StringReader(responseText))); JsonObject jo = je.getAsJsonObject(); - return new String[] {GsonHelper.getString(jo, "UserId"), GsonHelper.getString(jo, "DeviceId")}; + return new String[]{GsonHelper.getString(jo, "UserId"), GsonHelper.getString(jo, "DeviceId")}; } @Override @@ -494,7 +505,7 @@ public String[] getCallbackIp() throws WxErrorException { JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); JsonArray jsonArray = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray(); String[] ips = new String[jsonArray.size()]; - for(int i = 0; i < jsonArray.size(); i++) { + for (int i = 0; i < jsonArray.size(); i++) { ips[i] = jsonArray.get(i).getAsString(); } return ips; @@ -533,7 +544,7 @@ public T execute(RequestExecutor executor, String uri, E data) thro throw e; } } - } while(++retryTimes < maxRetryTimes); + } while (++retryTimes < maxRetryTimes); throw new RuntimeException("微信服务端异常,超出重试次数"); } @@ -571,6 +582,7 @@ protected synchronized T executeInternal(RequestExecutor executor, throw new RuntimeException(e); } } + protected CloseableHttpClient getHttpclient() { return httpClient; } @@ -579,12 +591,12 @@ public void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider) { this.wxCpConfigStorage = wxConfigProvider; ApacheHttpClientBuilder apacheHttpClientBuilder = wxCpConfigStorage.getApacheHttpClientBuilder(); if (null == apacheHttpClientBuilder) { - apacheHttpClientBuilder = DefaultApacheHttpHttpClientBuilder.get(); + apacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get(); } apacheHttpClientBuilder.httpProxyHost(wxCpConfigStorage.getHttp_proxy_host()) - .httpProxyPort(wxCpConfigStorage.getHttp_proxy_port()) - .httpProxyUsername(wxCpConfigStorage.getHttp_proxy_username()) - .httpProxyPassword(wxCpConfigStorage.getHttp_proxy_password()); + .httpProxyPort(wxCpConfigStorage.getHttp_proxy_port()) + .httpProxyUsername(wxCpConfigStorage.getHttp_proxy_username()) + .httpProxyPassword(wxCpConfigStorage.getHttp_proxy_password()); httpClient = apacheHttpClientBuilder.build(); } @@ -621,27 +633,27 @@ public WxSession getSession(String id, boolean create) { public void setSessionManager(WxSessionManager sessionManager) { this.sessionManager = sessionManager; } - + @Override public String replaceParty(String mediaId) throws WxErrorException { - String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceparty"; - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("media_id", mediaId); - return post(url, jsonObject.toString()); + String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceparty"; + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("media_id", mediaId); + return post(url, jsonObject.toString()); } @Override public String replaceUser(String mediaId) throws WxErrorException { - String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceuser"; - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("media_id", mediaId); - return post(url, jsonObject.toString()); + String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/replaceuser"; + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("media_id", mediaId); + return post(url, jsonObject.toString()); } @Override public String getTaskResult(String joinId) throws WxErrorException { - String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/getresult?jobid="+joinId; - return get(url, null); + String url = "https://qyapi.weixin.qq.com/cgi-bin/batch/getresult?jobid=" + joinId; + return get(url, null); } public File getTmpDirFile() { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java index 04fb46fde3..e2bfbd3953 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpDepart.java @@ -16,6 +16,10 @@ public class WxCpDepart implements Serializable { private Integer parentId; private Integer order; + public static WxCpDepart fromJson(String json) { + return WxCpGsonBuilder.create().fromJson(json, WxCpDepart.class); + } + public Integer getId() { return id; } @@ -48,10 +52,6 @@ public void setOrder(Integer order) { this.order = order; } - public static WxCpDepart fromJson(String json) { - return WxCpGsonBuilder.create().fromJson(json, WxCpDepart.class); - } - public String toJson() { return WxCpGsonBuilder.create().toJson(this); } @@ -59,10 +59,10 @@ public String toJson() { @Override public String toString() { return "WxCpDepart{" + - "id=" + id + - ", name='" + name + '\'' + - ", parentId=" + parentId + - ", order=" + order + - '}'; + "id=" + id + + ", name='" + name + '\'' + + ", parentId=" + parentId + + ", order=" + order + + '}'; } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java index 25734aef85..8961152507 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpMessage.java @@ -9,8 +9,8 @@ /** * 消息 - * @author Daniel Qian * + * @author Daniel Qian */ public class WxCpMessage implements Serializable { @@ -29,9 +29,52 @@ public class WxCpMessage implements Serializable { private String safe; private List articles = new ArrayList(); + /** + * 获得文本消息builder + */ + public static TextBuilder TEXT() { + return new TextBuilder(); + } + + /** + * 获得图片消息builder + */ + public static ImageBuilder IMAGE() { + return new ImageBuilder(); + } + + /** + * 获得语音消息builder + */ + public static VoiceBuilder VOICE() { + return new VoiceBuilder(); + } + + /** + * 获得视频消息builder + */ + public static VideoBuilder VIDEO() { + return new VideoBuilder(); + } + + /** + * 获得图文消息builder + */ + public static NewsBuilder NEWS() { + return new NewsBuilder(); + } + + /** + * 获得文件消息builder + */ + public static FileBuilder FILE() { + return new FileBuilder(); + } + public String getToUser() { return toUser; } + public void setToUser(String toUser) { this.toUser = toUser; } @@ -64,14 +107,6 @@ public String getMsgType() { return msgType; } - public String getSafe() { - return safe; - } - - public void setSafe(String safe) { - this.safe = safe; - } - /** *
        * 请使用
    @@ -82,56 +117,81 @@ public void setSafe(String safe) {
        * {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_VIDEO}
        * {@link me.chanjar.weixin.common.api.WxConsts#CUSTOM_MSG_NEWS}
        * 
    + * * @param msgType */ public void setMsgType(String msgType) { this.msgType = msgType; } + + public String getSafe() { + return safe; + } + + public void setSafe(String safe) { + this.safe = safe; + } + public String getContent() { return content; } + public void setContent(String content) { this.content = content; } + public String getMediaId() { return mediaId; } + public void setMediaId(String mediaId) { this.mediaId = mediaId; } + public String getThumbMediaId() { return thumbMediaId; } + public void setThumbMediaId(String thumbMediaId) { this.thumbMediaId = thumbMediaId; } + public String getTitle() { return title; } + public void setTitle(String title) { this.title = title; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public String getMusicUrl() { return musicUrl; } + public void setMusicUrl(String musicUrl) { this.musicUrl = musicUrl; } + public String getHqMusicUrl() { return hqMusicUrl; } + public void setHqMusicUrl(String hqMusicUrl) { this.hqMusicUrl = hqMusicUrl; } + public List getArticles() { return articles; } + public void setArticles(List articles) { this.articles = articles; } @@ -150,70 +210,35 @@ public static class WxArticle { public String getTitle() { return title; } + public void setTitle(String title) { this.title = title; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public String getUrl() { return url; } + public void setUrl(String url) { this.url = url; } + public String getPicUrl() { return picUrl; } + public void setPicUrl(String picUrl) { this.picUrl = picUrl; } } - /** - * 获得文本消息builder - */ - public static TextBuilder TEXT() { - return new TextBuilder(); - } - - /** - * 获得图片消息builder - */ - public static ImageBuilder IMAGE() { - return new ImageBuilder(); - } - - /** - * 获得语音消息builder - */ - public static VoiceBuilder VOICE() { - return new VoiceBuilder(); - } - - /** - * 获得视频消息builder - */ - public static VideoBuilder VIDEO() { - return new VideoBuilder(); - } - - /** - * 获得图文消息builder - */ - public static NewsBuilder NEWS() { - return new NewsBuilder(); - } - - /** - * 获得文件消息builder - */ - public static FileBuilder FILE() { - return new FileBuilder(); - } - } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java index 6c5d42c6e2..72fd66287b 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpTag.java @@ -23,6 +23,10 @@ public WxCpTag(String id, String name) { this.name = name; } + public static WxCpTag fromJson(String json) { + return WxCpGsonBuilder.create().fromJson(json, WxCpTag.class); + } + public String getName() { return name; } @@ -39,10 +43,6 @@ public void setId(String id) { this.id = id; } - public static WxCpTag fromJson(String json) { - return WxCpGsonBuilder.create().fromJson(json, WxCpTag.class); - } - public String toJson() { return WxCpGsonBuilder.create().toJson(this); } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java index 58b1d5ca3d..e96206eb20 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpUser.java @@ -13,6 +13,7 @@ */ public class WxCpUser implements Serializable { + private final List extAttrs = new ArrayList(); private String userId; private String name; private Integer[] departIds; @@ -25,7 +26,10 @@ public class WxCpUser implements Serializable { private String avatar; private Integer status; private Integer enable; - private final List extAttrs = new ArrayList(); + + public static WxCpUser fromJson(String json) { + return WxCpGsonBuilder.INSTANCE.create().fromJson(json, WxCpUser.class); + } public String getUserId() { return userId; @@ -116,13 +120,13 @@ public void setStatus(Integer status) { } public Integer getEnable() { - return enable; + return enable; } - + public void setEnable(Integer enable) { - this.enable = enable; + this.enable = enable; } - + public void addExtAttr(String name, String value) { this.extAttrs.add(new Attr(name, value)); } @@ -135,10 +139,6 @@ public String toJson() { return WxCpGsonBuilder.INSTANCE.create().toJson(this); } - public static WxCpUser fromJson(String json) { - return WxCpGsonBuilder.INSTANCE.create().fromJson(json, WxCpUser.class); - } - public static class Attr { private String name; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java index eaf926e2a2..0b833e06a2 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlMessage.java @@ -36,41 +36,41 @@ public class WxCpXmlMessage implements Serializable { private Integer agentId; @XStreamAlias("ToUserName") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String toUserName; @XStreamAlias("FromUserName") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String fromUserName; @XStreamAlias("CreateTime") private Long createTime; @XStreamAlias("MsgType") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String msgType; @XStreamAlias("Content") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String content; @XStreamAlias("MsgId") private Long msgId; @XStreamAlias("PicUrl") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String picUrl; @XStreamAlias("MediaId") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String mediaId; @XStreamAlias("Format") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String format; @XStreamAlias("ThumbMediaId") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String thumbMediaId; @XStreamAlias("Location_X") @@ -83,31 +83,31 @@ public class WxCpXmlMessage implements Serializable { private Double scale; @XStreamAlias("Label") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String label; @XStreamAlias("Title") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String title; @XStreamAlias("Description") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String description; @XStreamAlias("Url") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String url; @XStreamAlias("Event") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String event; @XStreamAlias("EventKey") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String eventKey; @XStreamAlias("Ticket") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String ticket; @XStreamAlias("Latitude") @@ -120,7 +120,7 @@ public class WxCpXmlMessage implements Serializable { private Double precision; @XStreamAlias("Recognition") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String recognition; /////////////////////////////////////// @@ -130,7 +130,7 @@ public class WxCpXmlMessage implements Serializable { * 群发的结果 */ @XStreamAlias("Status") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String status; /** * group_id下粉丝数;或者openid_list中的粉丝数 @@ -162,6 +162,43 @@ public class WxCpXmlMessage implements Serializable { @XStreamAlias("SendLocationInfo") private SendLocationInfo sendLocationInfo = new SendLocationInfo(); + protected static WxCpXmlMessage fromXml(String xml) { + return XStreamTransformer.fromXml(WxCpXmlMessage.class, xml); + } + + protected static WxCpXmlMessage fromXml(InputStream is) { + return XStreamTransformer.fromXml(WxCpXmlMessage.class, is); + } + + /** + * 从加密字符串转换 + * + * @param encryptedXml + * @param wxCpConfigStorage + * @param timestamp + * @param nonce + * @param msgSignature + */ + public static WxCpXmlMessage fromEncryptedXml( + String encryptedXml, + WxCpConfigStorage wxCpConfigStorage, + String timestamp, String nonce, String msgSignature) { + WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage); + String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml); + return fromXml(plainText); + } + + public static WxCpXmlMessage fromEncryptedXml( + InputStream is, + WxCpConfigStorage wxCpConfigStorage, + String timestamp, String nonce, String msgSignature) { + try { + return fromEncryptedXml(IOUtils.toString(is, "UTF-8"), wxCpConfigStorage, timestamp, nonce, msgSignature); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + public Integer getAgentId() { return agentId; } @@ -197,7 +234,6 @@ public void setCreateTime(Long createTime) { * {@link me.chanjar.weixin.common.api.WxConsts#XML_MSG_LINK} * {@link me.chanjar.weixin.common.api.WxConsts#XML_MSG_EVENT} * - * */ public String getMsgType() { return msgType; @@ -387,43 +423,6 @@ public void setFromUserName(String fromUserName) { this.fromUserName = fromUserName; } - protected static WxCpXmlMessage fromXml(String xml) { - return XStreamTransformer.fromXml(WxCpXmlMessage.class, xml); - } - - protected static WxCpXmlMessage fromXml(InputStream is) { - return XStreamTransformer.fromXml(WxCpXmlMessage.class, is); - } - - /** - * 从加密字符串转换 - * - * @param encryptedXml - * @param wxCpConfigStorage - * @param timestamp - * @param nonce - * @param msgSignature - */ - public static WxCpXmlMessage fromEncryptedXml( - String encryptedXml, - WxCpConfigStorage wxCpConfigStorage, - String timestamp, String nonce, String msgSignature) { - WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage); - String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml); - return fromXml(plainText); - } - - public static WxCpXmlMessage fromEncryptedXml( - InputStream is, - WxCpConfigStorage wxCpConfigStorage, - String timestamp, String nonce, String msgSignature) { - try { - return fromEncryptedXml(IOUtils.toString(is, "UTF-8"), wxCpConfigStorage, timestamp, nonce, msgSignature); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - public String getStatus() { return status; } @@ -491,51 +490,51 @@ public void setSendLocationInfo(WxCpXmlMessage.SendLocationInfo sendLocationInfo @Override public String toString() { return "WxCpXmlMessage{" + - "agentId=" + agentId + - ", toUserName='" + toUserName + '\'' + - ", fromUserName='" + fromUserName + '\'' + - ", createTime=" + createTime + - ", msgType='" + msgType + '\'' + - ", content='" + content + '\'' + - ", msgId=" + msgId + - ", picUrl='" + picUrl + '\'' + - ", mediaId='" + mediaId + '\'' + - ", format='" + format + '\'' + - ", thumbMediaId='" + thumbMediaId + '\'' + - ", locationX=" + locationX + - ", locationY=" + locationY + - ", scale=" + scale + - ", label='" + label + '\'' + - ", title='" + title + '\'' + - ", description='" + description + '\'' + - ", url='" + url + '\'' + - ", event='" + event + '\'' + - ", eventKey='" + eventKey + '\'' + - ", ticket='" + ticket + '\'' + - ", latitude=" + latitude + - ", longitude=" + longitude + - ", precision=" + precision + - ", recognition='" + recognition + '\'' + - ", status='" + status + '\'' + - ", totalCount=" + totalCount + - ", filterCount=" + filterCount + - ", sentCount=" + sentCount + - ", errorCount=" + errorCount + - ", scanCodeInfo=" + scanCodeInfo + - ", sendPicsInfo=" + sendPicsInfo + - ", sendLocationInfo=" + sendLocationInfo + - '}'; + "agentId=" + agentId + + ", toUserName='" + toUserName + '\'' + + ", fromUserName='" + fromUserName + '\'' + + ", createTime=" + createTime + + ", msgType='" + msgType + '\'' + + ", content='" + content + '\'' + + ", msgId=" + msgId + + ", picUrl='" + picUrl + '\'' + + ", mediaId='" + mediaId + '\'' + + ", format='" + format + '\'' + + ", thumbMediaId='" + thumbMediaId + '\'' + + ", locationX=" + locationX + + ", locationY=" + locationY + + ", scale=" + scale + + ", label='" + label + '\'' + + ", title='" + title + '\'' + + ", description='" + description + '\'' + + ", url='" + url + '\'' + + ", event='" + event + '\'' + + ", eventKey='" + eventKey + '\'' + + ", ticket='" + ticket + '\'' + + ", latitude=" + latitude + + ", longitude=" + longitude + + ", precision=" + precision + + ", recognition='" + recognition + '\'' + + ", status='" + status + '\'' + + ", totalCount=" + totalCount + + ", filterCount=" + filterCount + + ", sentCount=" + sentCount + + ", errorCount=" + errorCount + + ", scanCodeInfo=" + scanCodeInfo + + ", sendPicsInfo=" + sendPicsInfo + + ", sendLocationInfo=" + sendLocationInfo + + '}'; } @XStreamAlias("ScanCodeInfo") public static class ScanCodeInfo { @XStreamAlias("ScanType") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String scanType; @XStreamAlias("ScanResult") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String scanResult; /** @@ -566,11 +565,10 @@ public void setScanResult(String scanResult) { @XStreamAlias("SendPicsInfo") public static class SendPicsInfo { - @XStreamAlias("Count") - private Long count; - @XStreamAlias("PicList") protected final List picList = new ArrayList(); + @XStreamAlias("Count") + private Long count; public Long getCount() { return count; @@ -588,7 +586,7 @@ public List getPicList() { public static class Item { @XStreamAlias("PicMd5Sum") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String PicMd5Sum; public String getPicMd5Sum() { @@ -605,23 +603,23 @@ public void setPicMd5Sum(String picMd5Sum) { public static class SendLocationInfo { @XStreamAlias("Location_X") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String locationX; @XStreamAlias("Location_Y") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String locationY; @XStreamAlias("Scale") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String scale; @XStreamAlias("Label") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String label; @XStreamAlias("Poiname") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String poiname; public String getLocationX() { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java index 9706a5aa32..1bf4a33f29 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessage.java @@ -7,15 +7,15 @@ @XStreamAlias("xml") public class WxCpXmlOutImageMessage extends WxCpXmlOutMessage { - + @XStreamAlias("Image") - @XStreamConverter(value=XStreamMediaIdConverter.class) + @XStreamConverter(value = XStreamMediaIdConverter.class) private String mediaId; public WxCpXmlOutImageMessage() { this.msgType = WxConsts.XML_MSG_IMAGE; } - + public String getMediaId() { return mediaId; } @@ -23,5 +23,5 @@ public String getMediaId() { public void setMediaId(String mediaId) { this.mediaId = mediaId; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java index eccfbecd39..257778bfbf 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutMessage.java @@ -12,20 +12,55 @@ public abstract class WxCpXmlOutMessage { @XStreamAlias("ToUserName") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) protected String toUserName; @XStreamAlias("FromUserName") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) protected String fromUserName; @XStreamAlias("CreateTime") protected Long createTime; @XStreamAlias("MsgType") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) protected String msgType; + /** + * 获得文本消息builder + */ + public static TextBuilder TEXT() { + return new TextBuilder(); + } + + /** + * 获得图片消息builder + */ + public static ImageBuilder IMAGE() { + return new ImageBuilder(); + } + + /** + * 获得语音消息builder + */ + public static VoiceBuilder VOICE() { + return new VoiceBuilder(); + } + + /** + * 获得视频消息builder + */ + public static VideoBuilder VIDEO() { + return new VideoBuilder(); + } + + /** + * 获得图文消息builder + */ + public static NewsBuilder NEWS() { + return new NewsBuilder(); + } + public String getToUserName() { return toUserName; } @@ -59,7 +94,7 @@ public void setMsgType(String msgType) { } protected String toXml() { - return XStreamTransformer.toXml((Class)this.getClass(), this); + return XStreamTransformer.toXml((Class) this.getClass(), this); } /** @@ -70,39 +105,4 @@ public String toEncryptedXml(WxCpConfigStorage wxCpConfigStorage) { WxCpCryptUtil pc = new WxCpCryptUtil(wxCpConfigStorage); return pc.encrypt(plainXml); } - - /** - * 获得文本消息builder - */ - public static TextBuilder TEXT() { - return new TextBuilder(); - } - - /** - * 获得图片消息builder - */ - public static ImageBuilder IMAGE() { - return new ImageBuilder(); - } - - /** - * 获得语音消息builder - */ - public static VoiceBuilder VOICE() { - return new VoiceBuilder(); - } - - /** - * 获得视频消息builder - */ - public static VideoBuilder VIDEO() { - return new VideoBuilder(); - } - - /** - * 获得图文消息builder - */ - public static NewsBuilder NEWS() { - return new NewsBuilder(); - } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java index 79c35ba947..3b7ae3afb2 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessage.java @@ -11,12 +11,11 @@ @XStreamAlias("xml") public class WxCpXmlOutNewsMessage extends WxCpXmlOutMessage { - @XStreamAlias("ArticleCount") - protected int articleCount; - @XStreamAlias("Articles") protected final List articles = new ArrayList(); - + @XStreamAlias("ArticleCount") + protected int articleCount; + public WxCpXmlOutNewsMessage() { this.msgType = WxConsts.XML_MSG_NEWS; } @@ -29,31 +28,31 @@ public void addArticle(Item item) { this.articles.add(item); this.articleCount = this.articles.size(); } - + public List getArticles() { return articles; } - - + + @XStreamAlias("item") public static class Item { - + @XStreamAlias("Title") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String Title; @XStreamAlias("Description") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String Description; @XStreamAlias("PicUrl") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String PicUrl; - + @XStreamAlias("Url") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String Url; - + public String getTitle() { return Title; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java index f2096ba840..e9dd718306 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessage.java @@ -7,15 +7,15 @@ @XStreamAlias("xml") public class WxCpXmlOutTextMessage extends WxCpXmlOutMessage { - + @XStreamAlias("Content") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String content; public WxCpXmlOutTextMessage() { this.msgType = WxConsts.XML_MSG_TEXT; } - + public String getContent() { return content; } @@ -24,5 +24,5 @@ public void setContent(String content) { this.content = content; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java index 537147b6e1..b5e15801f3 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessage.java @@ -38,21 +38,21 @@ public String getDescription() { public void setDescription(String description) { video.setDescription(description); } - + @XStreamAlias("Video") public static class Video { - + @XStreamAlias("MediaId") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String mediaId; @XStreamAlias("Title") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String title; @XStreamAlias("Description") - @XStreamConverter(value=XStreamCDataConverter.class) + @XStreamConverter(value = XStreamCDataConverter.class) private String description; public String getMediaId() { @@ -78,7 +78,7 @@ public String getDescription() { public void setDescription(String description) { this.description = description; } - + } } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java index 54c53dc6f8..1730a0cf22 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessage.java @@ -7,15 +7,15 @@ @XStreamAlias("xml") public class WxCpXmlOutVoiceMessage extends WxCpXmlOutMessage { - + @XStreamAlias("Voice") - @XStreamConverter(value=XStreamMediaIdConverter.class) + @XStreamConverter(value = XStreamMediaIdConverter.class) private String mediaId; public WxCpXmlOutVoiceMessage() { this.msgType = WxConsts.XML_MSG_VOICE; } - + public String getMediaId() { return mediaId; } @@ -23,5 +23,5 @@ public String getMediaId() { public void setMediaId(String mediaId) { this.mediaId = mediaId; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java index ee075baf78..035777d83b 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/BaseBuilder.java @@ -44,7 +44,7 @@ public WxCpMessage build() { m.setToParty(this.toParty); m.setToTag(this.toTag); m.setSafe( - (this.safe == null || "".equals(this.safe))? WxConsts.CUSTOM_MSG_SAFE_NO: this.safe); + (this.safe == null || "".equals(this.safe)) ? WxConsts.CUSTOM_MSG_SAFE_NO : this.safe); return m; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java index ac15b5eecb..d82954541a 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/FileBuilder.java @@ -8,8 +8,8 @@ *
      * 用法: WxCustomMessage m = WxCustomMessage.FILE().mediaId(...).toUser(...).build();
      * 
    - * @author Daniel Qian * + * @author Daniel Qian */ public final class FileBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java index 5098708a3b..99195c2699 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/ImageBuilder.java @@ -8,8 +8,8 @@ *
      * 用法: WxCustomMessage m = WxCustomMessage.IMAGE().mediaId(...).toUser(...).build();
      * 
    - * @author Daniel Qian * + * @author Daniel Qian */ public final class ImageBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java index 0711b6f523..e2d2086af6 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/NewsBuilder.java @@ -12,13 +12,13 @@ * 用法: * WxCustomMessage m = WxCustomMessage.NEWS().addArticle(article).toUser(...).build(); * - * @author Daniel Qian * + * @author Daniel Qian */ public final class NewsBuilder extends BaseBuilder { private List articles = new ArrayList(); - + public NewsBuilder() { this.msgType = WxConsts.CUSTOM_MSG_NEWS; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java index 44a75b8f0b..076db2f10f 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/TextBuilder.java @@ -8,8 +8,8 @@ *
      * 用法: WxCustomMessage m = WxCustomMessage.TEXT().content(...).toUser(...).build();
      * 
    - * @author Daniel Qian * + * @author Daniel Qian */ public final class TextBuilder extends BaseBuilder { private String content; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java index 32990fa377..66dfc5536a 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VideoBuilder.java @@ -14,8 +14,8 @@ * .toUser(...) * .build(); * - * @author Daniel Qian * + * @author Daniel Qian */ public final class VideoBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java index 99914fcd8e..10b2b0fe00 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/messagebuilder/VoiceBuilder.java @@ -8,8 +8,8 @@ *
      * 用法: WxCustomMessage m = WxCustomMessage.VOICE().mediaId(...).toUser(...).build();
      * 
    - * @author Daniel Qian * + * @author Daniel Qian */ public final class VoiceBuilder extends BaseBuilder { private String mediaId; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/BaseBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/BaseBuilder.java index 78ba107410..03eb8f544a 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/BaseBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/BaseBuilder.java @@ -3,27 +3,27 @@ import me.chanjar.weixin.cp.bean.WxCpXmlOutMessage; public abstract class BaseBuilder { - + protected String toUserName; - + protected String fromUserName; - + public BuilderType toUser(String touser) { this.toUserName = touser; return (BuilderType) this; } - + public BuilderType fromUser(String fromusername) { this.fromUserName = fromusername; return (BuilderType) this; } public abstract ValueType build(); - + public void setCommon(WxCpXmlOutMessage m) { m.setToUserName(this.toUserName); m.setFromUserName(this.fromUserName); m.setCreateTime(System.currentTimeMillis() / 1000l); } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java index ac3b7fc925..ae774e4063 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/ImageBuilder.java @@ -4,6 +4,7 @@ /** * 图片消息builder + * * @author Daniel Qian */ public final class ImageBuilder extends BaseBuilder { @@ -21,5 +22,5 @@ public WxCpXmlOutImageMessage build() { m.setMediaId(this.mediaId); return m; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/NewsBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/NewsBuilder.java index 383904df41..57344ea55e 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/NewsBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/NewsBuilder.java @@ -8,24 +8,25 @@ /** * 图文消息builder + * * @author Daniel Qian */ public final class NewsBuilder extends BaseBuilder { protected final List articles = new ArrayList(); - + public NewsBuilder addArticle(Item item) { this.articles.add(item); return this; } - + public WxCpXmlOutNewsMessage build() { WxCpXmlOutNewsMessage m = new WxCpXmlOutNewsMessage(); - for(Item item : articles) { + for (Item item : articles) { m.addArticle(item); } setCommon(m); return m; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java index 5b1c2ae641..909a0ec932 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/TextBuilder.java @@ -4,8 +4,8 @@ /** * 文本消息builder - * @author Daniel Qian * + * @author Daniel Qian */ public final class TextBuilder extends BaseBuilder { private String content; diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VideoBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VideoBuilder.java index 1bb42ff241..f54b6d110b 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VideoBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VideoBuilder.java @@ -4,8 +4,8 @@ /** * 视频消息builder - * @author Daniel Qian * + * @author Daniel Qian */ public final class VideoBuilder extends BaseBuilder { @@ -17,15 +17,17 @@ public VideoBuilder title(String title) { this.title = title; return this; } + public VideoBuilder description(String description) { this.description = description; return this; } + public VideoBuilder mediaId(String mediaId) { this.mediaId = mediaId; return this; } - + public WxCpXmlOutVideoMessage build() { WxCpXmlOutVideoMessage m = new WxCpXmlOutVideoMessage(); setCommon(m); @@ -34,5 +36,5 @@ public WxCpXmlOutVideoMessage build() { m.setMediaId(mediaId); return m; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VoiceBuilder.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VoiceBuilder.java index fb07525af3..fd5c1f1840 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VoiceBuilder.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/outxmlbuilder/VoiceBuilder.java @@ -4,6 +4,7 @@ /** * 语音消息builder + * * @author Daniel Qian */ public final class VoiceBuilder extends BaseBuilder { @@ -14,12 +15,12 @@ public VoiceBuilder mediaId(String mediaId) { this.mediaId = mediaId; return this; } - + public WxCpXmlOutVoiceMessage build() { WxCpXmlOutVoiceMessage m = new WxCpXmlOutVoiceMessage(); setCommon(m); m.setMediaId(mediaId); return m; } - + } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java index d2d01c09bf..104b124377 100755 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpCryptUtil.java @@ -2,6 +2,10 @@ * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. + *

    + * 针对org.apache.commons.codec.binary.Base64, + * 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) + * 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi */ // ------------------------------------------------------------------------ diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java index 723d50dbf9..c6cb1ad728 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpDepartGsonAdapter.java @@ -37,7 +37,7 @@ public JsonElement serialize(WxCpDepart group, Type typeOfSrc, JsonSerialization } public WxCpDepart deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { WxCpDepart depart = new WxCpDepart(); JsonObject departJson = json.getAsJsonObject(); if (departJson.get("id") != null && !departJson.get("id").isJsonNull()) { diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java index 9c262a3157..45df80b353 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpMessageGsonAdapter.java @@ -16,9 +16,7 @@ import java.lang.reflect.Type; /** - * * @author Daniel Qian - * */ public class WxCpMessageGsonAdapter implements JsonSerializer { @@ -83,7 +81,7 @@ public JsonElement serialize(WxCpMessage message, Type typeOfSrc, JsonSerializat newsJsonObject.add("articles", articleJsonArray); messageJson.add("news", newsJsonObject); } - + return messageJson; } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java index 1b7a28347c..b8599a1cb4 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpTagGsonAdapter.java @@ -27,7 +27,7 @@ public JsonElement serialize(WxCpTag tag, Type typeOfSrc, JsonSerializationConte } public WxCpTag deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); return new WxCpTag(GsonHelper.getString(jsonObject, "tagid"), GsonHelper.getString(jsonObject, "tagname")); } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java index 0984644b49..7a88f47e91 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/json/WxCpUserGsonAdapter.java @@ -20,13 +20,13 @@ public class WxCpUserGsonAdapter implements JsonDeserializer, JsonSerializer { public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) - throws JsonParseException { + throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxCpUser user = new WxCpUser(); user.setUserId(GsonHelper.getString(o, "userid")); user.setName(GsonHelper.getString(o, "name")); - if(o.get("department") != null) { + if (o.get("department") != null) { JsonArray departJsonArray = o.get("department").getAsJsonArray(); Integer[] departIds = new Integer[departJsonArray.size()]; int i = 0; @@ -49,8 +49,8 @@ public WxCpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationC JsonArray attrJsonElements = o.get("extattr").getAsJsonObject().get("attrs").getAsJsonArray(); for (JsonElement attrJsonElement : attrJsonElements) { WxCpUser.Attr attr = new WxCpUser.Attr( - GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"), - GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value") + GsonHelper.getString(attrJsonElement.getAsJsonObject(), "name"), + GsonHelper.getString(attrJsonElement.getAsJsonObject(), "value") ); user.getExtAttrs().add(attr); } diff --git a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java index 9bcd5edacb..ae46d8f284 100644 --- a/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java +++ b/weixin-java-cp/src/main/java/me/chanjar/weixin/cp/util/xml/XStreamTransformer.java @@ -29,16 +29,16 @@ public static T fromXml(Class clazz, InputStream is) { /** * 注册扩展消息的解析器 - * @param clz 类型 + * + * @param clz 类型 * @param xStream xml解析器 - */ - public static void register(Class clz,XStream xStream){ - CLASS_2_XSTREAM_INSTANCE.put(clz,xStream); + */ + public static void register(Class clz, XStream xStream) { + CLASS_2_XSTREAM_INSTANCE.put(clz, xStream); } /** * pojo -> xml - * */ public static String toXml(Class clazz, T object) { return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java index bb3690bc97..5235486b04 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/ApiTestModule.java @@ -10,17 +10,6 @@ public class ApiTestModule implements Module { - @Override - public void configure(Binder binder) { - InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml"); - WxXmlCpInMemoryConfigStorage config = fromXml(WxXmlCpInMemoryConfigStorage.class, is1); - WxCpServiceImpl wxService = new WxCpServiceImpl(); - wxService.setWxCpConfigStorage(config); - - binder.bind(WxCpServiceImpl.class).toInstance(wxService); - binder.bind(WxCpConfigStorage.class).toInstance(config); - } - public static T fromXml(Class clazz, InputStream is) { XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", clazz); @@ -28,9 +17,20 @@ public static T fromXml(Class clazz, InputStream is) { return (T) xstream.fromXML(is); } + @Override + public void configure(Binder binder) { + InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml"); + WxXmlCpInMemoryConfigStorage config = fromXml(WxXmlCpInMemoryConfigStorage.class, is1); + WxCpServiceImpl wxService = new WxCpServiceImpl(); + wxService.setWxCpConfigStorage(config); + + binder.bind(WxCpServiceImpl.class).toInstance(wxService); + binder.bind(WxCpConfigStorage.class).toInstance(config); + } + @XStreamAlias("xml") public static class WxXmlCpInMemoryConfigStorage extends WxCpInMemoryConfigStorage { - + protected String userId; protected String departmentId; @@ -40,6 +40,7 @@ public static class WxXmlCpInMemoryConfigStorage extends WxCpInMemoryConfigStora public String getUserId() { return userId; } + public void setUserId(String userId) { this.userId = userId; } @@ -63,11 +64,11 @@ public void setTagId(String tagId) { @Override public String toString() { return super.toString() + " > WxXmlCpConfigStorage{" + - "userId='" + userId + '\'' + - ", departmentId='" + departmentId + '\'' + - ", tagId='" + tagId + '\'' + - '}'; + "userId='" + userId + '\'' + + ", departmentId='" + departmentId + '\'' + + ", tagId='" + tagId + '\'' + + '}'; } } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java index d8757f340e..9f2b60f818 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBaseAPITest.java @@ -9,8 +9,8 @@ /** * 基础API测试 - * @author Daniel Qian * + * @author Daniel Qian */ @Test(groups = "baseAPI") @Guice(modules = ApiTestModule.class) diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java index cf129088ff..989a69e6b2 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpBusyRetryTest.java @@ -14,7 +14,7 @@ @Test public class WxCpBusyRetryTest { - @DataProvider(name="getService") + @DataProvider(name = "getService") public Object[][] getService() { WxCpService service = new WxCpServiceImpl() { @@ -28,8 +28,8 @@ protected T executeInternal(RequestExecutor executor, String uri, E service.setMaxRetryTimes(3); service.setRetrySleepMillis(500); - return new Object[][] { - new Object[] { service } + return new Object[][]{ + new Object[]{service} }; } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java index 28779e655a..cb8db0d57f 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpDepartAPITest.java @@ -44,7 +44,7 @@ public void testDepartGet() throws WxErrorException { } } - @Test(dependsOnMethods = { "testDepartGet", "testDepartCreate" }) + @Test(dependsOnMethods = {"testDepartGet", "testDepartCreate"}) public void testDepartUpdate() throws WxErrorException { System.out.println("=================更新部门"); depart.setName("子部门改名" + System.currentTimeMillis()); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java index c67acab1c5..e880ad078d 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMediaAPITest.java @@ -16,8 +16,8 @@ /** * 测试多媒体文件上传下载 - * @author Daniel Qian * + * @author Daniel Qian */ //@Test(groups="mediaAPI", dependsOnGroups="baseAPI") @Test @@ -28,15 +28,15 @@ public class WxCpMediaAPITest { protected WxCpServiceImpl wxService; private List media_ids = new ArrayList(); - - @Test(dataProvider="uploadMedia") + + @Test(dataProvider = "uploadMedia") public void testUploadMedia(String mediaType, String fileType, String fileName) throws WxErrorException, IOException { InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName); WxMediaUploadResult res = wxService.mediaUpload(mediaType, fileType, inputStream); Assert.assertNotNull(res.getType()); Assert.assertNotNull(res.getCreatedAt()); Assert.assertTrue(res.getMediaId() != null || res.getThumbMediaId() != null); - + if (res.getMediaId() != null) { media_ids.add(res.getMediaId()); } @@ -44,29 +44,29 @@ public void testUploadMedia(String mediaType, String fileType, String fileName) media_ids.add(res.getThumbMediaId()); } } - + @DataProvider public Object[][] uploadMedia() { - return new Object[][] { - new Object[] { WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, "mm.jpeg" }, - new Object[] { WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, "mm.mp3" }, - new Object[] { WxConsts.MEDIA_VIDEO, WxConsts.FILE_MP4, "mm.mp4" }, - new Object[] { WxConsts.MEDIA_FILE, WxConsts.FILE_JPG, "mm.jpeg" } + return new Object[][]{ + new Object[]{WxConsts.MEDIA_IMAGE, WxConsts.FILE_JPG, "mm.jpeg"}, + new Object[]{WxConsts.MEDIA_VOICE, WxConsts.FILE_MP3, "mm.mp3"}, + new Object[]{WxConsts.MEDIA_VIDEO, WxConsts.FILE_MP4, "mm.mp4"}, + new Object[]{WxConsts.MEDIA_FILE, WxConsts.FILE_JPG, "mm.jpeg"} }; } - - @Test(dependsOnMethods = { "testUploadMedia" }, dataProvider="downloadMedia") + + @Test(dependsOnMethods = {"testUploadMedia"}, dataProvider = "downloadMedia") public void testDownloadMedia(String media_id) throws WxErrorException { wxService.mediaDownload(media_id); } - + @DataProvider public Object[][] downloadMedia() { Object[][] params = new Object[this.media_ids.size()][]; for (int i = 0; i < this.media_ids.size(); i++) { - params[i] = new Object[] { this.media_ids.get(i) }; + params[i] = new Object[]{this.media_ids.get(i)}; } return params; } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java index ee16f56f8e..9810435ead 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageAPITest.java @@ -12,7 +12,7 @@ * @author Daniel Qian * */ -@Test(groups="customMessageAPI", dependsOnGroups = "baseAPI") +@Test(groups = "customMessageAPI", dependsOnGroups = "baseAPI") @Guice(modules = ApiTestModule.class) public class WxCpMessageAPITest { @@ -29,11 +29,11 @@ public void testSendCustomMessage() throws WxErrorException { wxService.messageSend(message1); WxCpMessage message2 = WxCpMessage - .TEXT() - .agentId(configStorage.getAgentId()) - .toUser(configStorage.getUserId()) - .content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World") - .build(); + .TEXT() + .agentId(configStorage.getAgentId()) + .toUser(configStorage.getUserId()) + .content("欢迎欢迎,热烈欢迎\n换行测试\n超链接:Hello World") + .build(); wxService.messageSend(message2); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java index ccf981dd0f..a5e40968c4 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpMessageRouterTest.java @@ -13,45 +13,45 @@ /** * 测试消息路由器 - * @author Daniel Qian * + * @author Daniel Qian */ @Test public class WxCpMessageRouterTest { - + @Test(enabled = false) public void prepare(boolean async, StringBuffer sb, WxCpMessageRouter router) { router - .rule() - .async(async) - .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1").content("CONTENT_1") - .handler(new WxEchoCpMessageHandler(sb, "COMBINE_4")) - .end() - .rule() - .async(async) - .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1") - .handler(new WxEchoCpMessageHandler(sb, "COMBINE_3")) - .end() - .rule() - .async(async) - .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK) - .handler(new WxEchoCpMessageHandler(sb, "COMBINE_2")) - .end() - .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).handler(new WxEchoCpMessageHandler(sb, WxConsts.XML_MSG_TEXT)).end() - .rule().async(async).event(WxConsts.EVT_CLICK).handler(new WxEchoCpMessageHandler(sb, WxConsts.EVT_CLICK)).end() - .rule().async(async).eventKey("KEY_1").handler(new WxEchoCpMessageHandler(sb, "KEY_1")).end() - .rule().async(async).content("CONTENT_1").handler(new WxEchoCpMessageHandler(sb, "CONTENT_1")).end() - .rule().async(async).rContent(".*bc.*").handler(new WxEchoCpMessageHandler(sb, "abcd")).end() - .rule().async(async).matcher(new WxCpMessageMatcher() { - @Override - public boolean match(WxCpXmlMessage message) { - return "strangeformat".equals(message.getFormat()); - } - }).handler(new WxEchoCpMessageHandler(sb, "matcher")).end() - .rule().async(async).handler(new WxEchoCpMessageHandler(sb, "ALL")).end(); + .rule() + .async(async) + .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1").content("CONTENT_1") + .handler(new WxEchoCpMessageHandler(sb, "COMBINE_4")) + .end() + .rule() + .async(async) + .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK).eventKey("KEY_1") + .handler(new WxEchoCpMessageHandler(sb, "COMBINE_3")) + .end() + .rule() + .async(async) + .msgType(WxConsts.XML_MSG_TEXT).event(WxConsts.EVT_CLICK) + .handler(new WxEchoCpMessageHandler(sb, "COMBINE_2")) + .end() + .rule().async(async).msgType(WxConsts.XML_MSG_TEXT).handler(new WxEchoCpMessageHandler(sb, WxConsts.XML_MSG_TEXT)).end() + .rule().async(async).event(WxConsts.EVT_CLICK).handler(new WxEchoCpMessageHandler(sb, WxConsts.EVT_CLICK)).end() + .rule().async(async).eventKey("KEY_1").handler(new WxEchoCpMessageHandler(sb, "KEY_1")).end() + .rule().async(async).content("CONTENT_1").handler(new WxEchoCpMessageHandler(sb, "CONTENT_1")).end() + .rule().async(async).rContent(".*bc.*").handler(new WxEchoCpMessageHandler(sb, "abcd")).end() + .rule().async(async).matcher(new WxCpMessageMatcher() { + @Override + public boolean match(WxCpXmlMessage message) { + return "strangeformat".equals(message.getFormat()); + } + }).handler(new WxEchoCpMessageHandler(sb, "matcher")).end() + .rule().async(async).handler(new WxEchoCpMessageHandler(sb, "ALL")).end(); } - - @Test(dataProvider="messages-1") + + @Test(dataProvider = "messages-1") public void testSync(WxCpXmlMessage message, String expected) { StringBuffer sb = new StringBuffer(); WxCpMessageRouter router = new WxCpMessageRouter(null); @@ -59,27 +59,27 @@ public void testSync(WxCpXmlMessage message, String expected) { router.route(message); Assert.assertEquals(sb.toString(), expected); } - - @Test(dataProvider="messages-1") + + @Test(dataProvider = "messages-1") public void testAsync(WxCpXmlMessage message, String expected) throws InterruptedException { StringBuffer sb = new StringBuffer(); WxCpMessageRouter router = new WxCpMessageRouter(null); - prepare(true, sb, router); + prepare(true, sb, router); router.route(message); Thread.sleep(500l); Assert.assertEquals(sb.toString(), expected); } - + public void testConcurrency() throws InterruptedException { final WxCpMessageRouter router = new WxCpMessageRouter(null); router.rule().handler(new WxCpMessageHandler() { @Override public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, WxCpService wxCpService, - WxSessionManager sessionManager) { + WxSessionManager sessionManager) { return null; } }).end(); - + final WxCpXmlMessage m = new WxCpXmlMessage(); Runnable r = new Runnable() { @Override @@ -94,27 +94,27 @@ public void run() { for (int i = 0; i < 10; i++) { new Thread(r).start(); } - + Thread.sleep(1000l * 2); } - @DataProvider(name="messages-1") + @DataProvider(name = "messages-1") public Object[][] messages2() { WxCpXmlMessage message1 = new WxCpXmlMessage(); message1.setMsgType(WxConsts.XML_MSG_TEXT); - + WxCpXmlMessage message2 = new WxCpXmlMessage(); message2.setEvent(WxConsts.EVT_CLICK); - + WxCpXmlMessage message3 = new WxCpXmlMessage(); message3.setEventKey("KEY_1"); - + WxCpXmlMessage message4 = new WxCpXmlMessage(); message4.setContent("CONTENT_1"); - + WxCpXmlMessage message5 = new WxCpXmlMessage(); message5.setContent("BLA"); - + WxCpXmlMessage message6 = new WxCpXmlMessage(); message6.setContent("abcd"); @@ -124,12 +124,12 @@ public Object[][] messages2() { WxCpXmlMessage c2 = new WxCpXmlMessage(); c2.setMsgType(WxConsts.XML_MSG_TEXT); c2.setEvent(WxConsts.EVT_CLICK); - + WxCpXmlMessage c3 = new WxCpXmlMessage(); c3.setMsgType(WxConsts.XML_MSG_TEXT); c3.setEvent(WxConsts.EVT_CLICK); c3.setEventKey("KEY_1"); - + WxCpXmlMessage c4 = new WxCpXmlMessage(); c4.setMsgType(WxConsts.XML_MSG_TEXT); c4.setEvent(WxConsts.EVT_CLICK); @@ -137,37 +137,18 @@ public Object[][] messages2() { c4.setContent("CONTENT_1"); - return new Object[][] { - new Object[] { message1, WxConsts.XML_MSG_TEXT + "," }, - new Object[] { message2, WxConsts.EVT_CLICK + "," }, - new Object[] { message3, "KEY_1," }, - new Object[] { message4, "CONTENT_1," }, - new Object[] { message5, "ALL," }, - new Object[] { message6, "abcd," }, - new Object[] { message7, "matcher," }, - new Object[] { c2, "COMBINE_2," }, - new Object[] { c3, "COMBINE_3," }, - new Object[] { c4, "COMBINE_4," } + return new Object[][]{ + new Object[]{message1, WxConsts.XML_MSG_TEXT + ","}, + new Object[]{message2, WxConsts.EVT_CLICK + ","}, + new Object[]{message3, "KEY_1,"}, + new Object[]{message4, "CONTENT_1,"}, + new Object[]{message5, "ALL,"}, + new Object[]{message6, "abcd,"}, + new Object[]{message7, "matcher,"}, + new Object[]{c2, "COMBINE_2,"}, + new Object[]{c3, "COMBINE_3,"}, + new Object[]{c4, "COMBINE_4,"} }; - - } - - public static class WxEchoCpMessageHandler implements WxCpMessageHandler { - - private StringBuffer sb; - private String echoStr; - - public WxEchoCpMessageHandler(StringBuffer sb, String echoStr) { - this.sb = sb; - this.echoStr = echoStr; - } - - @Override - public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, WxCpService wxCpService, - WxSessionManager sessionManager) { - sb.append(this.echoStr).append(','); - return null; - } } @@ -180,8 +161,8 @@ public Object[][] standardSessionManager() { ism.setProcessExpiresFrequency(1); ism.setBackgroundProcessorDelay(1); - return new Object[][] { - new Object[] { ism } + return new Object[][]{ + new Object[]{ism} }; } @@ -193,8 +174,8 @@ public void testSessionClean1(StandardSessionManager ism) throws InterruptedExce final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(false).handler(new WxSessionMessageHandler()).next() - .rule().async(false).handler(new WxSessionMessageHandler()).end(); + .rule().async(false).handler(new WxSessionMessageHandler()).next() + .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -213,8 +194,8 @@ public void testSessionClean2(StandardSessionManager ism) throws InterruptedExce final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(false).handler(new WxSessionMessageHandler()).next() - .rule().async(true).handler(new WxSessionMessageHandler()).end(); + .rule().async(false).handler(new WxSessionMessageHandler()).next() + .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -227,8 +208,8 @@ public void testSessionClean2(StandardSessionManager ism) throws InterruptedExce final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(true).handler(new WxSessionMessageHandler()).next() - .rule().async(false).handler(new WxSessionMessageHandler()).end(); + .rule().async(true).handler(new WxSessionMessageHandler()).next() + .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -247,8 +228,8 @@ public void testSessionClean3(StandardSessionManager ism) throws InterruptedExce final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(true).handler(new WxSessionMessageHandler()).next() - .rule().async(true).handler(new WxSessionMessageHandler()).end(); + .rule().async(true).handler(new WxSessionMessageHandler()).next() + .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -267,7 +248,7 @@ public void testSessionClean4(StandardSessionManager ism) throws InterruptedExce final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(false).handler(new WxSessionMessageHandler()).end(); + .rule().async(false).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -281,7 +262,7 @@ public void testSessionClean4(StandardSessionManager ism) throws InterruptedExce final WxCpMessageRouter router = new WxCpMessageRouter(null); router.setSessionManager(ism); router - .rule().async(true).handler(new WxSessionMessageHandler()).end(); + .rule().async(true).handler(new WxSessionMessageHandler()).end(); WxCpXmlMessage msg = new WxCpXmlMessage(); msg.setFromUserName("abc"); @@ -292,11 +273,30 @@ public void testSessionClean4(StandardSessionManager ism) throws InterruptedExce } } - public static class WxSessionMessageHandler implements WxCpMessageHandler { + public static class WxEchoCpMessageHandler implements WxCpMessageHandler { + + private StringBuffer sb; + private String echoStr; + + public WxEchoCpMessageHandler(StringBuffer sb, String echoStr) { + this.sb = sb; + this.echoStr = echoStr; + } + + @Override + public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, WxCpService wxCpService, + WxSessionManager sessionManager) { + sb.append(this.echoStr).append(','); + return null; + } + + } + + public static class WxSessionMessageHandler implements WxCpMessageHandler { @Override public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, WxCpService wxCpService, - WxSessionManager sessionManager) { + WxSessionManager sessionManager) { sessionManager.getSession(wxMessage.getFromUserName()); return null; } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java index b101eeb660..130b072227 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpTagAPITest.java @@ -41,7 +41,7 @@ public void testTagGet() throws Exception { @Test(dependsOnMethods = "testTagGet") public void testTagAddUsers() throws Exception { List userIds = new ArrayList(); - userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage)configStorage).getUserId()); + userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage) configStorage).getUserId()); wxService.tagAddUsers(tagId, userIds, null); } @@ -54,7 +54,7 @@ public void testTagGetUsers() throws Exception { @Test(dependsOnMethods = "testTagGetUsers") public void testTagRemoveUsers() throws Exception { List userIds = new ArrayList(); - userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage)configStorage).getUserId()); + userIds.add(((ApiTestModule.WxXmlCpInMemoryConfigStorage) configStorage).getUserId()); wxService.tagRemoveUsers(tagId, userIds); } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java index c444eec5f4..8c5d2064ed 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxCpUserAPITest.java @@ -28,7 +28,7 @@ public void testUserCreate() throws WxErrorException { WxCpUser user = new WxCpUser(); user.setUserId("some.woman"); user.setName("Some Woman"); - user.setDepartIds(new Integer[] { 9, 8 }); + user.setDepartIds(new Integer[]{9, 8}); user.setEmail("none@none.com"); user.setGender("女"); user.setMobile("13560084979"); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java index ca5b59916b..8fe136b93f 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/WxMenuAPITest.java @@ -2,8 +2,8 @@ import com.google.inject.Inject; import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.common.bean.WxMenu; -import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton; +import me.chanjar.weixin.common.bean.menu.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenuButton; import me.chanjar.weixin.common.exception.WxErrorException; import org.testng.Assert; import org.testng.annotations.DataProvider; @@ -12,77 +12,77 @@ /** * 测试菜单 - * @author Daniel Qian * + * @author Daniel Qian */ -@Test(groups="menuAPI", dependsOnGroups="baseAPI") +@Test(groups = "menuAPI", dependsOnGroups = "baseAPI") @Guice(modules = ApiTestModule.class) public class WxMenuAPITest { @Inject protected WxCpServiceImpl wxService; - + @Test(dataProvider = "menu") public void testCreateMenu(WxMenu wxMenu) throws WxErrorException { wxService.menuCreate(wxMenu); } - - @Test(dependsOnMethods = { "testCreateMenu"}) + + @Test(dependsOnMethods = {"testCreateMenu"}) public void testGetMenu() throws WxErrorException { Assert.assertNotNull(wxService.menuGet()); } - - @Test(dependsOnMethods = { "testGetMenu"}) + + @Test(dependsOnMethods = {"testGetMenu"}) public void testDeleteMenu() throws WxErrorException { wxService.menuDelete(); } - - @DataProvider(name="menu") + + @DataProvider(name = "menu") public Object[][] getMenu() { WxMenu menu = new WxMenu(); WxMenuButton button1 = new WxMenuButton(); button1.setType(WxConsts.BUTTON_CLICK); button1.setName("今日歌曲"); button1.setKey("V1001_TODAY_MUSIC"); - + WxMenuButton button2 = new WxMenuButton(); button2.setType(WxConsts.BUTTON_CLICK); button2.setName("歌手简介"); button2.setKey("V1001_TODAY_SINGER"); - + WxMenuButton button3 = new WxMenuButton(); button3.setName("菜单"); - + menu.getButtons().add(button1); menu.getButtons().add(button2); menu.getButtons().add(button3); - + WxMenuButton button31 = new WxMenuButton(); button31.setType(WxConsts.BUTTON_VIEW); button31.setName("搜索"); button31.setUrl("http://www.soso.com/"); - + WxMenuButton button32 = new WxMenuButton(); button32.setType(WxConsts.BUTTON_VIEW); button32.setName("视频"); button32.setUrl("http://v.qq.com/"); - + WxMenuButton button33 = new WxMenuButton(); button33.setType(WxConsts.BUTTON_CLICK); button33.setName("赞一下我们"); button33.setKey("V1001_GOOD"); - + button3.getSubButtons().add(button31); button3.getSubButtons().add(button32); button3.getSubButtons().add(button33); - - return new Object[][] { - new Object[] { - menu - } + + return new Object[][]{ + new Object[]{ + menu + } }; - + } - - + + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java index f9dbe6574b..12b62e34b9 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpMessageTest.java @@ -15,12 +15,12 @@ public void testTextReply() { reply.setContent("sfsfdsdf"); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"sfsfdsdf\"}}"); } - + public void testTextBuild() { WxCpMessage reply = WxCpMessage.TEXT().toUser("OPENID").content("sfsfdsdf").build(); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"text\",\"text\":{\"content\":\"sfsfdsdf\"}}"); } - + public void testImageReply() { WxCpMessage reply = new WxCpMessage(); reply.setToUser("OPENID"); @@ -28,12 +28,12 @@ public void testImageReply() { reply.setMediaId("MEDIA_ID"); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"MEDIA_ID\"}}"); } - + public void testImageBuild() { WxCpMessage reply = WxCpMessage.IMAGE().toUser("OPENID").mediaId("MEDIA_ID").build(); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"image\",\"image\":{\"media_id\":\"MEDIA_ID\"}}"); } - + public void testVoiceReply() { WxCpMessage reply = new WxCpMessage(); reply.setToUser("OPENID"); @@ -41,12 +41,12 @@ public void testVoiceReply() { reply.setMediaId("MEDIA_ID"); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"MEDIA_ID\"}}"); } - + public void testVoiceBuild() { WxCpMessage reply = WxCpMessage.VOICE().toUser("OPENID").mediaId("MEDIA_ID").build(); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"voice\",\"voice\":{\"media_id\":\"MEDIA_ID\"}}"); } - + public void testVideoReply() { WxCpMessage reply = new WxCpMessage(); reply.setToUser("OPENID"); @@ -57,24 +57,24 @@ public void testVideoReply() { reply.setDescription("DESCRIPTION"); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"MEDIA_ID\",\"thumb_media_id\":\"MEDIA_ID\",\"title\":\"TITLE\",\"description\":\"DESCRIPTION\"}}"); } - + public void testVideoBuild() { WxCpMessage reply = WxCpMessage.VIDEO().toUser("OPENID").title("TITLE").mediaId("MEDIA_ID").thumbMediaId("MEDIA_ID").description("DESCRIPTION").build(); Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"video\",\"video\":{\"media_id\":\"MEDIA_ID\",\"thumb_media_id\":\"MEDIA_ID\",\"title\":\"TITLE\",\"description\":\"DESCRIPTION\"}}"); } - + public void testNewsReply() { WxCpMessage reply = new WxCpMessage(); reply.setToUser("OPENID"); reply.setMsgType(WxConsts.CUSTOM_MSG_NEWS); - + WxArticle article1 = new WxArticle(); article1.setUrl("URL"); article1.setPicUrl("PIC_URL"); article1.setDescription("Is Really A Happy Day"); article1.setTitle("Happy Day"); reply.getArticles().add(article1); - + WxArticle article2 = new WxArticle(); article2.setUrl("URL"); article2.setPicUrl("PIC_URL"); @@ -85,14 +85,14 @@ public void testNewsReply() { Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"news\",\"news\":{\"articles\":[{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"},{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"}]}}"); } - + public void testNewsBuild() { WxArticle article1 = new WxArticle(); article1.setUrl("URL"); article1.setPicUrl("PIC_URL"); article1.setDescription("Is Really A Happy Day"); article1.setTitle("Happy Day"); - + WxArticle article2 = new WxArticle(); article2.setUrl("URL"); article2.setPicUrl("PIC_URL"); @@ -103,5 +103,5 @@ public void testNewsBuild() { Assert.assertEquals(reply.toJson(), "{\"touser\":\"OPENID\",\"msgtype\":\"news\",\"news\":{\"articles\":[{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"},{\"title\":\"Happy Day\",\"description\":\"Is Really A Happy Day\",\"url\":\"URL\",\"picurl\":\"PIC_URL\"}]}}"); } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java index b4b75c9c37..270fa1d349 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlMessageTest.java @@ -10,49 +10,49 @@ public class WxCpXmlMessageTest { public void testFromXml() { String xml = "" - + "" - + " " - + "1348831860" - + "" - + "" - + "1234567890123456" - + "" - + "" - + "" - + "" - + "23.134521" - + "113.358803" - + "20" - + "" - + "" - + "" - + "<![CDATA[公众平台官网链接]]>" - + "" - + "" - + "" - + "23.137466" - + "113.352425" - + "119.385040" - + "" - + " " - + " " - + "" - + "" - + " 1\n" - + " " - + " " - + " " - + " " - + " " - + "" - + "" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + "" - + ""; + + "" + + " " + + "1348831860" + + "" + + "" + + "1234567890123456" + + "" + + "" + + "" + + "" + + "23.134521" + + "113.358803" + + "20" + + "" + + "" + + "" + + "<![CDATA[公众平台官网链接]]>" + + "" + + "" + + "" + + "23.137466" + + "113.352425" + + "119.385040" + + "" + + " " + + " " + + "" + + "" + + " 1\n" + + " " + + " " + + " " + + " " + + " " + + "" + + "" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + ""; WxCpXmlMessage wxMessage = WxCpXmlMessage.fromXml(xml); Assert.assertEquals(wxMessage.getToUserName(), "toUser"); Assert.assertEquals(wxMessage.getFromUserName(), "fromUser"); @@ -87,5 +87,5 @@ public void testFromXml() { Assert.assertEquals(wxMessage.getSendLocationInfo().getLabel(), " 广州市海珠区客村艺苑路 106号"); Assert.assertEquals(wxMessage.getSendLocationInfo().getPoiname(), "wo de poi"); } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java index aef4ec4546..8ace5d0aae 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutImageMessageTest.java @@ -12,37 +12,37 @@ public void test() { m.setCreateTime(1122l); m.setFromUserName("from"); m.setToUserName("to"); - + String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } - + public void testBuild() { WxCpXmlOutImageMessage m = WxCpXmlOutMessage.IMAGE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build(); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") - ); - + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") + ); + } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java index 7848bfcd45..bd66743c71 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutNewsMessageTest.java @@ -11,7 +11,7 @@ public void test() { m.setCreateTime(1122l); m.setFromUserName("fromUser"); m.setToUserName("toUser"); - + WxCpXmlOutNewsMessage.Item item = new WxCpXmlOutNewsMessage.Item(); item.setDescription("description"); item.setPicUrl("picUrl"); @@ -20,74 +20,74 @@ public void test() { m.addArticle(item); m.addArticle(item); String expected = "" - + "" - + "" - + "1122" - + "" - + " 2" - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + ""; + + "" + + "" + + "1122" + + "" + + " 2" + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } - + public void testBuild() { WxCpXmlOutNewsMessage.Item item = new WxCpXmlOutNewsMessage.Item(); item.setDescription("description"); item.setPicUrl("picUrl"); item.setTitle("title"); item.setUrl("url"); - + WxCpXmlOutNewsMessage m = WxCpXmlOutMessage.NEWS() - .fromUser("fromUser") - .toUser("toUser") - .addArticle(item) - .addArticle(item) - .build(); + .fromUser("fromUser") + .toUser("toUser") + .addArticle(item) + .addArticle(item) + .build(); String expected = "" - + "" - + "" - + "1122" - + "" - + " 2" - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + " <![CDATA[title]]>" - + " " - + " " - + " " - + " " - + " " - + ""; + + "" + + "" + + "1122" + + "" + + " 2" + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + " <![CDATA[title]]>" + + " " + + " " + + " " + + " " + + " " + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") - ); + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") + ); } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java index 75343cb444..57fcf8eb98 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutTextMessageTest.java @@ -12,39 +12,39 @@ public void test() { m.setCreateTime(1122l); m.setFromUserName("from"); m.setToUserName("to"); - + String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } - + public void testBuild() { WxCpXmlOutTextMessage m = WxCpXmlOutMessage.TEXT().content("content").fromUser("from").toUser("to").build(); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") - ); - + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") + ); + } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java index 61e1cbfb88..512dfef3b7 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVideoMessageTest.java @@ -14,51 +14,51 @@ public void test() { m.setCreateTime(1122l); m.setFromUserName("fromUser"); m.setToUserName("toUser"); - + String expected = "" - + "" - + "" - + "1122" - + "" - + " " - + ""; + + "" + + "" + + "1122" + + "" + + " " + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } - + public void testBuild() { WxCpXmlOutVideoMessage m = WxCpXmlOutMessage.VIDEO() - .mediaId("media_id") - .fromUser("fromUser") - .toUser("toUser") - .title("title") - .description("ddfff") - .build(); + .mediaId("media_id") + .fromUser("fromUser") + .toUser("toUser") + .title("title") + .description("ddfff") + .build(); String expected = "" - + "" - + "" - + "1122" - + "" - + " " - + ""; + + "" + + "" + + "1122" + + "" + + " " + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") - ); + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") + ); } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java index 897f5c3765..26db29c3c3 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/bean/WxCpXmlOutVoiceMessageTest.java @@ -12,37 +12,37 @@ public void test() { m.setCreateTime(1122l); m.setFromUserName("from"); m.setToUserName("to"); - + String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals(m.toXml().replaceAll("\\s", ""), expected.replaceAll("\\s", "")); } - + public void testBuild() { WxCpXmlOutVoiceMessage m = WxCpXmlOutMessage.VOICE().mediaId("ddfefesfsdfef").fromUser("from").toUser("to").build(); String expected = "" - + "" - + "" - + "1122" - + "" - + "" - + ""; + + "" + + "" + + "1122" + + "" + + "" + + ""; System.out.println(m.toXml()); Assert.assertEquals( - m - .toXml() - .replaceAll("\\s", "") - .replaceAll(".*?", ""), - expected - .replaceAll("\\s", "") - .replaceAll(".*?", "") - ); + m + .toXml() + .replaceAll("\\s", "") + .replaceAll(".*?", ""), + expected + .replaceAll("\\s", "") + .replaceAll(".*?", "") + ); } - + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java index 5221986833..f883e31120 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java @@ -13,17 +13,16 @@ @XStreamAlias("xml") class WxCpDemoInMemoryConfigStorage extends WxCpInMemoryConfigStorage { - @Override - public String toString() { - return "SimpleWxConfigProvider [appidOrCorpid=" + corpId + ", corpSecret=" + corpSecret + ", accessToken=" + accessToken - + ", expiresTime=" + expiresTime + ", token=" + token + ", aesKey=" + aesKey + "]"; - } - - public static WxCpDemoInMemoryConfigStorage fromXml(InputStream is) { XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxCpDemoInMemoryConfigStorage.class); return (WxCpDemoInMemoryConfigStorage) xstream.fromXML(is); } + @Override + public String toString() { + return "SimpleWxConfigProvider [appidOrCorpid=" + corpId + ", corpSecret=" + corpSecret + ", accessToken=" + accessToken + + ", expiresTime=" + expiresTime + ", token=" + token + ", aesKey=" + aesKey + "]"; + } + } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java index 3d80894559..10af3c575e 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoServer.java @@ -37,54 +37,54 @@ public static void main(String[] args) throws Exception { } private static void initWeixin() { - InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml"); - WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(is1); - - wxCpConfigStorage = config; - wxCpService = new WxCpServiceImpl(); - wxCpService.setWxCpConfigStorage(config); - - WxCpMessageHandler handler = new WxCpMessageHandler() { - @Override - public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, - WxCpService wxCpService, WxSessionManager sessionManager) { - WxCpXmlOutTextMessage m = WxCpXmlOutMessage - .TEXT() - .content("测试加密消息") - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()) - .build(); - return m; - } - }; - - WxCpMessageHandler oauth2handler = new WxCpMessageHandler() { - @Override - public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, - WxCpService wxCpService, WxSessionManager sessionManager) { - String href = "测试oauth2"; - return WxCpXmlOutMessage - .TEXT() - .content(href) - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()).build(); - } - }; - - wxCpMessageRouter = new WxCpMessageRouter(wxCpService); - wxCpMessageRouter - .rule() - .async(false) - .content("哈哈") // 拦截内容为“哈哈”的消息 - .handler(handler) - .end() - .rule() - .async(false) - .content("oauth") - .handler(oauth2handler) - .end() - ; + InputStream is1 = ClassLoader.getSystemResourceAsStream("test-config.xml"); + WxCpDemoInMemoryConfigStorage config = WxCpDemoInMemoryConfigStorage.fromXml(is1); + + wxCpConfigStorage = config; + wxCpService = new WxCpServiceImpl(); + wxCpService.setWxCpConfigStorage(config); + + WxCpMessageHandler handler = new WxCpMessageHandler() { + @Override + public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, + WxCpService wxCpService, WxSessionManager sessionManager) { + WxCpXmlOutTextMessage m = WxCpXmlOutMessage + .TEXT() + .content("测试加密消息") + .fromUser(wxMessage.getToUserName()) + .toUser(wxMessage.getFromUserName()) + .build(); + return m; + } + }; + + WxCpMessageHandler oauth2handler = new WxCpMessageHandler() { + @Override + public WxCpXmlOutMessage handle(WxCpXmlMessage wxMessage, Map context, + WxCpService wxCpService, WxSessionManager sessionManager) { + String href = "测试oauth2"; + return WxCpXmlOutMessage + .TEXT() + .content(href) + .fromUser(wxMessage.getToUserName()) + .toUser(wxMessage.getFromUserName()).build(); + } + }; + + wxCpMessageRouter = new WxCpMessageRouter(wxCpService); + wxCpMessageRouter + .rule() + .async(false) + .content("哈哈") // 拦截内容为“哈哈”的消息 + .handler(handler) + .end() + .rule() + .async(false) + .content("oauth") + .handler(oauth2handler) + .end() + ; } } diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java index 1fe8f5923d..67738d2b89 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpEndpointServlet.java @@ -24,7 +24,7 @@ public class WxCpEndpointServlet extends HttpServlet { protected WxCpMessageRouter wxCpMessageRouter; public WxCpEndpointServlet(WxCpConfigStorage wxCpConfigStorage, WxCpService wxCpService, - WxCpMessageRouter wxCpMessageRouter) { + WxCpMessageRouter wxCpMessageRouter) { this.wxCpConfigStorage = wxCpConfigStorage; this.wxCpService = wxCpService; this.wxCpMessageRouter = wxCpMessageRouter; @@ -32,7 +32,7 @@ public WxCpEndpointServlet(WxCpConfigStorage wxCpConfigStorage, WxCpService wxCp @Override protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); @@ -56,7 +56,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) } WxCpXmlMessage inMessage = WxCpXmlMessage - .fromEncryptedXml(request.getInputStream(), wxCpConfigStorage, timestamp, nonce, msgSignature); + .fromEncryptedXml(request.getInputStream(), wxCpConfigStorage, timestamp, nonce, msgSignature); WxCpXmlOutMessage outMessage = wxCpMessageRouter.route(inMessage); if (outMessage != null) { response.getWriter().write(outMessage.toEncryptedXml(wxCpConfigStorage)); diff --git a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java index e0800061f4..80dc565d7f 100644 --- a/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java +++ b/weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpOAuth2Servlet.java @@ -18,8 +18,9 @@ public WxCpOAuth2Servlet(WxCpService wxCpService) { this.wxCpService = wxCpService; } - @Override protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + @Override + protected void service(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); diff --git a/weixin-java-mp/build.gradle b/weixin-java-mp/build.gradle new file mode 100644 index 0000000000..dcc015480a --- /dev/null +++ b/weixin-java-mp/build.gradle @@ -0,0 +1,13 @@ + +description = 'WeiXin Java Tools - MP' +dependencies { + compile project(':weixin-java-common') + testCompile group: 'junit', name: 'junit', version:'4.11' + testCompile group: 'org.testng', name: 'testng', version:'6.8.7' + testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' + testCompile group: 'com.google.inject', name: 'guice', version:'3.0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-server', version:'9.3.0.M0' + testCompile group: 'org.eclipse.jetty', name: 'jetty-servlet', version:'9.3.0.M0' + testCompile group: 'joda-time', name: 'joda-time', version:'2.9.4' +} +test.useTestNG() diff --git a/weixin-java-mp/pom.xml b/weixin-java-mp/pom.xml index 8b84e8b8de..2ed001450a 100644 --- a/weixin-java-mp/pom.xml +++ b/weixin-java-mp/pom.xml @@ -6,7 +6,7 @@ com.github.binarywang weixin-java-parent - 2.0.0 + 2.1.0 weixin-java-mp WeiXin Java Tools - MP diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpConfigStorage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpConfigStorage.java index 0cf9d2e1bf..3a2e7654c9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpConfigStorage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpConfigStorage.java @@ -81,13 +81,13 @@ public interface WxMpConfigStorage { String getOauth2redirectUri(); - String getHttp_proxy_host(); + String getHttpProxyHost(); - int getHttp_proxy_port(); + int getHttpProxyPort(); - String getHttp_proxy_username(); + String getHttpProxyUsername(); - String getHttp_proxy_password(); + String getHttpProxyPassword(); File getTmpDirFile(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java new file mode 100644 index 0000000000..32f219d51a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpDataCubeService.java @@ -0,0 +1,217 @@ +package me.chanjar.weixin.mp.api; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleTotal; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeInterfaceResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeMsgResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; + +import java.util.Date; +import java.util.List; + +/** + * 统计分析相关接口 + * Created by Binary Wang on 2016/8/23. + * @author binarywang (https://github.com/binarywang) + */ +public interface WxMpDataCubeService { + //*******************用户分析数据接口***********************// + + /** + *

    +   * 获取用户增减数据
    +   * 详情请见文档:用户分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN
    +   * 
    + * + * @param beginDate 开始时间 + * @param endDate 最大时间跨度7天,endDate不能早于begingDate + */ + List getUserSummary(Date beginDate, Date endDate) throws WxErrorException; + + /** + *
    +   * 获取累计用户数据
    +   * 详情请见文档:用户分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getusercumulate?access_token=ACCESS_TOKEN
    +   * 
    + * + * @param beginDate 开始时间 + * @param endDate 最大时间跨度7天,endDate不能早于begingDate + */ + List getUserCumulate(Date beginDate, Date endDate) throws WxErrorException; + + //*******************图文分析数据接口***********************// + + /** + *
    +   * 获取图文群发每日数据(getarticlesummary)
    +   * 详情请见文档:图文分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getarticlesummary?access_token=ACCESS_TOKEN
    +   * 
    + * + * @param beginDate 开始时间 + * @param endDate 最大时间跨度1天,endDate不能早于begingDate + */ + List getArticleSummary(Date beginDate, Date endDate) throws WxErrorException; + + /** + *
    +   * 获取图文群发总数据(getarticletotal)
    +   * 详情请见文档:图文分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getarticletotal?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度1天,endDate不能早于begingDate
    +   */
    +  List getArticleTotal(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取图文统计数据(getuserread)
    +   * 详情请见文档:图文分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getuserread?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度3天,endDate不能早于begingDate
    +   */
    +  List getUserRead(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取图文统计分时数据(getuserreadhour)
    +   * 详情请见文档:图文分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getuserreadhour?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度1天,endDate不能早于begingDate
    +   */
    +  List getUserReadHour(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取图文分享转发数据(getusershare)
    +   * 详情请见文档:图文分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getusershare?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度7天,endDate不能早于begingDate
    +   */
    +  List getUserShare(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取图文分享转发分时数据(getusersharehour)
    +   * 详情请见文档:图文分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getusersharehour?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度1天,endDate不能早于begingDate
    +   */
    +  List getUserShareHour(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  //*******************消息分析数据接口***********************//
    +
    +  /**
    +   * 
    +   * 获取消息发送概况数据(getupstreammsg)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsg?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度7天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsg(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取消息分送分时数据(getupstreammsghour)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsghour?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度1天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsgHour(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取消息发送周数据(getupstreammsgweek)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsgweek?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度30天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsgWeek(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取消息发送月数据(getupstreammsgmonth)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsgmonth?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度30天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsgMonth(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取消息发送分布数据(getupstreammsgdist)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsgdist?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度15天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsgDist(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取消息发送分布周数据(getupstreammsgdistweek)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsgdistweek?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度30天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsgDistWeek(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取消息发送分布月数据(getupstreammsgdistmonth)
    +   * 详情请见文档:消息分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getupstreammsgdistmonth?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度30天,endDate不能早于begingDate
    +   */
    +  List getUpstreamMsgDistMonth(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  //*******************接口分析数据接口***********************//
    +  /**
    +   * 
    +   * 获取接口分析数据(getinterfacesummary)
    +   * 详情请见文档:接口分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getinterfacesummary?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度30天,endDate不能早于begingDate
    +   */
    +  List getInterfaceSummary(Date beginDate, Date endDate) throws WxErrorException;
    +
    +  /**
    +   * 
    +   * 获取接口分析分时数据(getinterfacesummaryhour)
    +   * 详情请见文档:接口分析数据接口
    +   * 接口url格式:https://api.weixin.qq.com/datacube/getinterfacesummaryhour?access_token=ACCESS_TOKEN
    +   *
    +   * @param beginDate 开始时间
    +   * @param endDate   最大时间跨度1天,endDate不能早于begingDate
    +   */
    +  List getInterfaceSummaryHour(Date beginDate, Date endDate) throws WxErrorException;
    +
    +}
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java
    index 024f914a1b..765f6d537c 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpInMemoryConfigStorage.java
    @@ -4,6 +4,10 @@
     import me.chanjar.weixin.common.util.http.ApacheHttpClientBuilder;
     
     import javax.net.ssl.SSLContext;
    +
    +import org.apache.commons.lang3.builder.ToStringBuilder;
    +import org.apache.commons.lang3.builder.ToStringStyle;
    +
     import java.io.File;
     
     /**
    @@ -24,10 +28,10 @@ public class WxMpInMemoryConfigStorage implements WxMpConfigStorage {
     
       protected volatile String oauth2redirectUri;
     
    -  protected volatile String http_proxy_host;
    -  protected volatile int http_proxy_port;
    -  protected volatile String http_proxy_username;
    -  protected volatile String http_proxy_password;
    +  protected volatile String httpProxyHost;
    +  protected volatile int httpProxyPort;
    +  protected volatile String httpProxyUsername;
    +  protected volatile String httpProxyPassword;
     
       protected volatile String jsapiTicket;
       protected volatile long jsapiTicketExpiresTime;
    @@ -188,62 +192,44 @@ public void setOauth2redirectUri(String oauth2redirectUri) {
       }
     
       @Override
    -  public String getHttp_proxy_host() {
    -    return this.http_proxy_host;
    +  public String getHttpProxyHost() {
    +    return this.httpProxyHost;
       }
     
    -  public void setHttp_proxy_host(String http_proxy_host) {
    -    this.http_proxy_host = http_proxy_host;
    +  public void setHttpProxyHost(String httpProxyHost) {
    +    this.httpProxyHost = httpProxyHost;
       }
     
       @Override
    -  public int getHttp_proxy_port() {
    -    return this.http_proxy_port;
    +  public int getHttpProxyPort() {
    +    return this.httpProxyPort;
       }
     
    -  public void setHttp_proxy_port(int http_proxy_port) {
    -    this.http_proxy_port = http_proxy_port;
    +  public void setHttpProxyPort(int httpProxyPort) {
    +    this.httpProxyPort = httpProxyPort;
       }
     
       @Override
    -  public String getHttp_proxy_username() {
    -    return this.http_proxy_username;
    +  public String getHttpProxyUsername() {
    +    return this.httpProxyUsername;
       }
     
    -  public void setHttp_proxy_username(String http_proxy_username) {
    -    this.http_proxy_username = http_proxy_username;
    +  public void setHttpProxyUsername(String httpProxyUsername) {
    +    this.httpProxyUsername = httpProxyUsername;
       }
     
       @Override
    -  public String getHttp_proxy_password() {
    -    return this.http_proxy_password;
    +  public String getHttpProxyPassword() {
    +    return this.httpProxyPassword;
       }
     
    -  public void setHttp_proxy_password(String http_proxy_password) {
    -    this.http_proxy_password = http_proxy_password;
    +  public void setHttpProxyPassword(String httpProxyPassword) {
    +    this.httpProxyPassword = httpProxyPassword;
       }
     
       @Override
       public String toString() {
    -    return "WxMpInMemoryConfigStorage{" +
    -        "appId='" + this.appId + '\'' +
    -        ", secret='" + this.secret + '\'' +
    -        ", token='" + this.token + '\'' +
    -        ", partnerId='" + this.partnerId + '\'' +
    -        ", partnerKey='" + this.partnerKey + '\'' +
    -        ", accessToken='" + this.accessToken + '\'' +
    -        ", aesKey='" + this.aesKey + '\'' +
    -        ", expiresTime=" + this.expiresTime +
    -        ", http_proxy_host='" + this.http_proxy_host + '\'' +
    -        ", http_proxy_port=" + this.http_proxy_port +
    -        ", http_proxy_username='" + this.http_proxy_username + '\'' +
    -        ", http_proxy_password='" + this.http_proxy_password + '\'' +
    -        ", jsapiTicket='" + this.jsapiTicket + '\'' +
    -        ", jsapiTicketExpiresTime='" + this.jsapiTicketExpiresTime + '\'' +
    -        ", cardApiTicket='" + this.cardApiTicket + '\'' +
    -        ", cardApiTicketExpiresTime='" + this.cardApiTicketExpiresTime + '\'' +
    -        ", tmpDirFile='" + this.tmpDirFile + '\'' +
    -        '}';
    +    return ToStringBuilder.reflectionToString(this,ToStringStyle.JSON_STYLE);
       }
     
       @Override
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java
    index 31ce48d3ac..22217801e0 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMenuService.java
    @@ -1,6 +1,6 @@
     package me.chanjar.weixin.mp.api;
     
    -import me.chanjar.weixin.common.bean.WxMenu;
    +import me.chanjar.weixin.common.bean.menu.WxMenu;
     import me.chanjar.weixin.common.exception.WxErrorException;
     
     /**
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java
    index 1de7ba9044..b72cc45af8 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpMessageRouter.java
    @@ -54,7 +54,7 @@ public class WxMpMessageRouter {
     
       private static final int DEFAULT_THREAD_POOL_SIZE = 100;
     
    -  private final List rules = new ArrayList();
    +  private final List rules = new ArrayList<>();
     
       private final WxMpService wxMpService;
     
    @@ -139,9 +139,9 @@ public WxMpXmlOutMessage route(final WxMpXmlMessage wxMessage) {
           return null;
         }
     
    -    final List matchRules = new ArrayList();
    +    final List matchRules = new ArrayList<>();
         // 收集匹配的规则
    -    for (final WxMpMessageRouterRule rule : rules) {
    +    for (final WxMpMessageRouterRule rule : this.rules) {
           if (rule.test(wxMessage)) {
             matchRules.add(rule);
             if(!rule.isReEnter()) {
    @@ -155,39 +155,40 @@ public WxMpXmlOutMessage route(final WxMpXmlMessage wxMessage) {
         }
     
         WxMpXmlOutMessage res = null;
    -    final List futures = new ArrayList();
    +    final List futures = new ArrayList<>();
         for (final WxMpMessageRouterRule rule : matchRules) {
           // 返回最后一个非异步的rule的执行结果
           if(rule.isAsync()) {
             futures.add(
    -            executorService.submit(new Runnable() {
    +            this.executorService.submit(new Runnable() {
    +              @Override
                   public void run() {
    -                rule.service(wxMessage, wxMpService, sessionManager, exceptionHandler);
    +                rule.service(wxMessage, WxMpMessageRouter.this.wxMpService, WxMpMessageRouter.this.sessionManager, WxMpMessageRouter.this.exceptionHandler);
                   }
                 })
             );
           } else {
    -        res = rule.service(wxMessage, wxMpService, sessionManager, exceptionHandler);
    +        res = rule.service(wxMessage, this.wxMpService, this.sessionManager, this.exceptionHandler);
             // 在同步操作结束,session访问结束
    -        log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName());
    +        this.log.debug("End session access: async=false, sessionId={}", wxMessage.getFromUserName());
             sessionEndAccess(wxMessage);
           }
         }
     
         if (futures.size() > 0) {
    -      executorService.submit(new Runnable() {
    +      this.executorService.submit(new Runnable() {
             @Override
             public void run() {
               for (Future future : futures) {
                 try {
                   future.get();
    -              log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName());
    +              WxMpMessageRouter.this.log.debug("End session access: async=true, sessionId={}", wxMessage.getFromUserName());
                   // 异步操作结束,session访问结束
                   sessionEndAccess(wxMessage);
                 } catch (InterruptedException e) {
    -              log.error("Error happened when wait task finish", e);
    +              WxMpMessageRouter.this.log.error("Error happened when wait task finish", e);
                 } catch (ExecutionException e) {
    -              log.error("Error happened when wait task finish", e);
    +              WxMpMessageRouter.this.log.error("Error happened when wait task finish", e);
                 }
               }
             }
    @@ -209,7 +210,7 @@ protected boolean isDuplicateMessage(WxMpXmlMessage wxMessage) {
           messageId.append(wxMessage.getMsgId());
         }
     
    -    return messageDuplicateChecker.isDuplicate(messageId.toString());
    +    return this.messageDuplicateChecker.isDuplicate(messageId.toString());
     
       }
     
    @@ -219,7 +220,7 @@ protected boolean isDuplicateMessage(WxMpXmlMessage wxMessage) {
        */
       protected void sessionEndAccess(WxMpXmlMessage wxMessage) {
     
    -    InternalSession session = ((InternalSessionManager)sessionManager).findSession(wxMessage.getFromUserName());
    +    InternalSession session = ((InternalSessionManager)this.sessionManager).findSession(wxMessage.getFromUserName());
         if (session != null) {
           session.endAccess();
         }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java
    index d136615223..7acd2342fe 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpService.java
    @@ -152,16 +152,6 @@ public interface WxMpService {
        */
       WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException;
     
    -  /**
    -   * 
    -   * 构造oauth2授权的url连接
    -   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息
    -   * 
    - * - * @return url - */ - String oauth2buildAuthorizationUrl(String scope, String state); - /** *
        * 构造oauth2授权的url连接
    @@ -346,4 +336,11 @@ public interface WxMpService {
        * @return WxMpPayService
        */
       WxMpPayService getPayService();
    +
    +  /**
    +   * 返回数据分析统计相关接口的方法实现类,以方便调用个其各种接口
    +   *
    +   * @return WxMpDataCubeService
    +   */
    +  WxMpDataCubeService getDataCubeService();
     }
    diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java
    index 0705e990a1..deaf85ab9d 100644
    --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java
    +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/WxMpUserService.java
    @@ -1,12 +1,10 @@
     package me.chanjar.weixin.mp.api;
     
     import me.chanjar.weixin.common.exception.WxErrorException;
    +import me.chanjar.weixin.mp.bean.WxMpUserQuery;
     import me.chanjar.weixin.mp.bean.result.WxMpUser;
    -import me.chanjar.weixin.mp.bean.result.WxMpUserCumulate;
     import me.chanjar.weixin.mp.bean.result.WxMpUserList;
    -import me.chanjar.weixin.mp.bean.result.WxMpUserSummary;
     
    -import java.util.Date;
     import java.util.List;
     
     /**
    @@ -34,39 +32,37 @@ public interface WxMpUserService {
        * 
    * * @param openid 用户openid - * @param lang 语言,zh_CN 简体(默认),zh_TW 繁体,en 英语 + * @param lang 语言,zh_CN 简体(默认),zh_TW 繁体,en 英语 */ WxMpUser userInfo(String openid, String lang) throws WxErrorException; /** *
    -   * 获取关注者列表
    -   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表
    +   * 获取用户基本信息列表
    +   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=批量获取用户基本信息
        * 
    * - * @param next_openid 可选,第一个拉取的OPENID,null为从头开始拉取 + * @param openidList 用户openid列表 */ - WxMpUserList userList(String next_openid) throws WxErrorException; + List userInfoList(List openidList) throws WxErrorException; /** *
    -   * 获取用户增减数据
    -   * http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
    +   * 获取用户基本信息列表
    +   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=批量获取用户基本信息
        * 
    * - * @param beginDate 最大时间跨度7天 - * @param endDate endDate不能早于begingDate + * @param userQuery 详细查询参数 */ - List dataCubeUserSummary(Date beginDate, Date endDate) throws WxErrorException; + List userInfoList(WxMpUserQuery userQuery) throws WxErrorException; /** *
    -   * 获取累计用户数据
    -   * http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html
    +   * 获取关注者列表
    +   * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表
        * 
    * - * @param beginDate 最大时间跨度7天 - * @param endDate endDate不能早于begingDate + * @param nextOpenid 可选,第一个拉取的OPENID,null为从头开始拉取 */ - List dataCubeUserCumulate(Date beginDate, Date endDate) throws WxErrorException; + WxMpUserList userList(String nextOpenid) throws WxErrorException; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java index 40d3557226..b65d1ff4bb 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java @@ -1,12 +1,17 @@ package me.chanjar.weixin.mp.api.impl; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; -import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; + import me.chanjar.weixin.common.bean.WxCardApiSignature; import me.chanjar.weixin.common.bean.result.WxError; import me.chanjar.weixin.common.exception.WxErrorException; @@ -17,12 +22,6 @@ import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpCardResult; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.StringReader; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; /** * Created by Binary Wang on 2016/7/27. @@ -38,7 +37,7 @@ public class WxMpCardServiceImpl implements WxMpCardService { private WxMpService wxMpService; - WxMpCardServiceImpl(WxMpService wxMpService) { + public WxMpCardServiceImpl(WxMpService wxMpService) { this.wxMpService = wxMpService; } @@ -76,7 +75,7 @@ public String getCardApiTicket(boolean forceRefresh) throws WxErrorException { if (this.wxMpService.getWxMpConfigStorage().isCardApiTicketExpired()) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=wx_card"; String responseContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String cardApiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); @@ -136,7 +135,7 @@ public String decryptCardCode(String encryptCode) throws WxErrorException { JsonObject param = new JsonObject(); param.addProperty("encrypt_code", encryptCode); String responseContent = this.wxMpService.post(url, param.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); JsonPrimitive jsonPrimitive = tmpJsonObject.getAsJsonPrimitive("code"); return jsonPrimitive.getAsString(); @@ -158,7 +157,7 @@ public WxMpCardResult queryCardCode(String cardId, String code, boolean checkCon param.addProperty("code", code); param.addProperty("check_consume", checkConsume); String responseContent = this.wxMpService.post(url, param.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement, new TypeToken() { }.getType()); @@ -217,7 +216,7 @@ public void markCardCode(String code, String cardId, String openId, boolean isMa param.addProperty("openid", openId); param.addProperty("is_mark", isMark); String responseContent = this.wxMpService.post(url, param.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); WxMpCardResult cardResult = WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement, new TypeToken() { }.getType()); if (!cardResult.getErrorCode().equals("0")) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java new file mode 100644 index 0000000000..092d6af16c --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImpl.java @@ -0,0 +1,265 @@ +package me.chanjar.weixin.mp.api.impl; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.WxMpDataCubeService; +import me.chanjar.weixin.mp.api.WxMpService; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleTotal; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeInterfaceResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeMsgResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; +import java.util.List; + +/** + * Created by Binary Wang on 2016/8/23. + * @author binarywang (https://github.com/binarywang) + */ +public class WxMpDataCubeServiceImpl implements WxMpDataCubeService { + protected final Logger log = LoggerFactory.getLogger(WxMpDataCubeServiceImpl.class); + + private static final String API_URL_PREFIX = "https://api.weixin.qq.com/datacube"; + private WxMpService wxMpService; + + public WxMpDataCubeServiceImpl(WxMpService wxMpService) { + this.wxMpService = wxMpService; + } + + @Override + public List getUserSummary(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getusersummary"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUserCumulate(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getusercumulate"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getArticleSummary(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getarticlesummary"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getArticleTotal(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getarticletotal"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUserRead(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getuserread"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUserReadHour(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getuserreadhour"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUserShare(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getusershare"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUserShareHour(Date beginDate, Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getusersharehour"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsg(Date beginDate, Date endDate) + throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsg"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsgHour(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsghour"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsgWeek(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsgweek"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsgMonth(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsgmonth"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsgDist(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsgdist"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsgDistWeek(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsgdistweek"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getUpstreamMsgDistMonth(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getupstreammsgdistmonth"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getInterfaceSummary(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getinterfacesummary"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } + + @Override + public List getInterfaceSummaryHour(Date beginDate, + Date endDate) throws WxErrorException { + String url = API_URL_PREFIX + "/getinterfacesummaryhour"; + JsonObject param = new JsonObject(); + param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); + param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); + String responseContent = this.wxMpService.post(url, param.toString()); + this.log.debug("\nurl:{}\nparams:{}\nresponse:{}",url, param, responseContent); + return WxMpGsonBuilder.INSTANCE.create().fromJson(new JsonParser().parse(responseContent).getAsJsonObject().get("list"), + new TypeToken>() { + }.getType()); + } +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java index ea388dea11..5f97a83aa0 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpGroupServiceImpl.java @@ -1,10 +1,12 @@ package me.chanjar.weixin.mp.api.impl; +import java.util.List; + import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.internal.Streams; +import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; + import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; @@ -14,9 +16,6 @@ import me.chanjar.weixin.mp.bean.WxMpGroup; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; -import java.io.StringReader; -import java.util.List; - /** * Created by Binary Wang on 2016/7/21. */ @@ -51,7 +50,7 @@ public List groupGet() throws WxErrorException { * 操蛋的微信API,创建时返回的是 { group : { id : ..., name : ...} } * 查询时返回的是 { groups : [ { id : ..., name : ..., count : ... }, ... ] } */ - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("groups"), new TypeToken>() { }.getType()); @@ -63,7 +62,7 @@ public long userGetGroup(String openid) throws WxErrorException { JsonObject o = new JsonObject(); o.addProperty("openid", openid); String responseContent = this.wxMpService.execute(new SimplePostRequestExecutor(), url, o.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = new JsonParser().parse(responseContent); return GsonHelper.getAsLong(tmpJsonElement.getAsJsonObject().get("groupid")); } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java index bfad1e06a9..28dbff912e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImpl.java @@ -1,6 +1,6 @@ package me.chanjar.weixin.mp.api.impl; -import me.chanjar.weixin.common.bean.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenu; import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java index 81638b7a71..ce7f951714 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpPayServiceImpl.java @@ -26,12 +26,15 @@ /** * Created by Binary Wang on 2016/7/28. + * * @author binarywang (https://github.com/binarywang) */ public class WxMpPayServiceImpl implements WxMpPayService { private final Logger log = LoggerFactory.getLogger(WxMpPayServiceImpl.class); - + private final String[] REQUIRED_ORDER_PARAMETERS = new String[]{"appid", + "mch_id", "body", "out_trade_no", "total_fee", "spbill_create_ip", + "notify_url", "trade_type"}; private HttpHost httpProxy; private WxMpServiceImpl wxMpService; @@ -41,10 +44,14 @@ public WxMpPayServiceImpl(WxMpServiceImpl wxMpService) { } @Override - public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double amt, String body, String tradeType, String ip, String callbackUrl) { + public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, + double amt, String body, String tradeType, String ip, + String callbackUrl) { Map packageParams = new HashMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -58,62 +65,81 @@ public WxMpPrepayIdResult getPrepayId(String openId, String outTradeNo, double a @Override public WxMpPrepayIdResult getPrepayId(final Map parameters) { - String nonce_str = System.currentTimeMillis() + ""; - final SortedMap packageParams = new TreeMap<>(parameters); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("nonce_str", nonce_str); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("nonce_str", System.currentTimeMillis() + ""); checkParameters(packageParams); - String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + String sign = WxCryptUtil.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } + request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/pay/unifiedorder"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPrepayIdResult.class); return (WxMpPrepayIdResult) xstream.fromXML(responseContent); } catch (IOException e) { - throw new RuntimeException("Failed to get prepay id due to IO exception.", e); - }finally { + throw new RuntimeException("Failed to get prepay id due to IO exception.", + e); + } finally { httpPost.releaseConnection(); } } - private final String[] REQUIRED_ORDER_PARAMETERS = new String[] { "appid", "mch_id", "body", "out_trade_no", - "total_fee", "spbill_create_ip", "notify_url","trade_type"}; - private void checkParameters(Map parameters) { for (String para : this.REQUIRED_ORDER_PARAMETERS) { - if (!parameters.containsKey(para)) - throw new IllegalArgumentException("Reqiured argument '" + para + "' is missing."); + if (!parameters.containsKey(para)) { + throw new IllegalArgumentException( + "Reqiured argument '" + para + "' is missing."); + } + } + + if ("JSAPI".equals(parameters.get("trade_type")) + && !parameters.containsKey("openid")) { + throw new IllegalArgumentException( + "Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); + } + + if ("NATIVE".equals(parameters.get("trade_type")) + && !parameters.containsKey("product_id")) { + throw new IllegalArgumentException( + "Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); } - if ("JSAPI".equals(parameters.get("trade_type")) && !parameters.containsKey("openid")) - throw new IllegalArgumentException("Reqiured argument 'openid' is missing when trade_type is 'JSAPI'."); - if ("NATIVE".equals(parameters.get("trade_type")) && !parameters.containsKey("product_id")) - throw new IllegalArgumentException("Reqiured argument 'product_id' is missing when trade_type is 'NATIVE'."); } @Override - public Map getJsapiPayInfo(String openId,String outTradeNo, double amt, String body,String ip, String callbackUrl) throws WxErrorException { + public Map getJsapiPayInfo(String openId, String outTradeNo, + double amt, String body, String ip, String callbackUrl) + throws WxErrorException { Map packageParams = new HashMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -126,10 +152,14 @@ public Map getJsapiPayInfo(String openId,String outTradeNo, doub } @Override - public Map getNativePayInfo(String productId,String outTradeNo, double amt, String body,String ip, String callbackUrl) throws WxErrorException{ + public Map getNativePayInfo(String productId, + String outTradeNo, double amt, String body, String ip, String callbackUrl) + throws WxErrorException { Map packageParams = new HashMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); packageParams.put("body", body); packageParams.put("out_trade_no", outTradeNo); packageParams.put("total_fee", (int) (amt * 100) + ""); @@ -142,24 +172,28 @@ public Map getNativePayInfo(String productId,String outTradeNo, } @Override - public Map getPayInfo(Map parameters) throws WxErrorException { + public Map getPayInfo(Map parameters) + throws WxErrorException { WxMpPrepayIdResult wxMpPrepayIdResult = getPrepayId(parameters); if (!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getReturn_code()) - ||!"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { + || !"SUCCESS".equalsIgnoreCase(wxMpPrepayIdResult.getResult_code())) { WxError error = new WxError(); error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() + - ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + - ";result_code:" + wxMpPrepayIdResult.getResult_code() + - ";err_code" + wxMpPrepayIdResult.getErr_code() + - ";err_code_des" + wxMpPrepayIdResult.getErr_code_des()); + error.setErrorMsg("return_code:" + wxMpPrepayIdResult.getReturn_code() + + ";return_msg:" + wxMpPrepayIdResult.getReturn_msg() + + ";result_code:" + wxMpPrepayIdResult.getResult_code() + ";err_code" + + wxMpPrepayIdResult.getErr_code() + ";err_code_des" + + wxMpPrepayIdResult.getErr_code_des()); throw new WxErrorException(error); } String prepayId = wxMpPrepayIdResult.getPrepay_id(); if (prepayId == null || prepayId.equals("")) { - throw new RuntimeException(String.format("Failed to get prepay id due to error code '%s'(%s).", wxMpPrepayIdResult.getErr_code(), wxMpPrepayIdResult.getErr_code_des())); + throw new RuntimeException( + String.format("Failed to get prepay id due to error code '%s'(%s).", + wxMpPrepayIdResult.getErr_code(), + wxMpPrepayIdResult.getErr_code_des())); } Map payInfo = new HashMap<>(); @@ -169,52 +203,67 @@ public Map getPayInfo(Map parameters) throws WxE payInfo.put("nonceStr", System.currentTimeMillis() + ""); payInfo.put("package", "prepay_id=" + prepayId); payInfo.put("signType", "MD5"); - if("NATIVE".equals(parameters.get("trade_type"))){ + if ("NATIVE".equals(parameters.get("trade_type"))) { payInfo.put("codeUrl", wxMpPrepayIdResult.getCode_url()); } - String finalSign = WxCryptUtil.createSign(payInfo, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + String finalSign = WxCryptUtil.createSign(payInfo, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); payInfo.put("paySign", finalSign); return payInfo; } @Override - public WxMpPayResult getJSSDKPayResult(String transactionId, String outTradeNo) { + public WxMpPayResult getJSSDKPayResult(String transactionId, + String outTradeNo) { String nonce_str = System.currentTimeMillis() + ""; SortedMap packageParams = new TreeMap<>(); - packageParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - if (transactionId != null && !"".equals(transactionId.trim())) + packageParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + + if (transactionId != null && !"".equals(transactionId.trim())) { packageParams.put("transaction_id", transactionId); - else if (outTradeNo != null && !"".equals(outTradeNo.trim())) + } else if (outTradeNo != null && !"".equals(outTradeNo.trim())) { packageParams.put("out_trade_no", outTradeNo); - else - throw new IllegalArgumentException("Either 'transactionId' or 'outTradeNo' must be given."); + } else { + throw new IllegalArgumentException( + "Either 'transactionId' or 'outTradeNo' must be given."); + } + packageParams.put("nonce_str", nonce_str); - packageParams.put("sign", WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + packageParams.put("sign", WxCryptUtil.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/pay/orderquery"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayResult.class); return (WxMpPayResult) xstream.fromXML(responseContent); } catch (IOException e) { - throw new RuntimeException("Failed to query order due to IO exception.", e); + throw new RuntimeException("Failed to query order due to IO exception.", + e); } } @@ -224,7 +273,7 @@ public WxMpPayCallback getJSSDKCallbackData(String xmlData) { XStream xstream = XStreamInitializer.getInstance(); xstream.alias("xml", WxMpPayCallback.class); return (WxMpPayCallback) xstream.fromXML(xmlData); - } catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } @@ -232,102 +281,126 @@ public WxMpPayCallback getJSSDKCallbackData(String xmlData) { } @Override - public WxMpPayRefundResult refundPay(Map parameters) throws WxErrorException { + public WxMpPayRefundResult refundPay(Map parameters) + throws WxErrorException { SortedMap refundParams = new TreeMap<>(parameters); - refundParams.put("appid", this.wxMpService.getWxMpConfigStorage().getAppId()); - refundParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); + refundParams.put("appid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + refundParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); refundParams.put("nonce_str", System.currentTimeMillis() + ""); - refundParams.put("op_user_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - String sign = WxCryptUtil.createSign(refundParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + refundParams.put("op_user_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + String sign = WxCryptUtil.createSign(refundParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); refundParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : refundParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/secapi/pay/refund"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxMpPayRefundResult.class); - WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream.fromXML(responseContent); + WxMpPayRefundResult wxMpPayRefundResult = (WxMpPayRefundResult) xstream + .fromXML(responseContent); if (!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getResultCode()) - ||!"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { + || !"SUCCESS".equalsIgnoreCase(wxMpPayRefundResult.getReturnCode())) { WxError error = new WxError(); error.setErrorCode(-1); - error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + - ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + - ";result_code:" + wxMpPayRefundResult.getResultCode() + - ";err_code" + wxMpPayRefundResult.getErrCode() + - ";err_code_des" + wxMpPayRefundResult.getErrCodeDes()); + error.setErrorMsg("return_code:" + wxMpPayRefundResult.getReturnCode() + + ";return_msg:" + wxMpPayRefundResult.getReturnMsg() + + ";result_code:" + wxMpPayRefundResult.getResultCode() + + ";err_code" + wxMpPayRefundResult.getErrCode() + ";err_code_des" + + wxMpPayRefundResult.getErrCodeDes()); throw new WxErrorException(error); } return wxMpPayRefundResult; } catch (IOException e) { - this.log.error(MessageFormatter.format("The exception was happened when sending refund '{}'.", - request.toString()).getMessage(), e); - WxError error = new WxError(); - error.setErrorCode(-1); - error.setErrorMsg("incorrect response."); - throw new WxErrorException(error); - }finally { + String message = MessageFormatter + .format("Exception happened when sending refund '{}'.", + request.toString()) + .getMessage(); + this.log.error(message, e); + throw new WxErrorException( + WxError.newBuilder().setErrorMsg(message).build()); + } finally { httpPost.releaseConnection(); } } @Override - public boolean checkJSSDKCallbackDataSignature(Map kvm, String signature) { - return signature.equals(WxCryptUtil.createSign(kvm, this.wxMpService.getWxMpConfigStorage().getPartnerKey())); + public boolean checkJSSDKCallbackDataSignature(Map kvm, + String signature) { + return signature.equals(WxCryptUtil.createSign(kvm, + this.wxMpService.getWxMpConfigStorage().getPartnerKey())); } @Override - public WxRedpackResult sendRedpack(Map parameters) throws WxErrorException { - String nonce_str = System.currentTimeMillis() + ""; - + public WxRedpackResult sendRedpack(Map parameters) + throws WxErrorException { SortedMap packageParams = new TreeMap<>(parameters); - packageParams.put("wxappid", this.wxMpService.getWxMpConfigStorage().getAppId()); - packageParams.put("mch_id", this.wxMpService.getWxMpConfigStorage().getPartnerId()); - packageParams.put("nonce_str", nonce_str); - - String sign = WxCryptUtil.createSign(packageParams, this.wxMpService.getWxMpConfigStorage().getPartnerKey()); + packageParams.put("wxappid", + this.wxMpService.getWxMpConfigStorage().getAppId()); + packageParams.put("mch_id", + this.wxMpService.getWxMpConfigStorage().getPartnerId()); + packageParams.put("nonce_str", System.currentTimeMillis() + ""); + + String sign = WxCryptUtil.createSign(packageParams, + this.wxMpService.getWxMpConfigStorage().getPartnerKey()); packageParams.put("sign", sign); StringBuilder request = new StringBuilder(""); for (Map.Entry para : packageParams.entrySet()) { - request.append(String.format("<%s>%s", para.getKey(), para.getValue(), para.getKey())); + request.append(String.format("<%s>%s", para.getKey(), + para.getValue(), para.getKey())); } + request.append(""); - HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); + HttpPost httpPost = new HttpPost( + "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"); if (this.httpProxy != null) { - RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy).build(); + RequestConfig config = RequestConfig.custom().setProxy(this.httpProxy) + .build(); httpPost.setConfig(config); } StringEntity entity = new StringEntity(request.toString(), Consts.UTF_8); httpPost.setEntity(entity); - try(CloseableHttpResponse response = this.wxMpService.getHttpclient().execute(httpPost)) { - String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response); + try (CloseableHttpResponse response = this.wxMpService.getHttpclient() + .execute(httpPost)) { + String responseContent = Utf8ResponseHandler.INSTANCE + .handleResponse(response); XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxRedpackResult.class); return (WxRedpackResult) xstream.fromXML(responseContent); } catch (IOException e) { - this.log.error(MessageFormatter.format("The exception was happened when sending redpack '{}'.", request.toString()).getMessage(), e); - WxError error = new WxError(); - error.setErrorCode(-1); - throw new WxErrorException(error); - }finally { + String message = MessageFormatter + .format("Exception occured when sending redpack '{}'.", + request.toString()) + .getMessage(); + this.log.error(message, e); + throw new WxErrorException(WxError.newBuilder().setErrorMsg(message).build()); + } finally { httpPost.releaseConnection(); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java index f0ca0d17fe..43777c1627 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpServiceImpl.java @@ -3,8 +3,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.internal.Streams; -import com.google.gson.stream.JsonReader; +import com.google.gson.JsonParser; import me.chanjar.weixin.common.bean.WxAccessToken; import me.chanjar.weixin.common.bean.WxJsapiSignature; import me.chanjar.weixin.common.bean.result.WxError; @@ -21,6 +20,7 @@ import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; @@ -28,11 +28,12 @@ import org.slf4j.LoggerFactory; import java.io.IOException; -import java.io.StringReader; import java.security.NoSuchAlgorithmException; public class WxMpServiceImpl implements WxMpService { + private static final JsonParser JSON_PARSER = new JsonParser(); + protected final Logger log = LoggerFactory.getLogger(WxMpServiceImpl.class); /** @@ -63,14 +64,12 @@ public class WxMpServiceImpl implements WxMpService { private WxMpPayService payService = new WxMpPayServiceImpl(this); + private WxMpDataCubeService dataCubeService = new WxMpDataCubeServiceImpl(this); + private CloseableHttpClient httpClient; private HttpHost httpProxy; - public HttpHost getHttpProxy() { - return this.httpProxy; - } - private int retrySleepMillis = 1000; private int maxRetryTimes = 5; @@ -144,7 +143,7 @@ public String getJsapiTicket(boolean forceRefresh) throws WxErrorException { if (this.wxMpConfigStorage.isJsapiTicketExpired()) { String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi"; String responseContent = execute(new SimpleGetRequestExecutor(), url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); JsonObject tmpJsonObject = tmpJsonElement.getAsJsonObject(); String jsapiTicket = tmpJsonObject.get("ticket").getAsString(); int expiresInSeconds = tmpJsonObject.get("expires_in").getAsInt(); @@ -213,6 +212,13 @@ public WxMpMassSendResult massOpenIdsMessageSend(WxMpMassOpenIdsMessage message) return WxMpMassSendResult.fromJson(responseContent); } + @Override + public WxMpMassSendResult massMessagePreview(WxMpMassPreviewMessage wxMpMassPreviewMessage) throws Exception { + String url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview"; + String responseContent = execute(new SimplePostRequestExecutor(), url, wxMpMassPreviewMessage.toJson()); + return WxMpMassSendResult.fromJson(responseContent); + } + @Override public String shortUrl(String long_url) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/shorturl"; @@ -220,7 +226,7 @@ public String shortUrl(String long_url) throws WxErrorException { o.addProperty("action", "long2short"); o.addProperty("long_url", long_url); String responseContent = execute(new SimplePostRequestExecutor(), url, o.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); return tmpJsonElement.getAsJsonObject().get("short_url").getAsString(); } @@ -228,13 +234,32 @@ public String shortUrl(String long_url) throws WxErrorException { public String templateSend(WxMpTemplateMessage templateMessage) throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/message/template/send"; String responseContent = execute(new SimplePostRequestExecutor(), url, templateMessage.toJson()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); final JsonObject jsonObject = tmpJsonElement.getAsJsonObject(); - if (jsonObject.get("errcode").getAsInt() == 0) + if (jsonObject.get("errcode").getAsInt() == 0){ return jsonObject.get("msgid").getAsString(); + } + throw new WxErrorException(WxError.fromJson(responseContent)); } + @Override + public String setIndustry(WxMpIndustry wxMpIndustry) throws WxErrorException { + if (null == wxMpIndustry.getPrimaryIndustry() || null == wxMpIndustry.getPrimaryIndustry().getId() + || null == wxMpIndustry.getSecondIndustry() || null == wxMpIndustry.getSecondIndustry().getId()) { + throw new IllegalArgumentException("industry id is empty"); + } + String url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry"; + return execute(new SimplePostRequestExecutor(), url, wxMpIndustry.toJson()); + } + + @Override + public WxMpIndustry getIndustry() throws WxErrorException { + String url = "https://api.weixin.qq.com/cgi-bin/template/get_industry"; + String responseContent = execute(new SimpleGetRequestExecutor(), url, null); + return WxMpIndustry.fromJson(responseContent); + } + @Override public WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) throws WxErrorException { String url = "https://api.weixin.qq.com/semantic/semproxy/search"; @@ -242,11 +267,6 @@ public WxMpSemanticQueryResult semanticQuery(WxMpSemanticQuery semanticQuery) th return WxMpSemanticQueryResult.fromJson(responseContent); } - @Override - public String oauth2buildAuthorizationUrl(String scope, String state) { - return this.oauth2buildAuthorizationUrl(this.wxMpConfigStorage.getOauth2redirectUri(), scope, state); - } - @Override public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) { StringBuilder url = new StringBuilder(); @@ -262,6 +282,16 @@ public String oauth2buildAuthorizationUrl(String redirectURI, String scope, Stri return url.toString(); } + private WxMpOAuth2AccessToken getOAuth2AccessToken(StringBuilder url) throws WxErrorException { + try { + RequestExecutor executor = new SimpleGetRequestExecutor(); + String responseText = executor.execute(this.getHttpclient(), this.httpProxy, url.toString(), null); + return WxMpOAuth2AccessToken.fromJson(responseText); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + @Override public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException { StringBuilder url = new StringBuilder(); @@ -271,13 +301,7 @@ public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorExc url.append("&code=").append(code); url.append("&grant_type=authorization_code"); - try { - RequestExecutor executor = new SimpleGetRequestExecutor(); - String responseText = executor.execute(getHttpclient(), this.httpProxy, url.toString(), null); - return WxMpOAuth2AccessToken.fromJson(responseText); - } catch (IOException e) { - throw new RuntimeException(e); - } + return this.getOAuth2AccessToken(url); } @Override @@ -288,13 +312,7 @@ public WxMpOAuth2AccessToken oauth2refreshAccessToken(String refreshToken) throw url.append("&grant_type=refresh_token"); url.append("&refresh_token=").append(refreshToken); - try { - RequestExecutor executor = new SimpleGetRequestExecutor(); - String responseText = executor.execute(getHttpclient(), this.httpProxy, url.toString(), null); - return WxMpOAuth2AccessToken.fromJson(responseText); - } catch (IOException e) { - throw new RuntimeException(e); - } + return this.getOAuth2AccessToken(url); } @Override @@ -340,7 +358,7 @@ public boolean oauth2validateAccessToken(WxMpOAuth2AccessToken oAuth2AccessToken public String[] getCallbackIP() throws WxErrorException { String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip"; String responseContent = get(url, null); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); + JsonElement tmpJsonElement = JSON_PARSER.parse(responseContent); JsonArray ipList = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray(); String[] ipArray = new String[ipList.size()]; for (int i = 0; i < ipList.size(); i++) { @@ -421,6 +439,10 @@ protected synchronized T executeInternal(RequestExecutor executor, throw new RuntimeException(e); } } + + public HttpHost getHttpProxy() { + return this.httpProxy; + } public CloseableHttpClient getHttpclient() { return this.httpClient; @@ -429,22 +451,23 @@ public CloseableHttpClient getHttpclient() { @Override public void setWxMpConfigStorage(WxMpConfigStorage wxConfigProvider) { this.wxMpConfigStorage = wxConfigProvider; + this.initHttpClient(); + } + private void initHttpClient() { ApacheHttpClientBuilder apacheHttpClientBuilder = this.wxMpConfigStorage.getApacheHttpClientBuilder(); if (null == apacheHttpClientBuilder) { - apacheHttpClientBuilder = DefaultApacheHttpHttpClientBuilder.get(); + apacheHttpClientBuilder = DefaultApacheHttpClientBuilder.get(); } - apacheHttpClientBuilder.httpProxyHost(this.wxMpConfigStorage.getHttp_proxy_host()) - .httpProxyPort(this.wxMpConfigStorage.getHttp_proxy_port()) - .httpProxyUsername(this.wxMpConfigStorage.getHttp_proxy_username()) - .httpProxyPassword(this.wxMpConfigStorage.getHttp_proxy_password()); + + apacheHttpClientBuilder.httpProxyHost(this.wxMpConfigStorage.getHttpProxyHost()) + .httpProxyPort(this.wxMpConfigStorage.getHttpProxyPort()) + .httpProxyUsername(this.wxMpConfigStorage.getHttpProxyUsername()) + .httpProxyPassword(this.wxMpConfigStorage.getHttpProxyPassword()); - if (wxConfigProvider.getSSLContext() != null){ + if (this.wxMpConfigStorage.getSSLContext() != null){ SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( - wxConfigProvider.getSSLContext(), - new String[] { "TLSv1" }, - null, - SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + this.wxMpConfigStorage.getSSLContext(), new String[] { "TLSv1" }, null, new DefaultHostnameVerifier()); apacheHttpClientBuilder.sslConnectionSocketFactory(sslsf); } @@ -461,36 +484,11 @@ public void setRetrySleepMillis(int retrySleepMillis) { this.retrySleepMillis = retrySleepMillis; } - @Override public void setMaxRetryTimes(int maxRetryTimes) { this.maxRetryTimes = maxRetryTimes; } - @Override - public WxMpMassSendResult massMessagePreview(WxMpMassPreviewMessage wxMpMassPreviewMessage) throws Exception { - String url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview"; - String responseContent = execute(new SimplePostRequestExecutor(), url, wxMpMassPreviewMessage.toJson()); - return WxMpMassSendResult.fromJson(responseContent); - } - - @Override - public String setIndustry(WxMpIndustry wxMpIndustry) throws WxErrorException { - if (null == wxMpIndustry.getPrimaryIndustry() || null == wxMpIndustry.getPrimaryIndustry().getId() - || null == wxMpIndustry.getSecondIndustry() || null == wxMpIndustry.getSecondIndustry().getId()) { - throw new IllegalArgumentException("industry id is empty"); - } - String url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry"; - return execute(new SimplePostRequestExecutor(), url, wxMpIndustry.toJson()); - } - - @Override - public WxMpIndustry getIndustry() throws WxErrorException { - String url = "https://api.weixin.qq.com/cgi-bin/template/get_industry"; - String responseContent = execute(new SimpleGetRequestExecutor(), url, null); - return WxMpIndustry.fromJson(responseContent); - } - @Override public WxMpKefuService getKefuService() { return this.kefuService; @@ -531,4 +529,9 @@ public WxMpPayService getPayService() { return this.payService; } + @Override + public WxMpDataCubeService getDataCubeService() { + return this.dataCubeService; + } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java index f2ceac3460..995eb58a1b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImpl.java @@ -1,24 +1,17 @@ package me.chanjar.weixin.mp.api.impl; -import com.google.gson.JsonElement; +import java.util.List; + import com.google.gson.JsonObject; -import com.google.gson.internal.Streams; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; + import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor; import me.chanjar.weixin.common.util.http.SimplePostRequestExecutor; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpUserService; +import me.chanjar.weixin.mp.bean.WxMpUserQuery; import me.chanjar.weixin.mp.bean.result.WxMpUser; -import me.chanjar.weixin.mp.bean.result.WxMpUserCumulate; import me.chanjar.weixin.mp.bean.result.WxMpUserList; -import me.chanjar.weixin.mp.bean.result.WxMpUserSummary; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - -import java.io.StringReader; -import java.util.Date; -import java.util.List; /** * Created by Binary Wang on 2016/7/21. @@ -56,28 +49,15 @@ public WxMpUserList userList(String next_openid) throws WxErrorException { } @Override - public List dataCubeUserSummary(Date beginDate, Date endDate) throws WxErrorException { - String url = "https://api.weixin.qq.com/datacube/getusersummary"; - JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); - String responseContent = this.wxMpService.post(url, param.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); - return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + public List userInfoList(List openidList) throws WxErrorException { + return userInfoList(new WxMpUserQuery(openidList)); } @Override - public List dataCubeUserCumulate(Date beginDate, Date endDate) throws WxErrorException { - String url = "https://api.weixin.qq.com/datacube/getusercumulate"; - JsonObject param = new JsonObject(); - param.addProperty("begin_date", WxMpService.SIMPLE_DATE_FORMAT.format(beginDate)); - param.addProperty("end_date", WxMpService.SIMPLE_DATE_FORMAT.format(endDate)); - String responseContent = this.wxMpService.post(url, param.toString()); - JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent))); - return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"), - new TypeToken>() { - }.getType()); + public List userInfoList(WxMpUserQuery userQuery) throws WxErrorException { + String url = API_URL_PREFIX + "/info/batchget"; + String responseContent = this.wxMpService.execute(new SimpleGetRequestExecutor(), url, userQuery.toJsonString()); + return WxMpUser.fromJsonList(responseContent); } + } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/Industry.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/Industry.java index 1270e7f5c2..da5b513427 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/Industry.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/Industry.java @@ -13,7 +13,7 @@ public class Industry implements Serializable { private String secondClass; public String getId() { - return id; + return this.id; } public void setId(String id) { @@ -21,7 +21,7 @@ public void setId(String id) { } public String getFirstClass() { - return firstClass; + return this.firstClass; } public void setFirstClass(String firstClass) { @@ -29,7 +29,7 @@ public void setFirstClass(String firstClass) { } public String getSecondClass() { - return secondClass; + return this.secondClass; } public void setSecondClass(String secondClass) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCard.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCard.java index d530fbe820..7bb4330fce 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCard.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCard.java @@ -20,7 +20,7 @@ public class WxMpCard { private Boolean canConsume; public String getCardId() { - return cardId; + return this.cardId; } public void setCardId(String cardId) { @@ -28,7 +28,7 @@ public void setCardId(String cardId) { } public Long getBeginTime() { - return beginTime; + return this.beginTime; } public void setBeginTime(Long beginTime) { @@ -36,7 +36,7 @@ public void setBeginTime(Long beginTime) { } public Long getEndTime() { - return endTime; + return this.endTime; } public void setEndTime(Long endTime) { @@ -44,7 +44,7 @@ public void setEndTime(Long endTime) { } public String getUserCardStatus() { - return userCardStatus; + return this.userCardStatus; } public void setUserCardStatus(String userCardStatus) { @@ -52,7 +52,7 @@ public void setUserCardStatus(String userCardStatus) { } public Boolean getCanConsume() { - return canConsume; + return this.canConsume; } public void setCanConsume(Boolean canConsume) { @@ -62,11 +62,11 @@ public void setCanConsume(Boolean canConsume) { @Override public String toString() { return "WxMpCard{" + - "cardId='" + cardId + '\'' + - ", beginTime=" + beginTime + - ", endTime=" + endTime + - ", userCardStatus='" + userCardStatus + '\'' + - ", canConsume=" + canConsume + + "cardId='" + this.cardId + '\'' + + ", beginTime=" + this.beginTime + + ", endTime=" + this.endTime + + ", userCardStatus='" + this.userCardStatus + '\'' + + ", canConsume=" + this.canConsume + '}'; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java index 5fce97a3f3..04eee33233 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpCustomMessage.java @@ -182,7 +182,7 @@ public static NewsBuilder NEWS() { } public String getKfAccount() { - return kfAccount; + return this.kfAccount; } public void setKfAccount(String kfAccount) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java index 9cef8c1be2..7dfd4ccccd 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpGroup.java @@ -11,23 +11,27 @@ */ public class WxMpGroup implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1554709708638735270L; private long id = -1; private String name; private long count; public long getId() { - return id; + return this.id; } public void setId(long id) { this.id = id; } public String getName() { - return name; + return this.name; } public void setName(String name) { this.name = name; } public long getCount() { - return count; + return this.count; } public void setCount(long count) { this.count = count; @@ -42,7 +46,7 @@ public String toJson() { } @Override public String toString() { - return "WxMpGroup [id=" + id + ", name=" + name + ", count=" + count + "]"; + return "WxMpGroup [id=" + this.id + ", name=" + this.name + ", count=" + this.count + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpIndustry.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpIndustry.java index be62084dea..281b9315a1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpIndustry.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpIndustry.java @@ -22,7 +22,7 @@ public String toJson() { } public Industry getPrimaryIndustry() { - return primaryIndustry; + return this.primaryIndustry; } public void setPrimaryIndustry(Industry primaryIndustry) { @@ -30,7 +30,7 @@ public void setPrimaryIndustry(Industry primaryIndustry) { } public Industry getSecondIndustry() { - return secondIndustry; + return this.secondIndustry; } public void setSecondIndustry(Industry secondIndustry) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java index b5faef72d9..d77605a610 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassGroupMessage.java @@ -11,6 +11,10 @@ */ public class WxMpMassGroupMessage implements Serializable { + /** + * + */ + private static final long serialVersionUID = -6625914040986749286L; private Long groupId; private String msgtype; private String content; @@ -21,7 +25,7 @@ public WxMpMassGroupMessage() { } public String getMsgtype() { - return msgtype; + return this.msgtype; } /** @@ -41,7 +45,7 @@ public void setMsgtype(String msgtype) { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { @@ -49,7 +53,7 @@ public void setContent(String content) { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -61,7 +65,7 @@ public String toJson() { } public Long getGroupId() { - return groupId; + return this.groupId; } /** diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java index 215bff5280..4b059ea8ee 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassNews.java @@ -13,10 +13,14 @@ */ public class WxMpMassNews implements Serializable { - private List articles = new ArrayList(); + /** + * + */ + private static final long serialVersionUID = 565937155013581016L; + private List articles = new ArrayList<>(); public List getArticles() { - return articles; + return this.articles; } public void addArticle(WxMpMassNewsArticle article) { @@ -28,7 +32,7 @@ public String toJson() { } public boolean isEmpty() { - return articles == null || articles.isEmpty(); + return this.articles == null || this.articles.isEmpty(); } /** @@ -76,7 +80,7 @@ public static class WxMpMassNewsArticle { private boolean showCoverPic; public String getThumbMediaId() { - return thumbMediaId; + return this.thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { @@ -84,7 +88,7 @@ public void setThumbMediaId(String thumbMediaId) { } public String getAuthor() { - return author; + return this.author; } public void setAuthor(String author) { @@ -92,7 +96,7 @@ public void setAuthor(String author) { } public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -100,7 +104,7 @@ public void setTitle(String title) { } public String getContentSourceUrl() { - return contentSourceUrl; + return this.contentSourceUrl; } public void setContentSourceUrl(String contentSourceUrl) { @@ -108,7 +112,7 @@ public void setContentSourceUrl(String contentSourceUrl) { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { @@ -116,7 +120,7 @@ public void setContent(String content) { } public String getDigest() { - return digest; + return this.digest; } public void setDigest(String digest) { @@ -124,7 +128,7 @@ public void setDigest(String digest) { } public boolean isShowCoverPic() { - return showCoverPic; + return this.showCoverPic; } public void setShowCoverPic(boolean showCoverPic) { @@ -133,14 +137,14 @@ public void setShowCoverPic(boolean showCoverPic) { @Override public String toString() { - return "WxMpMassNewsArticle [" + "thumbMediaId=" + thumbMediaId + ", author=" + author + ", title=" + title + - ", contentSourceUrl=" + contentSourceUrl + ", content=" + content + ", digest=" + digest + - ", showCoverPic=" + showCoverPic + "]"; + return "WxMpMassNewsArticle [" + "thumbMediaId=" + this.thumbMediaId + ", author=" + this.author + ", title=" + this.title + + ", contentSourceUrl=" + this.contentSourceUrl + ", content=" + this.content + ", digest=" + this.digest + + ", showCoverPic=" + this.showCoverPic + "]"; } } @Override public String toString() { - return "WxMpMassNews [" + "articles=" + articles + "]"; + return "WxMpMassNews [" + "articles=" + this.articles + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassPreviewMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassPreviewMessage.java index 154195dbb7..78e699e942 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassPreviewMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassPreviewMessage.java @@ -8,6 +8,10 @@ * @author miller */ public class WxMpMassPreviewMessage implements Serializable { + /** + * + */ + private static final long serialVersionUID = 9095211638358424020L; private String toWxUsername; private String msgType; private String content; @@ -18,7 +22,7 @@ public WxMpMassPreviewMessage() { } public String getToWxUsername() { - return toWxUsername; + return this.toWxUsername; } public void setToWxUsername(String toWxUsername) { @@ -26,7 +30,7 @@ public void setToWxUsername(String toWxUsername) { } public String getMsgType() { - return msgType; + return this.msgType; } /** @@ -47,7 +51,7 @@ public void setMsgType(String msgType) { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { @@ -55,7 +59,7 @@ public void setContent(String content) { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java index c2f0461086..ec94092cd1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMassVideo.java @@ -11,12 +11,16 @@ */ public class WxMpMassVideo implements Serializable { + /** + * + */ + private static final long serialVersionUID = 9153925016061915637L; private String mediaId; private String title; private String description; public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -24,7 +28,7 @@ public void setTitle(String title) { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { @@ -32,7 +36,7 @@ public void setDescription(String description) { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java index 582825aa99..058d903412 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterial.java @@ -22,14 +22,14 @@ public WxMpMaterial(String name, File file, String videoTitle, String videoIntro } public Map getForm() { - Map form = new HashMap(); - form.put("title", videoTitle); - form.put("introduction", videoIntroduction); + Map form = new HashMap<>(); + form.put("title", this.videoTitle); + form.put("introduction", this.videoIntroduction); return form; } public String getVideoTitle() { - return videoTitle; + return this.videoTitle; } public void setVideoTitle(String videoTitle) { @@ -37,7 +37,7 @@ public void setVideoTitle(String videoTitle) { } public String getVideoIntroduction() { - return videoIntroduction; + return this.videoIntroduction; } public void setVideoIntroduction(String videoIntroduction) { @@ -45,7 +45,7 @@ public void setVideoIntroduction(String videoIntroduction) { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -53,7 +53,7 @@ public void setName(String name) { } public File getFile() { - return file; + return this.file; } public void setFile(File file) { @@ -62,6 +62,6 @@ public void setFile(File file) { @Override public String toString() { - return "WxMpMaterial [" + "name=" + name + ", file=" + file + ", videoTitle=" + videoTitle + ", videoIntroduction=" + videoIntroduction + "]"; + return "WxMpMaterial [" + "name=" + this.name + ", file=" + this.file + ", videoTitle=" + this.videoTitle + ", videoIntroduction=" + this.videoIntroduction + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java index be8e75f8e2..f8ee265e5f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialArticleUpdate.java @@ -6,12 +6,16 @@ public class WxMpMaterialArticleUpdate implements Serializable { + /** + * + */ + private static final long serialVersionUID = -7611963949517780270L; private String mediaId; private int index; private WxMpMaterialNews.WxMpMaterialNewsArticle articles; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -19,7 +23,7 @@ public void setMediaId(String mediaId) { } public int getIndex() { - return index; + return this.index; } public void setIndex(int index) { @@ -27,7 +31,7 @@ public void setIndex(int index) { } public WxMpMaterialNews.WxMpMaterialNewsArticle getArticles() { - return articles; + return this.articles; } public void setArticles(WxMpMaterialNews.WxMpMaterialNewsArticle articles) { @@ -40,6 +44,6 @@ public String toJson() { @Override public String toString() { - return "WxMpMaterialArticleUpdate [" + "mediaId=" + mediaId + ", index=" + index + ", articles=" + articles + "]"; + return "WxMpMaterialArticleUpdate [" + "mediaId=" + this.mediaId + ", index=" + this.index + ", articles=" + this.articles + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java index 75ee479f1b..df40f6c3e9 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpMaterialNews.java @@ -8,10 +8,14 @@ public class WxMpMaterialNews implements Serializable { - private List articles = new ArrayList(); + /** + * + */ + private static final long serialVersionUID = -3283203652013494976L; + private List articles = new ArrayList<>(); public List getArticles() { - return articles; + return this.articles; } public void addArticle(WxMpMaterialNewsArticle article) { @@ -23,7 +27,7 @@ public String toJson() { } public boolean isEmpty() { - return articles == null || articles.isEmpty(); + return this.articles == null || this.articles.isEmpty(); } /** @@ -82,7 +86,7 @@ public static class WxMpMaterialNewsArticle { private String url; public String getThumbMediaId() { - return thumbMediaId; + return this.thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { @@ -90,7 +94,7 @@ public void setThumbMediaId(String thumbMediaId) { } public String getAuthor() { - return author; + return this.author; } public void setAuthor(String author) { @@ -98,7 +102,7 @@ public void setAuthor(String author) { } public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -106,7 +110,7 @@ public void setTitle(String title) { } public String getContentSourceUrl() { - return contentSourceUrl; + return this.contentSourceUrl; } public void setContentSourceUrl(String contentSourceUrl) { @@ -114,7 +118,7 @@ public void setContentSourceUrl(String contentSourceUrl) { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { @@ -122,7 +126,7 @@ public void setContent(String content) { } public String getDigest() { - return digest; + return this.digest; } public void setDigest(String digest) { @@ -130,7 +134,7 @@ public void setDigest(String digest) { } public boolean isShowCoverPic() { - return showCoverPic; + return this.showCoverPic; } public void setShowCoverPic(boolean showCoverPic) { @@ -138,7 +142,7 @@ public void setShowCoverPic(boolean showCoverPic) { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -146,7 +150,7 @@ public void setUrl(String url) { } public String getThumbUrl() { - return thumbUrl; + return this.thumbUrl; } public void setThumbUrl(String thumbUrl) { @@ -155,14 +159,14 @@ public void setThumbUrl(String thumbUrl) { @Override public String toString() { - return "WxMpMassNewsArticle [" + "thumbMediaId=" + thumbMediaId + "thumbUrl=" + thumbUrl + ", author=" + author + ", title=" + title + - ", contentSourceUrl=" + contentSourceUrl + ", content=" + content + ", digest=" + digest + - ", showCoverPic=" + showCoverPic +", url=" + url + "]"; + return "WxMpMassNewsArticle [" + "thumbMediaId=" + this.thumbMediaId + "thumbUrl=" + this.thumbUrl + ", author=" + this.author + ", title=" + this.title + + ", contentSourceUrl=" + this.contentSourceUrl + ", content=" + this.content + ", digest=" + this.digest + + ", showCoverPic=" + this.showCoverPic +", url=" + this.url + "]"; } } @Override public String toString() { - return "WxMpMaterialNews [" + "articles=" + articles + "]"; + return "WxMpMaterialNews [" + "articles=" + this.articles + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java index faf0ec7729..c17f38e99f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpSemanticQuery.java @@ -13,6 +13,10 @@ */ public class WxMpSemanticQuery implements Serializable { + /** + * + */ + private static final long serialVersionUID = 7685873048199870690L; private String query; private String category; private Float latitude; @@ -23,7 +27,7 @@ public class WxMpSemanticQuery implements Serializable { private String uid; public String getQuery() { - return query; + return this.query; } public void setQuery(String query) { @@ -31,7 +35,7 @@ public void setQuery(String query) { } public String getCategory() { - return category; + return this.category; } public void setCategory(String category) { @@ -39,7 +43,7 @@ public void setCategory(String category) { } public Float getLatitude() { - return latitude; + return this.latitude; } public void setLatitude(Float latitude) { @@ -47,7 +51,7 @@ public void setLatitude(Float latitude) { } public Float getLongitude() { - return longitude; + return this.longitude; } public void setLongitude(Float longitude) { @@ -55,7 +59,7 @@ public void setLongitude(Float longitude) { } public String getCity() { - return city; + return this.city; } public void setCity(String city) { @@ -63,7 +67,7 @@ public void setCity(String city) { } public String getRegion() { - return region; + return this.region; } public void setRegion(String region) { @@ -71,7 +75,7 @@ public void setRegion(String region) { } public String getAppid() { - return appid; + return this.appid; } public void setAppid(String appid) { @@ -79,7 +83,7 @@ public void setAppid(String appid) { } public String getUid() { - return uid; + return this.uid; } public void setUid(String uid) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java index 51d29e2861..ff83baa91b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateData.java @@ -7,6 +7,10 @@ */ public class WxMpTemplateData implements Serializable { + /** + * + */ + private static final long serialVersionUID = 6301835292940277870L; private String name; private String value; private String color; @@ -26,7 +30,7 @@ public WxMpTemplateData(String name, String value, String color) { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -34,7 +38,7 @@ public void setName(String name) { } public String getValue() { - return value; + return this.value; } public void setValue(String value) { @@ -42,7 +46,7 @@ public void setValue(String value) { } public String getColor() { - return color; + return this.color; } public void setColor(String color) { this.color = color; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java index dd822ba52e..eec25eda45 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpTemplateMessage.java @@ -8,14 +8,18 @@ public class WxMpTemplateMessage implements Serializable { + /** + * + */ + private static final long serialVersionUID = 5063374783759519418L; private String toUser; private String templateId; private String url; private String topColor; - private List data = new ArrayList(); + private List data = new ArrayList<>(); public String getToUser() { - return toUser; + return this.toUser; } public void setToUser(String toUser) { @@ -23,7 +27,7 @@ public void setToUser(String toUser) { } public String getTemplateId() { - return templateId; + return this.templateId; } public void setTemplateId(String templateId) { @@ -31,7 +35,7 @@ public void setTemplateId(String templateId) { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -39,7 +43,7 @@ public void setUrl(String url) { } public String getTopColor() { - return topColor; + return this.topColor; } public void setTopColor(String topColor) { @@ -47,7 +51,7 @@ public void setTopColor(String topColor) { } public List getData() { - return data; + return this.data; } public void setData(List data) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java new file mode 100644 index 0000000000..f16c004c55 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpUserQuery.java @@ -0,0 +1,192 @@ +package me.chanjar.weixin.mp.bean; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; + +/** + * 批量查询用户信息查询参数
    + * Created by LiuJunGuang on 2016/8/31. + * + * @author LiuJunGuang + */ +public class WxMpUserQuery { + private List queryParamList = new ArrayList<>(); + + public WxMpUserQuery() { + super(); + } + + /** + * 语言使用默认(zh_CN) + * + * @param openIdList + */ + public WxMpUserQuery(List openIdList) { + super(); + add(openIdList); + } + + /** + * 添加OpenId列表,语言使用默认(zh_CN) + * + * @param openIdList + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery add(List openIdList) { + for (String openId : openIdList) { + this.add(openId); + } + return this; + } + + /** + * 添加一个OpenId + * + * @param openId + * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery add(String openId, String lang) { + this.queryParamList.add(new WxMpUserQueryParam(openId, lang)); + return this; + } + + /** + * 添加一个OpenId到列表中,并返回本对象 + * + *
    +   * 该方法默认lang = zh_CN
    +   * 
    + * + * @param openId + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery add(String openId) { + this.queryParamList.add(new WxMpUserQueryParam(openId)); + return this; + } + + /** + * 删除指定的OpenId,语言使用默认(zh_CN) + * + * @param openId + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery remove(String openId) { + this.queryParamList.remove(new WxMpUserQueryParam(openId)); + return this; + } + + /** + * 删除指定的OpenId + * + * @param openId + * @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 + * @return {@link WxMpUserQuery} + */ + public WxMpUserQuery remove(String openId, String lang) { + this.queryParamList.remove(new WxMpUserQueryParam(openId, lang)); + return this; + } + + /** + * 获取查询参数列表 + * + */ + public List getQueryParamList() { + return this.queryParamList; + } + + public String toJsonString() { + Map map = new HashMap<>(); + map.put("user_list", this.queryParamList); + return new Gson().toJson(map); + } + + // 查询参数封装 + public class WxMpUserQueryParam implements Serializable { + /** + * @fields serialVersionUID + */ + private static final long serialVersionUID = -6863571795702385319L; + private String openid; + private String lang; + + public WxMpUserQueryParam(String openid, String lang) { + super(); + this.openid = openid; + this.lang = lang; + } + + public WxMpUserQueryParam(String openid) { + super(); + this.openid = openid; + this.lang = "zh_CN"; + } + + public WxMpUserQueryParam() { + super(); + } + + public String getOpenid() { + return this.openid; + } + + public void setOpenid(String openid) { + this.openid = openid; + } + + public String getLang() { + return this.lang; + } + + public void setLang(String lang) { + this.lang = lang; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + getOuterType().hashCode(); + result = prime * result + ((this.lang == null) ? 0 : this.lang.hashCode()); + result = prime * result + ((this.openid == null) ? 0 : this.openid.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + WxMpUserQueryParam other = (WxMpUserQueryParam) obj; + if (!getOuterType().equals(other.getOuterType())) + return false; + if (this.lang == null) { + if (other.lang != null) + return false; + } else if (!this.lang.equals(other.lang)) + return false; + if (this.openid == null) { + if (other.openid != null) + return false; + } else if (!this.openid.equals(other.openid)) + return false; + return true; + } + + private WxMpUserQuery getOuterType() { + return WxMpUserQuery.this; + } + + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutImageMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutImageMessage.java index 6f6510c256..18204a514e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutImageMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutImageMessage.java @@ -8,12 +8,16 @@ @XStreamAlias("xml") public class WxMpXmlOutImageMessage extends WxMpXmlOutMessage { + /** + * + */ + private static final long serialVersionUID = -2684778597067990723L; @XStreamAlias("Image") @XStreamConverter(value = XStreamMediaIdConverter.class) private String mediaId; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutMusicMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutMusicMessage.java index b6fefdac49..ec71167c45 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutMusicMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutMusicMessage.java @@ -8,6 +8,10 @@ @XStreamAlias("xml") public class WxMpXmlOutMusicMessage extends WxMpXmlOutMessage { + /** + * + */ + private static final long serialVersionUID = -4159937804975448945L; @XStreamAlias("Music") protected final Music music = new Music(); @@ -16,43 +20,43 @@ public WxMpXmlOutMusicMessage() { } public String getTitle() { - return music.getTitle(); + return this.music.getTitle(); } public void setTitle(String title) { - music.setTitle(title); + this.music.setTitle(title); } public String getDescription() { - return music.getDescription(); + return this.music.getDescription(); } public void setDescription(String description) { - music.setDescription(description); + this.music.setDescription(description); } public String getThumbMediaId() { - return music.getThumbMediaId(); + return this.music.getThumbMediaId(); } public void setThumbMediaId(String thumbMediaId) { - music.setThumbMediaId(thumbMediaId); + this.music.setThumbMediaId(thumbMediaId); } public String getMusicUrl() { - return music.getMusicUrl(); + return this.music.getMusicUrl(); } public void setMusicUrl(String musicUrl) { - music.setMusicUrl(musicUrl); + this.music.setMusicUrl(musicUrl); } public String getHqMusicUrl() { - return music.getHqMusicUrl(); + return this.music.getHqMusicUrl(); } public void setHqMusicUrl(String hqMusicUrl) { - music.setHqMusicUrl(hqMusicUrl); + this.music.setHqMusicUrl(hqMusicUrl); } @XStreamAlias("Music") @@ -79,7 +83,7 @@ public static class Music { private String hqMusicUrl; public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -87,7 +91,7 @@ public void setTitle(String title) { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { @@ -95,7 +99,7 @@ public void setDescription(String description) { } public String getThumbMediaId() { - return thumbMediaId; + return this.thumbMediaId; } public void setThumbMediaId(String thumbMediaId) { @@ -103,7 +107,7 @@ public void setThumbMediaId(String thumbMediaId) { } public String getMusicUrl() { - return musicUrl; + return this.musicUrl; } public void setMusicUrl(String musicUrl) { @@ -111,7 +115,7 @@ public void setMusicUrl(String musicUrl) { } public String getHqMusicUrl() { - return hqMusicUrl; + return this.hqMusicUrl; } public void setHqMusicUrl(String hqMusicUrl) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutNewsMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutNewsMessage.java index 4b76b4f5c3..170023a3cc 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutNewsMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutNewsMessage.java @@ -11,18 +11,23 @@ @XStreamAlias("xml") public class WxMpXmlOutNewsMessage extends WxMpXmlOutMessage { + /** + * + */ + private static final long serialVersionUID = -4604402850905714772L; + @XStreamAlias("ArticleCount") protected int articleCount; @XStreamAlias("Articles") - protected final List articles = new ArrayList(); + protected final List articles = new ArrayList<>(); public WxMpXmlOutNewsMessage() { this.msgType = WxConsts.XML_MSG_NEWS; } public int getArticleCount() { - return articleCount; + return this.articleCount; } public void addArticle(Item item) { @@ -31,7 +36,7 @@ public void addArticle(Item item) { } public List getArticles() { - return articles; + return this.articles; } @@ -55,35 +60,35 @@ public static class Item { private String Url; public String getTitle() { - return Title; + return this.Title; } public void setTitle(String title) { - Title = title; + this.Title = title; } public String getDescription() { - return Description; + return this.Description; } public void setDescription(String description) { - Description = description; + this.Description = description; } public String getPicUrl() { - return PicUrl; + return this.PicUrl; } public void setPicUrl(String picUrl) { - PicUrl = picUrl; + this.PicUrl = picUrl; } public String getUrl() { - return Url; + return this.Url; } public void setUrl(String url) { - Url = url; + this.Url = url; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutTextMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutTextMessage.java index e2458a032b..4c439a7c1a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutTextMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutTextMessage.java @@ -8,6 +8,10 @@ @XStreamAlias("xml") public class WxMpXmlOutTextMessage extends WxMpXmlOutMessage { + /** + * + */ + private static final long serialVersionUID = -3972786455288763361L; @XStreamAlias("Content") @XStreamConverter(value=XStreamCDataConverter.class) private String content; @@ -17,7 +21,7 @@ public WxMpXmlOutTextMessage() { } public String getContent() { - return content; + return this.content; } public void setContent(String content) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVideoMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVideoMessage.java index fb0520c1fc..a8f751cfcf 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVideoMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVideoMessage.java @@ -8,6 +8,10 @@ @XStreamAlias("xml") public class WxMpXmlOutVideoMessage extends WxMpXmlOutMessage { + /** + * + */ + private static final long serialVersionUID = 1745902309380113978L; @XStreamAlias("Video") protected final Video video = new Video(); @@ -16,27 +20,27 @@ public WxMpXmlOutVideoMessage() { } public String getMediaId() { - return video.getMediaId(); + return this.video.getMediaId(); } public void setMediaId(String mediaId) { - video.setMediaId(mediaId); + this.video.setMediaId(mediaId); } public String getTitle() { - return video.getTitle(); + return this.video.getTitle(); } public void setTitle(String title) { - video.setTitle(title); + this.video.setTitle(title); } public String getDescription() { - return video.getDescription(); + return this.video.getDescription(); } public void setDescription(String description) { - video.setDescription(description); + this.video.setDescription(description); } @@ -56,7 +60,7 @@ public static class Video { private String description; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -64,7 +68,7 @@ public void setMediaId(String mediaId) { } public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -72,7 +76,7 @@ public void setTitle(String title) { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVoiceMessage.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVoiceMessage.java index 29c74e9032..a47766dcd2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVoiceMessage.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/WxMpXmlOutVoiceMessage.java @@ -8,6 +8,10 @@ @XStreamAlias("xml") public class WxMpXmlOutVoiceMessage extends WxMpXmlOutMessage { + /** + * + */ + private static final long serialVersionUID = 240367390249860551L; @XStreamAlias("Voice") @XStreamConverter(value = XStreamMediaIdConverter.class) private String mediaId; @@ -17,7 +21,7 @@ public WxMpXmlOutVoiceMessage() { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/ImageBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/ImageBuilder.java index 1c37b46e73..1fb5363c4b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/ImageBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/ImageBuilder.java @@ -23,6 +23,7 @@ public ImageBuilder mediaId(String media_id) { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setMediaId(this.mediaId); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/MusicBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/MusicBuilder.java index 5c1abe388e..7a9994adbc 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/MusicBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/MusicBuilder.java @@ -52,13 +52,14 @@ public MusicBuilder thumbMediaId(String thumb_media_id) { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setMusicUrl(this.musicUrl); m.setHqMusicUrl(this.hqMusicUrl); - m.setTitle(title); - m.setDescription(description); - m.setThumbMediaId(thumbMediaId); + m.setTitle(this.title); + m.setDescription(this.description); + m.setThumbMediaId(this.thumbMediaId); return m; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/NewsBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/NewsBuilder.java index 825e72f896..ad0efb23b1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/NewsBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/NewsBuilder.java @@ -17,7 +17,7 @@ */ public final class NewsBuilder extends BaseBuilder { - private List articles = new ArrayList(); + private List articles = new ArrayList<>(); public NewsBuilder() { this.msgType = WxConsts.CUSTOM_MSG_NEWS; @@ -28,6 +28,7 @@ public NewsBuilder addArticle(WxMpCustomMessage.WxArticle article) { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setArticles(this.articles); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/TextBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/TextBuilder.java index 11249d6dc5..7f458457b2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/TextBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/TextBuilder.java @@ -23,6 +23,7 @@ public TextBuilder content(String content) { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setContent(this.content); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VideoBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VideoBuilder.java index a871d491be..bda6ef7c5b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VideoBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VideoBuilder.java @@ -47,12 +47,13 @@ public VideoBuilder thumbMediaId(String thumb_media_id) { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setMediaId(this.mediaId); - m.setTitle(title); - m.setDescription(description); - m.setThumbMediaId(thumbMediaId); + m.setTitle(this.title); + m.setDescription(this.description); + m.setThumbMediaId(this.thumbMediaId); return m; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VoiceBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VoiceBuilder.java index 3f81aeb092..867c8aff6f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VoiceBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/custombuilder/VoiceBuilder.java @@ -23,6 +23,7 @@ public VoiceBuilder mediaId(String media_id) { return this; } + @Override public WxMpCustomMessage build() { WxMpCustomMessage m = super.build(); m.setMediaId(this.mediaId); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java new file mode 100644 index 0000000000..ce1f4269a7 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleResult.java @@ -0,0 +1,207 @@ +package me.chanjar.weixin.mp.bean.datacube; + +import com.google.gson.annotations.SerializedName; + +/** + * 图文分析数据接口返回结果对象 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/8/24. + */ +public class WxDataCubeArticleResult extends WxDataCubeBaseResult { + + /** + * ref_hour + * 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 + */ + @SerializedName("ref_hour") + private Integer refHour; + + /** + * msgid + * 请注意:这里的msgid实际上是由msgid(图文消息id,这也就是群发接口调用后返回的msg_data_id)和index(消息次序索引)组成, 例如12003_3, 其中12003是msgid,即一次群发的消息的id; 3为index,假设该次群发的图文消息共5个文章(因为可能为多图文),3表示5个中的第3个 + */ + @SerializedName("msgid") + private String msgId; + + /** + * title + * 图文消息的标题 + */ + @SerializedName("title") + private String title; + + /** + * int_page_read_user + * 图文页(点击群发图文卡片进入的页面)的阅读人数 + */ + @SerializedName("int_page_read_user") + private Integer intPageReadUser; + + /** + * int_page_read_count + * 图文页的阅读次数 + */ + @SerializedName("int_page_read_count") + private Integer intPageReadCount; + + /** + * ori_page_read_user + * 原文页(点击图文页“阅读原文”进入的页面)的阅读人数,无原文页时此处数据为0 + */ + @SerializedName("ori_page_read_user") + private Integer oriPageReadUser; + + /** + * ori_page_read_count + * 原文页的阅读次数 + */ + @SerializedName("ori_page_read_count") + private Integer oriPageReadCount; + + /** + * share_scene + * 分享的场景 1代表好友转发 2代表朋友圈 3代表腾讯微博 255代表其他 + */ + @SerializedName("share_scene") + private Integer shareScene; + + /** + * share_user + * 分享的人数 + */ + @SerializedName("share_user") + private Integer shareUser; + + /** + * share_count + * 分享的次数 + */ + @SerializedName("share_count") + private Integer shareCount; + + /** + * add_to_fav_user + * 收藏的人数 + */ + @SerializedName("add_to_fav_user") + private Integer addToFavUser; + + /** + * add_to_fav_count + * 收藏的次数 + */ + @SerializedName("add_to_fav_count") + private Integer addToFavCount; + + /** + * user_source + * 在获取图文阅读分时数据时才有该字段,代表用户从哪里进入来阅读该图文。0:会话;1.好友;2.朋友圈;3.腾讯微博;4.历史消息页;5.其他 + */ + @SerializedName("user_source") + private Integer userSource; + + public Integer getRefHour() { + return this.refHour; + } + + public void setRefHour(Integer refHour) { + this.refHour = refHour; + } + + public String getMsgId() { + return this.msgId; + } + + public void setMsgId(String msgId) { + this.msgId = msgId; + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getIntPageReadUser() { + return this.intPageReadUser; + } + + public void setIntPageReadUser(Integer intPageReadUser) { + this.intPageReadUser = intPageReadUser; + } + + public Integer getIntPageReadCount() { + return this.intPageReadCount; + } + + public void setIntPageReadCount(Integer intPageReadCount) { + this.intPageReadCount = intPageReadCount; + } + + public Integer getOriPageReadUser() { + return this.oriPageReadUser; + } + + public void setOriPageReadUser(Integer oriPageReadUser) { + this.oriPageReadUser = oriPageReadUser; + } + + public Integer getOriPageReadCount() { + return this.oriPageReadCount; + } + + public void setOriPageReadCount(Integer oriPageReadCount) { + this.oriPageReadCount = oriPageReadCount; + } + + public Integer getShareScene() { + return this.shareScene; + } + + public void setShareScene(Integer shareScene) { + this.shareScene = shareScene; + } + + public Integer getShareUser() { + return this.shareUser; + } + + public void setShareUser(Integer shareUser) { + this.shareUser = shareUser; + } + + public Integer getShareCount() { + return this.shareCount; + } + + public void setShareCount(Integer shareCount) { + this.shareCount = shareCount; + } + + public Integer getAddToFavUser() { + return this.addToFavUser; + } + + public void setAddToFavUser(Integer addToFavUser) { + this.addToFavUser = addToFavUser; + } + + public Integer getAddToFavCount() { + return this.addToFavCount; + } + + public void setAddToFavCount(Integer addToFavCount) { + this.addToFavCount = addToFavCount; + } + + public Integer getUserSource() { + return this.userSource; + } + + public void setUserSource(Integer userSource) { + this.userSource = userSource; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java new file mode 100644 index 0000000000..1832f7344a --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotal.java @@ -0,0 +1,59 @@ +package me.chanjar.weixin.mp.bean.datacube; + +import com.google.gson.annotations.SerializedName; + +import java.util.List; + +/** + * 图文分析数据接口返回结果对象 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/8/24. + */ +public class WxDataCubeArticleTotal extends WxDataCubeBaseResult { + + /** + * msgid + * 请注意:这里的msgid实际上是由msgid(图文消息id,这也就是群发接口调用后返回的msg_data_id)和index(消息次序索引)组成, 例如12003_3, 其中12003是msgid,即一次群发的消息的id; 3为index,假设该次群发的图文消息共5个文章(因为可能为多图文),3表示5个中的第3个 + */ + @SerializedName("msgid") + private String msgId; + + /** + * title + * 图文消息的标题 + */ + @SerializedName("title") + private String title; + + /** + * details + * 详细信息 + */ + @SerializedName("details") + private List details; + + public String getMsgId() { + return this.msgId; + } + + public void setMsgId(String msgId) { + this.msgId = msgId; + } + + public String getTitle() { + return this.title; + } + + public void setTitle(String title) { + this.title = title; + } + + public List getDetails() { + return this.details; + } + + public void setDetails(List details) { + this.details = details; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java new file mode 100644 index 0000000000..cbbf148f3d --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeArticleTotalDetail.java @@ -0,0 +1,405 @@ +package me.chanjar.weixin.mp.bean.datacube; + +import com.google.gson.annotations.SerializedName; + +/** + * 获取图文群发总数据接口(getarticletotal)中的详细字段 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/8/24. + */ +public class WxDataCubeArticleTotalDetail { + + /** + * stat_date + * 统计的日期,在getarticletotal接口中,ref_date指的是文章群发出日期, 而stat_date是数据统计日期 + */ + @SerializedName("stat_date") + private Integer statDate; + + /** + * target_user + * 送达人数,一般约等于总粉丝数(需排除黑名单或其他异常情况下无法收到消息的粉丝) + */ + @SerializedName("target_user") + private Integer targetUser; + + /** + * int_page_read_user + * 图文页(点击群发图文卡片进入的页面)的阅读人数 + */ + @SerializedName("int_page_read_user") + private Integer intPageReadUser; + + /** + * int_page_read_count + * 图文页的阅读次数 + */ + @SerializedName("int_page_read_count") + private Integer intPageReadCount; + + /** + * ori_page_read_user + * 原文页(点击图文页“阅读原文”进入的页面)的阅读人数,无原文页时此处数据为0 + */ + @SerializedName("ori_page_read_user") + private Integer oriPageReadUser; + + /** + * ori_page_read_count + * 原文页的阅读次数 + */ + @SerializedName("ori_page_read_count") + private Integer oriPageReadCount; + + /** + * share_user + * 分享的人数 + */ + @SerializedName("share_user") + private Integer shareUser; + + /** + * share_count + * 分享的次数 + */ + @SerializedName("share_count") + private Integer shareCount; + + /** + * add_to_fav_user + * 收藏的人数 + */ + @SerializedName("add_to_fav_user") + private Integer addToFavUser; + + /** + * add_to_fav_count + * 收藏的次数 + */ + @SerializedName("add_to_fav_count") + private Integer addToFavCount; + + /** + * int_page_from_session_read_user + * 公众号会话阅读人数 + */ + @SerializedName("int_page_from_session_read_user") + private Integer intPageFromSessionReadUser; + + /** + * int_page_from_session_read_count + * 公众号会话阅读次数 + */ + @SerializedName("int_page_from_session_read_count") + private Integer intPageFromSessionReadCount; + + /** + * int_page_from_hist_msg_read_user + * 历史消息页阅读人数 + */ + @SerializedName("int_page_from_hist_msg_read_user") + private Integer intPageFromHistMsgReadUser; + + /** + * int_page_from_hist_msg_read_count + * 历史消息页阅读次数 + */ + @SerializedName("int_page_from_hist_msg_read_count") + private Integer intPageFromHistMsgReadCount; + + /** + * int_page_from_feed_read_user + * 朋友圈阅读人数 + */ + @SerializedName("int_page_from_feed_read_user") + private Integer intPageFromFeedReadUser; + + /** + * int_page_from_feed_read_count + * 朋友圈阅读次数 + */ + @SerializedName("int_page_from_feed_read_count") + private Integer intPageFromFeedReadCount; + + /** + * int_page_from_friends_read_user + * 好友转发阅读人数 + */ + @SerializedName("int_page_from_friends_read_user") + private Integer intPageFromFriendsReadUser; + + /** + * int_page_from_friends_read_count + * 好友转发阅读次数 + */ + @SerializedName("int_page_from_friends_read_count") + private Integer intPageFromFriendsReadCount; + + /** + * int_page_from_other_read_user + * 其他场景阅读人数 + */ + @SerializedName("int_page_from_other_read_user") + private Integer intPageFromOtherReadUser; + + /** + * int_page_from_other_read_count + * 其他场景阅读次数 + */ + @SerializedName("int_page_from_other_read_count") + private Integer intPageFromOtherReadCount; + + /** + * feed_share_from_session_user + * 公众号会话转发朋友圈人数 + */ + @SerializedName("feed_share_from_session_user") + private Integer feedShareFromSessionUser; + + /** + * feed_share_from_session_cnt + * 公众号会话转发朋友圈次数 + */ + @SerializedName("feed_share_from_session_cnt") + private Integer feedShareFromSessionCnt; + + /** + * feed_share_from_feed_user + * 朋友圈转发朋友圈人数 + */ + @SerializedName("feed_share_from_feed_user") + private Integer feedShareFromFeedUser; + + /** + * feed_share_from_feed_cnt + * 朋友圈转发朋友圈次数 + */ + @SerializedName("feed_share_from_feed_cnt") + private Integer feedShareFromFeedCnt; + + /** + * feed_share_from_other_user + * 其他场景转发朋友圈人数 + */ + @SerializedName("feed_share_from_other_user") + private Integer feedShareFromOtherUser; + + /** + * feed_share_from_other_cnt + * 其他场景转发朋友圈次数 + */ + @SerializedName("feed_share_from_other_cnt") + private Integer feedShareFromOtherCnt; + + public Integer getStatDate() { + return this.statDate; + } + + public void setStatDate(Integer statDate) { + this.statDate = statDate; + } + + public Integer getTargetUser() { + return this.targetUser; + } + + public void setTargetUser(Integer targetUser) { + this.targetUser = targetUser; + } + + public Integer getIntPageReadUser() { + return this.intPageReadUser; + } + + public void setIntPageReadUser(Integer intPageReadUser) { + this.intPageReadUser = intPageReadUser; + } + + public Integer getIntPageReadCount() { + return this.intPageReadCount; + } + + public void setIntPageReadCount(Integer intPageReadCount) { + this.intPageReadCount = intPageReadCount; + } + + public Integer getOriPageReadUser() { + return this.oriPageReadUser; + } + + public void setOriPageReadUser(Integer oriPageReadUser) { + this.oriPageReadUser = oriPageReadUser; + } + + public Integer getOriPageReadCount() { + return this.oriPageReadCount; + } + + public void setOriPageReadCount(Integer oriPageReadCount) { + this.oriPageReadCount = oriPageReadCount; + } + + public Integer getShareUser() { + return this.shareUser; + } + + public void setShareUser(Integer shareUser) { + this.shareUser = shareUser; + } + + public Integer getShareCount() { + return this.shareCount; + } + + public void setShareCount(Integer shareCount) { + this.shareCount = shareCount; + } + + public Integer getAddToFavUser() { + return this.addToFavUser; + } + + public void setAddToFavUser(Integer addToFavUser) { + this.addToFavUser = addToFavUser; + } + + public Integer getAddToFavCount() { + return this.addToFavCount; + } + + public void setAddToFavCount(Integer addToFavCount) { + this.addToFavCount = addToFavCount; + } + + public Integer getIntPageFromSessionReadUser() { + return this.intPageFromSessionReadUser; + } + + public void setIntPageFromSessionReadUser(Integer intPageFromSessionReadUser) { + this.intPageFromSessionReadUser = intPageFromSessionReadUser; + } + + public Integer getIntPageFromSessionReadCount() { + return this.intPageFromSessionReadCount; + } + + public void setIntPageFromSessionReadCount( + Integer intPageFromSessionReadCount) { + this.intPageFromSessionReadCount = intPageFromSessionReadCount; + } + + public Integer getIntPageFromHistMsgReadUser() { + return this.intPageFromHistMsgReadUser; + } + + public void setIntPageFromHistMsgReadUser(Integer intPageFromHistMsgReadUser) { + this.intPageFromHistMsgReadUser = intPageFromHistMsgReadUser; + } + + public Integer getIntPageFromHistMsgReadCount() { + return this.intPageFromHistMsgReadCount; + } + + public void setIntPageFromHistMsgReadCount( + Integer intPageFromHistMsgReadCount) { + this.intPageFromHistMsgReadCount = intPageFromHistMsgReadCount; + } + + public Integer getIntPageFromFeedReadUser() { + return this.intPageFromFeedReadUser; + } + + public void setIntPageFromFeedReadUser(Integer intPageFromFeedReadUser) { + this.intPageFromFeedReadUser = intPageFromFeedReadUser; + } + + public Integer getIntPageFromFeedReadCount() { + return this.intPageFromFeedReadCount; + } + + public void setIntPageFromFeedReadCount(Integer intPageFromFeedReadCount) { + this.intPageFromFeedReadCount = intPageFromFeedReadCount; + } + + public Integer getIntPageFromFriendsReadUser() { + return this.intPageFromFriendsReadUser; + } + + public void setIntPageFromFriendsReadUser(Integer intPageFromFriendsReadUser) { + this.intPageFromFriendsReadUser = intPageFromFriendsReadUser; + } + + public Integer getIntPageFromFriendsReadCount() { + return this.intPageFromFriendsReadCount; + } + + public void setIntPageFromFriendsReadCount( + Integer intPageFromFriendsReadCount) { + this.intPageFromFriendsReadCount = intPageFromFriendsReadCount; + } + + public Integer getIntPageFromOtherReadUser() { + return this.intPageFromOtherReadUser; + } + + public void setIntPageFromOtherReadUser(Integer intPageFromOtherReadUser) { + this.intPageFromOtherReadUser = intPageFromOtherReadUser; + } + + public Integer getIntPageFromOtherReadCount() { + return this.intPageFromOtherReadCount; + } + + public void setIntPageFromOtherReadCount(Integer intPageFromOtherReadCount) { + this.intPageFromOtherReadCount = intPageFromOtherReadCount; + } + + public Integer getFeedShareFromSessionUser() { + return this.feedShareFromSessionUser; + } + + public void setFeedShareFromSessionUser(Integer feedShareFromSessionUser) { + this.feedShareFromSessionUser = feedShareFromSessionUser; + } + + public Integer getFeedShareFromSessionCnt() { + return this.feedShareFromSessionCnt; + } + + public void setFeedShareFromSessionCnt(Integer feedShareFromSessionCnt) { + this.feedShareFromSessionCnt = feedShareFromSessionCnt; + } + + public Integer getFeedShareFromFeedUser() { + return this.feedShareFromFeedUser; + } + + public void setFeedShareFromFeedUser(Integer feedShareFromFeedUser) { + this.feedShareFromFeedUser = feedShareFromFeedUser; + } + + public Integer getFeedShareFromFeedCnt() { + return this.feedShareFromFeedCnt; + } + + public void setFeedShareFromFeedCnt(Integer feedShareFromFeedCnt) { + this.feedShareFromFeedCnt = feedShareFromFeedCnt; + } + + public Integer getFeedShareFromOtherUser() { + return this.feedShareFromOtherUser; + } + + public void setFeedShareFromOtherUser(Integer feedShareFromOtherUser) { + this.feedShareFromOtherUser = feedShareFromOtherUser; + } + + public Integer getFeedShareFromOtherCnt() { + return this.feedShareFromOtherCnt; + } + + public void setFeedShareFromOtherCnt(Integer feedShareFromOtherCnt) { + this.feedShareFromOtherCnt = feedShareFromOtherCnt; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java new file mode 100644 index 0000000000..f819ab4299 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeBaseResult.java @@ -0,0 +1,33 @@ +package me.chanjar.weixin.mp.bean.datacube; + +import com.google.gson.annotations.SerializedName; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 统计接口的共用属性类 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/8/25. + */ +public class WxDataCubeBaseResult { + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); + } + + /** + * ref_date + * 数据的日期,需在begin_date和end_date之间 + */ + @SerializedName("ref_date") + private String refDate; + + public String getRefDate() { + return this.refDate; + } + + public void setRefDate(String refDate) { + this.refDate = refDate; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java new file mode 100644 index 0000000000..4abbe27793 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeInterfaceResult.java @@ -0,0 +1,87 @@ +package me.chanjar.weixin.mp.bean.datacube; + +import com.google.gson.annotations.SerializedName; + +/** + * 接口分析数据接口返回结果对象 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/8/30. + */ +public class WxDataCubeInterfaceResult extends WxDataCubeBaseResult { + + /** + * ref_hour + * 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 + */ + @SerializedName("ref_hour") + private Integer refHour; + + /** + * callback_count + * 通过服务器配置地址获得消息后,被动回复用户消息的次数 + */ + @SerializedName("callback_count") + private Integer callbackCount; + + /** + * fail_count + * 上述动作的失败次数 + */ + @SerializedName("fail_count") + private Integer failCount; + + /** + * total_time_cost + * 总耗时,除以callback_count即为平均耗时 + */ + @SerializedName("total_time_cost") + private Integer totalTimeCost; + + /** + * max_time_cost + * 最大耗时 + */ + @SerializedName("max_time_cost") + private Integer maxTimeCost; + + public Integer getRefHour() { + return this.refHour; + } + + public void setRefHour(Integer refHour) { + this.refHour = refHour; + } + + public Integer getCallbackCount() { + return this.callbackCount; + } + + public void setCallbackCount(Integer callbackCount) { + this.callbackCount = callbackCount; + } + + public Integer getFailCount() { + return this.failCount; + } + + public void setFailCount(Integer failCount) { + this.failCount = failCount; + } + + public Integer getTotalTimeCost() { + return this.totalTimeCost; + } + + public void setTotalTimeCost(Integer totalTimeCost) { + this.totalTimeCost = totalTimeCost; + } + + public Integer getMaxTimeCost() { + return this.maxTimeCost; + } + + public void setMaxTimeCost(Integer maxTimeCost) { + this.maxTimeCost = maxTimeCost; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java new file mode 100644 index 0000000000..bbeb3b3697 --- /dev/null +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeMsgResult.java @@ -0,0 +1,117 @@ +package me.chanjar.weixin.mp.bean.datacube; + +import com.google.gson.annotations.SerializedName; + +/** + * 消息分析数据接口返回结果对象 + * @author binarywang(https://github.com/binarywang) + * Created by Binary Wang on 2016/8/29. + */ +public class WxDataCubeMsgResult extends WxDataCubeBaseResult { + + /** + * ref_hour + * 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 + */ + @SerializedName("ref_hour") + private Integer refHour; + + /** + * msg_type + * 消息类型,代表含义如下:1代表文字 2代表图片 3代表语音 4代表视频 6代表第三方应用消息(链接消息) + */ + @SerializedName("msg_type") + private Integer msgType; + + /** + * msg_user + * 上行发送了(向公众号发送了)消息的用户数 + */ + @SerializedName("msg_user") + private Integer msgUser; + + /** + * msg_count + * 上行发送了消息的消息总数 + */ + @SerializedName("msg_count") + private Integer msgCount; + + /** + * count_interval + * 当日发送消息量分布的区间,0代表 “0”,1代表“1-5”,2代表“6-10”,3代表“10次以上” + */ + @SerializedName("count_interval") + private Integer countInterval; + + /** + * int_page_read_count + * 图文页的阅读次数 + */ + @SerializedName("int_page_read_count") + private Integer intPageReadCount; + + /** + * ori_page_read_user + * 原文页(点击图文页“阅读原文”进入的页面)的阅读人数,无原文页时此处数据为0 + */ + @SerializedName("ori_page_read_user") + private Integer oriPageReadUser; + + public Integer getRefHour() { + return this.refHour; + } + + public void setRefHour(Integer refHour) { + this.refHour = refHour; + } + + public Integer getMsgType() { + return this.msgType; + } + + public void setMsgType(Integer msgType) { + this.msgType = msgType; + } + + public Integer getMsgUser() { + return this.msgUser; + } + + public void setMsgUser(Integer msgUser) { + this.msgUser = msgUser; + } + + public Integer getMsgCount() { + return this.msgCount; + } + + public void setMsgCount(Integer msgCount) { + this.msgCount = msgCount; + } + + public Integer getCountInterval() { + return this.countInterval; + } + + public void setCountInterval(Integer countInterval) { + this.countInterval = countInterval; + } + + public Integer getIntPageReadCount() { + return this.intPageReadCount; + } + + public void setIntPageReadCount(Integer intPageReadCount) { + this.intPageReadCount = intPageReadCount; + } + + public Integer getOriPageReadUser() { + return this.oriPageReadUser; + } + + public void setOriPageReadUser(Integer oriPageReadUser) { + this.oriPageReadUser = oriPageReadUser; + } + +} diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserCumulate.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java similarity index 56% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserCumulate.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java index 4c295c4189..7192cfb481 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserCumulate.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserCumulate.java @@ -1,4 +1,7 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.datacube; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; import java.util.Date; @@ -9,14 +12,16 @@ * http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html *
    */ -public class WxMpUserCumulate implements Serializable { +public class WxDataCubeUserCumulate implements Serializable { + + private static final long serialVersionUID = -3570981300225093657L; private Date refDate; private Integer cumulateUser; public Date getRefDate() { - return refDate; + return this.refDate; } public void setRefDate(Date refDate) { @@ -24,7 +29,7 @@ public void setRefDate(Date refDate) { } public Integer getCumulateUser() { - return cumulateUser; + return this.cumulateUser; } public void setCumulateUser(Integer cumulateUser) { @@ -33,9 +38,6 @@ public void setCumulateUser(Integer cumulateUser) { @Override public String toString() { - return "WxMpUserCumulate{" + - "refDate=" + refDate + - ", cumulateUser=" + cumulateUser + - '}'; + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserSummary.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java similarity index 64% rename from weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserSummary.java rename to weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java index de61a80bfd..cfb418425e 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserSummary.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/datacube/WxDataCubeUserSummary.java @@ -1,4 +1,7 @@ -package me.chanjar.weixin.mp.bean.result; +package me.chanjar.weixin.mp.bean.datacube; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; import java.io.Serializable; import java.util.Date; @@ -9,7 +12,8 @@ * http://mp.weixin.qq.com/wiki/3/ecfed6e1a0a03b5f35e5efac98e864b7.html *
    */ -public class WxMpUserSummary implements Serializable { +public class WxDataCubeUserSummary implements Serializable { + private static final long serialVersionUID = -2336654489906694173L; private Date refDate; @@ -20,7 +24,7 @@ public class WxMpUserSummary implements Serializable { private Integer cancelUser; public Date getRefDate() { - return refDate; + return this.refDate; } public void setRefDate(Date refDate) { @@ -28,7 +32,7 @@ public void setRefDate(Date refDate) { } public Integer getUserSource() { - return userSource; + return this.userSource; } public void setUserSource(Integer userSource) { @@ -36,7 +40,7 @@ public void setUserSource(Integer userSource) { } public Integer getNewUser() { - return newUser; + return this.newUser; } public void setNewUser(Integer newUser) { @@ -44,7 +48,7 @@ public void setNewUser(Integer newUser) { } public Integer getCancelUser() { - return cancelUser; + return this.cancelUser; } public void setCancelUser(Integer cancelUser) { @@ -53,11 +57,6 @@ public void setCancelUser(Integer cancelUser) { @Override public String toString() { - return "WxMpUserSummary{" + - "refDate=" + refDate + - ", userSource=" + userSource + - ", newUser=" + newUser + - ", cancelUser=" + cancelUser + - '}'; + return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java index 5078a2e5cf..570f2defc1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgList.java @@ -21,7 +21,7 @@ public class WxMpKfMsgList { private Long msgId; public List getRecords() { - return records; + return this.records; } public void setRecords(List records) { @@ -29,7 +29,7 @@ public void setRecords(List records) { } public Integer getNumber() { - return number; + return this.number; } public void setNumber(Integer number) { @@ -37,7 +37,7 @@ public void setNumber(Integer number) { } public Long getMsgId() { - return msgId; + return this.msgId; } public void setMsgId(Long msgId) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java index 00b7771e5a..3fe2002c99 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfMsgRecord.java @@ -46,7 +46,7 @@ public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE); } public String getWorker() { - return worker; + return this.worker; } public void setWorker(String worker) { @@ -54,7 +54,7 @@ public void setWorker(String worker) { } public String getOpenid() { - return openid; + return this.openid; } public void setOpenid(String openid) { @@ -62,7 +62,7 @@ public void setOpenid(String openid) { } public String getText() { - return text; + return this.text; } public void setText(String text) { @@ -70,7 +70,7 @@ public void setText(String text) { } public Long getTime() { - return time; + return this.time; } public void setTime(Long time) { @@ -78,7 +78,7 @@ public void setTime(Long time) { } public Integer getOperateCode() { - return operateCode; + return this.operateCode; } public void setOperateCode(Integer operateCode) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/ImageBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/ImageBuilder.java index e263e57fed..ee265bf3c5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/ImageBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/ImageBuilder.java @@ -15,6 +15,7 @@ public ImageBuilder mediaId(String media_id) { return this; } + @Override public WxMpXmlOutImageMessage build() { WxMpXmlOutImageMessage m = new WxMpXmlOutImageMessage(); setCommon(m); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/MusicBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/MusicBuilder.java index 0276e8cc93..6a0ee1bcdc 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/MusicBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/MusicBuilder.java @@ -40,14 +40,15 @@ public MusicBuilder thumbMediaId(String thumbMediaId) { return this; } + @Override public WxMpXmlOutMusicMessage build() { WxMpXmlOutMusicMessage m = new WxMpXmlOutMusicMessage(); setCommon(m); - m.setTitle(title); - m.setDescription(description); - m.setHqMusicUrl(hqMusicUrl); - m.setMusicUrl(musicUrl); - m.setThumbMediaId(thumbMediaId); + m.setTitle(this.title); + m.setDescription(this.description); + m.setHqMusicUrl(this.hqMusicUrl); + m.setMusicUrl(this.musicUrl); + m.setThumbMediaId(this.thumbMediaId); return m; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/NewsBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/NewsBuilder.java index 6f2258254e..1014c452c8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/NewsBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/NewsBuilder.java @@ -11,16 +11,17 @@ */ public final class NewsBuilder extends BaseBuilder { - protected final List articles = new ArrayList(); + protected final List articles = new ArrayList<>(); public NewsBuilder addArticle(WxMpXmlOutNewsMessage.Item item) { this.articles.add(item); return this; } + @Override public WxMpXmlOutNewsMessage build() { WxMpXmlOutNewsMessage m = new WxMpXmlOutNewsMessage(); - for(WxMpXmlOutNewsMessage.Item item : articles) { + for(WxMpXmlOutNewsMessage.Item item : this.articles) { m.addArticle(item); } setCommon(m); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/TextBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/TextBuilder.java index 8352ddead9..f8075e4441 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/TextBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/TextBuilder.java @@ -15,6 +15,7 @@ public TextBuilder content(String content) { return this; } + @Override public WxMpXmlOutTextMessage build() { WxMpXmlOutTextMessage m = new WxMpXmlOutTextMessage(); setCommon(m); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VideoBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VideoBuilder.java index 9bb5fe3622..1690725c03 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VideoBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VideoBuilder.java @@ -26,12 +26,13 @@ public VideoBuilder mediaId(String mediaId) { return this; } + @Override public WxMpXmlOutVideoMessage build() { WxMpXmlOutVideoMessage m = new WxMpXmlOutVideoMessage(); setCommon(m); - m.setTitle(title); - m.setDescription(description); - m.setMediaId(mediaId); + m.setTitle(this.title); + m.setDescription(this.description); + m.setMediaId(this.mediaId); return m; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VoiceBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VoiceBuilder.java index d0a52ae585..f4c340e376 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VoiceBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/outxmlbuilder/VoiceBuilder.java @@ -15,10 +15,11 @@ public VoiceBuilder mediaId(String mediaId) { return this; } + @Override public WxMpXmlOutVoiceMessage build() { WxMpXmlOutVoiceMessage m = new WxMpXmlOutVoiceMessage(); setCommon(m); - m.setMediaId(mediaId); + m.setMediaId(this.mediaId); return m; } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMediaImgUploadResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMediaImgUploadResult.java index 3e5ff6b2fd..58ff57a3cb 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMediaImgUploadResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMediaImgUploadResult.java @@ -8,6 +8,10 @@ * @author miller */ public class WxMediaImgUploadResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1996392453428768829L; private String url; public static WxMediaImgUploadResult fromJson(String json) { @@ -15,7 +19,7 @@ public static WxMediaImgUploadResult fromJson(String json) { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpCardResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpCardResult.java index 4f2e99798e..8ce5ca47ae 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpCardResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpCardResult.java @@ -14,6 +14,11 @@ */ public class WxMpCardResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -7950878428289035637L; + private String errorCode; private String errorMsg; @@ -27,7 +32,7 @@ public class WxMpCardResult implements Serializable { private Boolean canConsume; public String getErrorCode() { - return errorCode; + return this.errorCode; } public void setErrorCode(String errorCode) { @@ -35,7 +40,7 @@ public void setErrorCode(String errorCode) { } public String getErrorMsg() { - return errorMsg; + return this.errorMsg; } public void setErrorMsg(String errorMsg) { @@ -43,7 +48,7 @@ public void setErrorMsg(String errorMsg) { } public String getOpenId() { - return openId; + return this.openId; } public void setOpenId(String openId) { @@ -51,7 +56,7 @@ public void setOpenId(String openId) { } public WxMpCard getCard() { - return card; + return this.card; } public void setCard(WxMpCard card) { @@ -64,7 +69,7 @@ public String toString() { } public String getUserCardStatus() { - return userCardStatus; + return this.userCardStatus; } public void setUserCardStatus(String userCardStatus) { @@ -72,7 +77,7 @@ public void setUserCardStatus(String userCardStatus) { } public Boolean getCanConsume() { - return canConsume; + return this.canConsume; } public void setCanConsume(Boolean canConsume) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java index dd12a53a98..0e9a158d7d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassSendResult.java @@ -17,13 +17,17 @@ */ public class WxMpMassSendResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -4816336807575562818L; private String errorCode; private String errorMsg; private String msgId; private String msgDataId; public String getErrorCode() { - return errorCode; + return this.errorCode; } public void setErrorCode(String errorCode) { @@ -31,7 +35,7 @@ public void setErrorCode(String errorCode) { } public String getErrorMsg() { - return errorMsg; + return this.errorMsg; } public void setErrorMsg(String errorMsg) { @@ -39,7 +43,7 @@ public void setErrorMsg(String errorMsg) { } public String getMsgId() { - return msgId; + return this.msgId; } public void setMsgId(String msgId) { @@ -47,7 +51,7 @@ public void setMsgId(String msgId) { } public String getMsgDataId() { - return msgDataId; + return this.msgDataId; } public void setMsgDataId(String msgDataId) { @@ -60,7 +64,7 @@ public static WxMpMassSendResult fromJson(String json) { @Override public String toString() { - return "WxMassSendResult [errcode=" + errorCode + ", errmsg=" + errorMsg + ", msg_id=" + msgId + "]"; + return "WxMassSendResult [errcode=" + this.errorCode + ", errmsg=" + this.errorMsg + ", msg_id=" + this.msgId + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java index 7100c63058..6a4f88d804 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMassUploadResult.java @@ -14,12 +14,16 @@ */ public class WxMpMassUploadResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = 6568157943644994029L; private String type; private String mediaId; private long createdAt; public String getType() { - return type; + return this.type; } public void setType(String type) { @@ -27,7 +31,7 @@ public void setType(String type) { } public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -35,7 +39,7 @@ public void setMediaId(String mediaId) { } public long getCreatedAt() { - return createdAt; + return this.createdAt; } public void setCreatedAt(long createdAt) { @@ -48,7 +52,7 @@ public static WxMpMassUploadResult fromJson(String json) { @Override public String toString() { - return "WxUploadResult [type=" + type + ", media_id=" + mediaId + ", created_at=" + createdAt + "]"; + return "WxUploadResult [type=" + this.type + ", media_id=" + this.mediaId + ", created_at=" + this.createdAt + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java index 83bb720d4b..94e20d50b2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialCountResult.java @@ -4,13 +4,17 @@ public class WxMpMaterialCountResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -5568772662085874138L; private int voiceCount; private int videoCount; private int imageCount; private int newsCount; public int getVoiceCount() { - return voiceCount; + return this.voiceCount; } public void setVoiceCount(int voiceCount) { @@ -18,7 +22,7 @@ public void setVoiceCount(int voiceCount) { } public int getVideoCount() { - return videoCount; + return this.videoCount; } public void setVideoCount(int videoCount) { @@ -26,7 +30,7 @@ public void setVideoCount(int videoCount) { } public int getImageCount() { - return imageCount; + return this.imageCount; } public void setImageCount(int imageCount) { @@ -34,7 +38,7 @@ public void setImageCount(int imageCount) { } public int getNewsCount() { - return newsCount; + return this.newsCount; } public void setNewsCount(int newsCount) { @@ -43,8 +47,8 @@ public void setNewsCount(int newsCount) { @Override public String toString() { - return "WxMpMaterialCountResult [" + "voiceCount=" + voiceCount + ", videoCount=" + videoCount - + ", imageCount=" + imageCount + ", newsCount=" + newsCount + "]"; + return "WxMpMaterialCountResult [" + "voiceCount=" + this.voiceCount + ", videoCount=" + this.videoCount + + ", imageCount=" + this.imageCount + ", newsCount=" + this.newsCount + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java index b47b15a78a..40eaecc114 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialFileBatchGetResult.java @@ -6,12 +6,16 @@ public class WxMpMaterialFileBatchGetResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -560388368297267884L; private int totalCount; private int itemCount; private List items; public int getTotalCount() { - return totalCount; + return this.totalCount; } public void setTotalCount(int totalCount) { @@ -19,7 +23,7 @@ public void setTotalCount(int totalCount) { } public int getItemCount() { - return itemCount; + return this.itemCount; } public void setItemCount(int itemCount) { @@ -27,7 +31,7 @@ public void setItemCount(int itemCount) { } public List getItems() { - return items; + return this.items; } public void setItems(List items) { @@ -36,7 +40,7 @@ public void setItems(List items) { @Override public String toString() { - return "WxMpMaterialFileBatchGetResult [" + "totalCount=" + totalCount + ", itemCount=" + itemCount + ", items=" + items + "]"; + return "WxMpMaterialFileBatchGetResult [" + "totalCount=" + this.totalCount + ", itemCount=" + this.itemCount + ", items=" + this.items + "]"; } public static class WxMaterialFileBatchGetNewsItem { @@ -46,7 +50,7 @@ public static class WxMaterialFileBatchGetNewsItem { private String url; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -54,7 +58,7 @@ public void setMediaId(String mediaId) { } public Date getUpdateTime() { - return updateTime; + return this.updateTime; } public void setUpdateTime(Date updateTime) { @@ -62,7 +66,7 @@ public void setUpdateTime(Date updateTime) { } public String getName() { - return name; + return this.name; } public void setName(String name) { @@ -70,7 +74,7 @@ public void setName(String name) { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -79,7 +83,7 @@ public void setUrl(String url) { @Override public String toString() { - return "WxMaterialFileBatchGetNewsItem [" + "mediaId=" + mediaId + ", updateTime=" + updateTime + ", name=" + name + ", url=" + url + "]"; + return "WxMaterialFileBatchGetNewsItem [" + "mediaId=" + this.mediaId + ", updateTime=" + this.updateTime + ", name=" + this.name + ", url=" + this.url + "]"; } } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java index 2d78ab8cfd..4856324480 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialNewsBatchGetResult.java @@ -8,12 +8,16 @@ public class WxMpMaterialNewsBatchGetResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1617952797921001666L; private int totalCount; private int itemCount; private List items; public int getTotalCount() { - return totalCount; + return this.totalCount; } public void setTotalCount(int totalCount) { @@ -21,7 +25,7 @@ public void setTotalCount(int totalCount) { } public int getItemCount() { - return itemCount; + return this.itemCount; } public void setItemCount(int itemCount) { @@ -29,7 +33,7 @@ public void setItemCount(int itemCount) { } public List getItems() { - return items; + return this.items; } public void setItems(List items) { @@ -38,7 +42,7 @@ public void setItems(List items) { @Override public String toString() { - return "WxMpMaterialNewsBatchGetResult [" + "totalCount=" + totalCount + ", itemCount=" + itemCount + ", items=" + items + "]"; + return "WxMpMaterialNewsBatchGetResult [" + "totalCount=" + this.totalCount + ", itemCount=" + this.itemCount + ", items=" + this.items + "]"; } public static class WxMaterialNewsBatchGetNewsItem { @@ -47,7 +51,7 @@ public static class WxMaterialNewsBatchGetNewsItem { private WxMpMaterialNews content; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -55,7 +59,7 @@ public void setMediaId(String mediaId) { } public Date getUpdateTime() { - return updateTime; + return this.updateTime; } public void setUpdateTime(Date updateTime) { @@ -63,7 +67,7 @@ public void setUpdateTime(Date updateTime) { } public WxMpMaterialNews getContent() { - return content; + return this.content; } public void setContent(WxMpMaterialNews content) { @@ -72,7 +76,7 @@ public void setContent(WxMpMaterialNews content) { @Override public String toString() { - return "WxMaterialNewsBatchGetNewsItem [" + "mediaId=" + mediaId + ", updateTime=" + updateTime + ", content=" + content + "]"; + return "WxMaterialNewsBatchGetNewsItem [" + "mediaId=" + this.mediaId + ", updateTime=" + this.updateTime + ", content=" + this.content + "]"; } } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java index 2c2bf4d6e0..cb9cecd1b1 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialUploadResult.java @@ -6,11 +6,15 @@ public class WxMpMaterialUploadResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -128818731449449537L; private String mediaId; private String url; public String getMediaId() { - return mediaId; + return this.mediaId; } public void setMediaId(String mediaId) { @@ -18,7 +22,7 @@ public void setMediaId(String mediaId) { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { @@ -31,7 +35,7 @@ public static WxMpMaterialUploadResult fromJson(String json) { @Override public String toString() { - return "WxMpMaterialUploadResult [media_id=" + mediaId + ", url=" + url + "]"; + return "WxMpMaterialUploadResult [media_id=" + this.mediaId + ", url=" + this.url + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java index 1650c760e6..456544d132 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpMaterialVideoInfoResult.java @@ -6,12 +6,16 @@ public class WxMpMaterialVideoInfoResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1269131745333792202L; private String title; private String description; private String downUrl; public String getTitle() { - return title; + return this.title; } public void setTitle(String title) { @@ -19,7 +23,7 @@ public void setTitle(String title) { } public String getDescription() { - return description; + return this.description; } public void setDescription(String description) { @@ -27,7 +31,7 @@ public void setDescription(String description) { } public String getDownUrl() { - return downUrl; + return this.downUrl; } public void setDownUrl(String downUrl) { @@ -40,7 +44,7 @@ public static WxMpMaterialVideoInfoResult fromJson(String json) { @Override public String toString() { - return "WxMpMaterialVideoInfoResult [title=" + title + ", description=" + description + ", downUrl=" + downUrl + "]"; + return "WxMpMaterialVideoInfoResult [title=" + this.title + ", description=" + this.description + ", downUrl=" + this.downUrl + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java index 6ac77c83ce..d38317ce8f 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpOAuth2AccessToken.java @@ -6,6 +6,11 @@ public class WxMpOAuth2AccessToken implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1345910558078620805L; + private String accessToken; private int expiresIn = -1; @@ -19,7 +24,7 @@ public class WxMpOAuth2AccessToken implements Serializable { private String unionId; public String getRefreshToken() { - return refreshToken; + return this.refreshToken; } public void setRefreshToken(String refreshToken) { @@ -27,7 +32,7 @@ public void setRefreshToken(String refreshToken) { } public String getOpenId() { - return openId; + return this.openId; } public void setOpenId(String openId) { @@ -35,7 +40,7 @@ public void setOpenId(String openId) { } public String getScope() { - return scope; + return this.scope; } public void setScope(String scope) { @@ -43,7 +48,7 @@ public void setScope(String scope) { } public String getAccessToken() { - return accessToken; + return this.accessToken; } public void setAccessToken(String accessToken) { @@ -51,7 +56,7 @@ public void setAccessToken(String accessToken) { } public int getExpiresIn() { - return expiresIn; + return this.expiresIn; } public void setExpiresIn(int expiresIn) { @@ -59,7 +64,7 @@ public void setExpiresIn(int expiresIn) { } public String getUnionId() { - return unionId; + return this.unionId; } public void setUnionId(String unionId) { @@ -73,12 +78,12 @@ public static WxMpOAuth2AccessToken fromJson(String json) { @Override public String toString() { return "WxMpOAuth2AccessToken{" + - "accessToken='" + accessToken + '\'' + - ", expiresTime=" + expiresIn + - ", refreshToken='" + refreshToken + '\'' + - ", openId='" + openId + '\'' + - ", scope='" + scope + '\'' + - ", unionId='" + unionId + '\'' + + "accessToken='" + this.accessToken + '\'' + + ", expiresTime=" + this.expiresIn + + ", refreshToken='" + this.refreshToken + '\'' + + ", openId='" + this.openId + '\'' + + ", scope='" + this.scope + '\'' + + ", unionId='" + this.unionId + '\'' + '}'; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java index 18aeda4d58..6e96f5e238 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayCallback.java @@ -12,6 +12,10 @@ * @author ukid */ public class WxMpPayCallback implements Serializable { + /** + * + */ + private static final long serialVersionUID = -4143804055690843641L; private String return_code; private String return_msg; @@ -42,111 +46,111 @@ public class WxMpPayCallback implements Serializable { private String time_end; public String getReturn_code() { - return return_code; + return this.return_code; } public String getReturn_msg() { - return return_msg; + return this.return_msg; } public String getAppid() { - return appid; + return this.appid; } public String getMch_id() { - return mch_id; + return this.mch_id; } public String getDevice_info() { - return device_info; + return this.device_info; } public String getNonce_str() { - return nonce_str; + return this.nonce_str; } public String getSign() { - return sign; + return this.sign; } public String getResult_code() { - return result_code; + return this.result_code; } public String getErr_code() { - return err_code; + return this.err_code; } public String getErr_code_des() { - return err_code_des; + return this.err_code_des; } public String getOpenid() { - return openid; + return this.openid; } public String getIs_subscribe() { - return is_subscribe; + return this.is_subscribe; } public String getTrade_type() { - return trade_type; + return this.trade_type; } public String getBank_type() { - return bank_type; + return this.bank_type; } public String getTotal_fee() { - return total_fee; + return this.total_fee; } public String getFee_type() { - return fee_type; + return this.fee_type; } public String getCash_fee() { - return cash_fee; + return this.cash_fee; } public String getCash_fee_type() { - return cash_fee_type; + return this.cash_fee_type; } public String getCoupon_fee() { - return coupon_fee; + return this.coupon_fee; } public String getCoupon_count() { - return coupon_count; + return this.coupon_count; } public String getCoupon_batch_id_$n() { - return coupon_batch_id_$n; + return this.coupon_batch_id_$n; } public String getCoupon_id_$n() { - return coupon_id_$n; + return this.coupon_id_$n; } public String getCoupon_fee_$n() { - return coupon_fee_$n; + return this.coupon_fee_$n; } public String getTransaction_id() { - return transaction_id; + return this.transaction_id; } public String getOut_trade_no() { - return out_trade_no; + return this.out_trade_no; } public String getAttach() { - return attach; + return this.attach; } public String getTime_end() { - return time_end; + return this.time_end; } public void setReturn_code(String return_code) { @@ -259,21 +263,21 @@ public void setTime_end(String time_end) { @Override public String toString() { - return "WxMpPayCallback [return_code=" + return_code + ", return_msg=" - + return_msg + ", appid=" + appid + ", mch_id=" + mch_id - + ", device_info=" + device_info + ", nonce_str=" + nonce_str - + ", sign=" + sign + ", result_code=" + result_code - + ", err_code=" + err_code + ", err_code_des=" + err_code_des - + ", openid=" + openid + ", is_subscribe=" + is_subscribe - + ", trade_type=" + trade_type + ", bank_type=" + bank_type - + ", total_fee=" + total_fee + ", fee_type=" + fee_type - + ", cash_fee=" + cash_fee + ", cash_fee_type=" + cash_fee_type - + ", coupon_fee=" + coupon_fee + ", coupon_count=" - + coupon_count + ", coupon_batch_id_$n=" + coupon_batch_id_$n - + ", coupon_id_$n=" + coupon_id_$n + ", coupon_fee_$n=" - + coupon_fee_$n + ", transaction_id=" + transaction_id - + ", out_trade_no=" + out_trade_no + ", attach=" + attach - + ", time_end=" + time_end + "]"; + return "WxMpPayCallback [return_code=" + this.return_code + ", return_msg=" + + this.return_msg + ", appid=" + this.appid + ", mch_id=" + this.mch_id + + ", device_info=" + this.device_info + ", nonce_str=" + this.nonce_str + + ", sign=" + this.sign + ", result_code=" + this.result_code + + ", err_code=" + this.err_code + ", err_code_des=" + this.err_code_des + + ", openid=" + this.openid + ", is_subscribe=" + this.is_subscribe + + ", trade_type=" + this.trade_type + ", bank_type=" + this.bank_type + + ", total_fee=" + this.total_fee + ", fee_type=" + this.fee_type + + ", cash_fee=" + this.cash_fee + ", cash_fee_type=" + this.cash_fee_type + + ", coupon_fee=" + this.coupon_fee + ", coupon_count=" + + this.coupon_count + ", coupon_batch_id_$n=" + this.coupon_batch_id_$n + + ", coupon_id_$n=" + this.coupon_id_$n + ", coupon_fee_$n=" + + this.coupon_fee_$n + ", transaction_id=" + this.transaction_id + + ", out_trade_no=" + this.out_trade_no + ", attach=" + this.attach + + ", time_end=" + this.time_end + "]"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java index 1e8327e30f..4d51e8f493 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayRefundResult.java @@ -85,7 +85,7 @@ public class WxMpPayRefundResult implements Serializable { private String couponRefundId; public String getReturnCode() { - return returnCode; + return this.returnCode; } public void setReturnCode(String returnCode) { @@ -93,7 +93,7 @@ public void setReturnCode(String returnCode) { } public String getReturnMsg() { - return returnMsg; + return this.returnMsg; } public void setReturnMsg(String returnMsg) { @@ -101,7 +101,7 @@ public void setReturnMsg(String returnMsg) { } public String getResultCode() { - return resultCode; + return this.resultCode; } public void setResultCode(String resultCode) { @@ -109,7 +109,7 @@ public void setResultCode(String resultCode) { } public String getErrCode() { - return errCode; + return this.errCode; } public void setErrCode(String errCode) { @@ -117,7 +117,7 @@ public void setErrCode(String errCode) { } public String getErrCodeDes() { - return errCodeDes; + return this.errCodeDes; } public void setErrCodeDes(String errCodeDes) { @@ -125,7 +125,7 @@ public void setErrCodeDes(String errCodeDes) { } public String getAppid() { - return appid; + return this.appid; } public void setAppid(String appid) { @@ -133,7 +133,7 @@ public void setAppid(String appid) { } public String getMchId() { - return mchId; + return this.mchId; } public void setMchId(String mchId) { @@ -141,7 +141,7 @@ public void setMchId(String mchId) { } public String getDeviceInfo() { - return deviceInfo; + return this.deviceInfo; } public void setDeviceInfo(String deviceInfo) { @@ -149,7 +149,7 @@ public void setDeviceInfo(String deviceInfo) { } public String getNonceStr() { - return nonceStr; + return this.nonceStr; } public void setNonceStr(String nonceStr) { @@ -157,7 +157,7 @@ public void setNonceStr(String nonceStr) { } public String getSign() { - return sign; + return this.sign; } public void setSign(String sign) { @@ -165,7 +165,7 @@ public void setSign(String sign) { } public String getTransactionId() { - return transactionId; + return this.transactionId; } public void setTransactionId(String transactionId) { @@ -173,7 +173,7 @@ public void setTransactionId(String transactionId) { } public String getOutTradeNo() { - return outTradeNo; + return this.outTradeNo; } public void setOutTradeNo(String outTradeNo) { @@ -181,7 +181,7 @@ public void setOutTradeNo(String outTradeNo) { } public String getOutRefundNo() { - return outRefundNo; + return this.outRefundNo; } public void setOutRefundNo(String outRefundNo) { @@ -189,7 +189,7 @@ public void setOutRefundNo(String outRefundNo) { } public String getRefundId() { - return refundId; + return this.refundId; } public void setRefundId(String refundId) { @@ -197,7 +197,7 @@ public void setRefundId(String refundId) { } public String getRefundChannel() { - return refundChannel; + return this.refundChannel; } public void setRefundChannel(String refundChannel) { @@ -205,7 +205,7 @@ public void setRefundChannel(String refundChannel) { } public String getRefundFee() { - return refundFee; + return this.refundFee; } public void setRefundFee(String refundFee) { @@ -213,7 +213,7 @@ public void setRefundFee(String refundFee) { } public String getTotalFee() { - return totalFee; + return this.totalFee; } public void setTotalFee(String totalFee) { @@ -221,7 +221,7 @@ public void setTotalFee(String totalFee) { } public String getFeeType() { - return feeType; + return this.feeType; } public void setFeeType(String feeType) { @@ -229,7 +229,7 @@ public void setFeeType(String feeType) { } public String getCashFee() { - return cashFee; + return this.cashFee; } public void setCashFee(String cashFee) { @@ -237,7 +237,7 @@ public void setCashFee(String cashFee) { } public String getCashRefundfee() { - return cashRefundfee; + return this.cashRefundfee; } public void setCashRefundfee(String cashRefundfee) { @@ -245,7 +245,7 @@ public void setCashRefundfee(String cashRefundfee) { } public String getCouponRefundFee() { - return couponRefundFee; + return this.couponRefundFee; } public void setCouponRefundFee(String couponRefundFee) { @@ -253,7 +253,7 @@ public void setCouponRefundFee(String couponRefundFee) { } public String getCouponRefundCount() { - return couponRefundCount; + return this.couponRefundCount; } public void setCouponRefundCount(String couponRefundCount) { @@ -261,7 +261,7 @@ public void setCouponRefundCount(String couponRefundCount) { } public String getCouponRefundId() { - return couponRefundId; + return this.couponRefundId; } public void setCouponRefundId(String couponRefundId) { @@ -271,8 +271,8 @@ public void setCouponRefundId(String couponRefundId) { @Override public String toString() { return "[" + - "return_code:" + returnCode + ";" + - "return_msg" + returnMsg + ";"; + "return_code:" + this.returnCode + ";" + + "return_msg" + this.returnMsg + ";"; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java index 3c7887296a..1ea8fd65ee 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPayResult.java @@ -43,91 +43,91 @@ public class WxMpPayResult implements Serializable { private String time_end; public String getReturn_code() { - return return_code; + return this.return_code; } public String getReturn_msg() { - return return_msg; + return this.return_msg; } public String getAppid() { - return appid; + return this.appid; } public String getMch_id() { - return mch_id; + return this.mch_id; } public String getNonce_str() { - return nonce_str; + return this.nonce_str; } public String getSign() { - return sign; + return this.sign; } public String getResult_code() { - return result_code; + return this.result_code; } public String getErr_code() { - return err_code; + return this.err_code; } public String getErr_code_des() { - return err_code_des; + return this.err_code_des; } public String getTrade_state() { - return trade_state; + return this.trade_state; } public String getDevice_info() { - return device_info; + return this.device_info; } public String getOpenid() { - return openid; + return this.openid; } public String getIs_subscribe() { - return is_subscribe; + return this.is_subscribe; } public String getTrade_type() { - return trade_type; + return this.trade_type; } public String getBank_type() { - return bank_type; + return this.bank_type; } public String getTotal_fee() { - return total_fee; + return this.total_fee; } public String getCoupon_fee() { - return coupon_fee; + return this.coupon_fee; } public String getFee_type() { - return fee_type; + return this.fee_type; } public String getTransaction_id() { - return transaction_id; + return this.transaction_id; } public String getOut_trade_no() { - return out_trade_no; + return this.out_trade_no; } public String getAttach() { - return attach; + return this.attach; } public String getTime_end() { - return time_end; + return this.time_end; } public void setReturn_code(String return_code) { @@ -219,7 +219,7 @@ public void setTime_end(String time_end) { } public String getTrade_state_desc() { - return trade_state_desc; + return this.trade_state_desc; } public void setTrade_state_desc(String trade_state_desc) { @@ -229,29 +229,29 @@ public void setTrade_state_desc(String trade_state_desc) { @Override public String toString() { return "WxMpPayResult{" + - "return_code=" + return_code + - ", return_msg='" + return_msg + '\'' + - ", appid='" + appid + '\'' + - ", mch_id='" + mch_id + '\'' + - ", nonce_str='" + nonce_str + '\'' + - ", sign='" + sign + '\'' + - ", result_code='" + result_code + '\'' + - ", err_code='" + err_code + '\'' + - ", err_code_des='" + err_code_des + '\'' + - ", trade_state=" + trade_state + - ", trade_state_desc=" + trade_state_desc + - ", device_info='" + device_info + '\'' + - ", openid='" + openid + '\'' + - ", is_subscribe='" + is_subscribe + '\'' + - ", trade_type='" + trade_type + '\'' + - ", bank_type='" + bank_type + '\'' + - ", total_fee='" + total_fee + '\'' + - ", coupon_fee='" + coupon_fee + '\'' + - ", fee_type='" + fee_type + '\'' + - ", transaction_id='" + transaction_id + '\'' + - ", out_trade_no='" + out_trade_no + '\'' + - ", attach='" + attach + '\'' + - ", time_end='" + time_end + '\'' + + "return_code=" + this.return_code + + ", return_msg='" + this.return_msg + '\'' + + ", appid='" + this.appid + '\'' + + ", mch_id='" + this.mch_id + '\'' + + ", nonce_str='" + this.nonce_str + '\'' + + ", sign='" + this.sign + '\'' + + ", result_code='" + this.result_code + '\'' + + ", err_code='" + this.err_code + '\'' + + ", err_code_des='" + this.err_code_des + '\'' + + ", trade_state=" + this.trade_state + + ", trade_state_desc=" + this.trade_state_desc + + ", device_info='" + this.device_info + '\'' + + ", openid='" + this.openid + '\'' + + ", is_subscribe='" + this.is_subscribe + '\'' + + ", trade_type='" + this.trade_type + '\'' + + ", bank_type='" + this.bank_type + '\'' + + ", total_fee='" + this.total_fee + '\'' + + ", coupon_fee='" + this.coupon_fee + '\'' + + ", fee_type='" + this.fee_type + '\'' + + ", transaction_id='" + this.transaction_id + '\'' + + ", out_trade_no='" + this.out_trade_no + '\'' + + ", attach='" + this.attach + '\'' + + ", time_end='" + this.time_end + '\'' + '}'; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java index b5c09b21c7..e930fc13b2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpPrepayIdResult.java @@ -13,6 +13,10 @@ * @author chanjarster */ public class WxMpPrepayIdResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = -8970574397788396143L; private String return_code; private String return_msg; private String appid; @@ -27,7 +31,7 @@ public class WxMpPrepayIdResult implements Serializable { private String code_url; public String getReturn_code() { - return return_code; + return this.return_code; } public void setReturn_code(String return_code) { @@ -35,7 +39,7 @@ public void setReturn_code(String return_code) { } public String getReturn_msg() { - return return_msg; + return this.return_msg; } public void setReturn_msg(String return_msg) { @@ -43,7 +47,7 @@ public void setReturn_msg(String return_msg) { } public String getAppid() { - return appid; + return this.appid; } public void setAppid(String appid) { @@ -51,7 +55,7 @@ public void setAppid(String appid) { } public String getMch_id() { - return mch_id; + return this.mch_id; } public void setMch_id(String mch_id) { @@ -59,7 +63,7 @@ public void setMch_id(String mch_id) { } public String getNonce_str() { - return nonce_str; + return this.nonce_str; } public void setNonce_str(String nonce_str) { @@ -67,7 +71,7 @@ public void setNonce_str(String nonce_str) { } public String getSign() { - return sign; + return this.sign; } public void setSign(String sign) { @@ -75,7 +79,7 @@ public void setSign(String sign) { } public String getResult_code() { - return result_code; + return this.result_code; } public void setResult_code(String result_code) { @@ -83,7 +87,7 @@ public void setResult_code(String result_code) { } public String getPrepay_id() { - return prepay_id; + return this.prepay_id; } public void setPrepay_id(String prepay_id) { @@ -91,7 +95,7 @@ public void setPrepay_id(String prepay_id) { } public String getTrade_type() { - return trade_type; + return this.trade_type; } public void setTrade_type(String trade_type) { @@ -99,7 +103,7 @@ public void setTrade_type(String trade_type) { } public String getErr_code() { - return err_code; + return this.err_code; } public void setErr_code(String err_code) { @@ -107,7 +111,7 @@ public void setErr_code(String err_code) { } public String getErr_code_des() { - return err_code_des; + return this.err_code_des; } public void setErr_code_des(String err_code_des) { @@ -115,7 +119,7 @@ public void setErr_code_des(String err_code_des) { } public String getCode_url() { - return code_url; + return this.code_url; } public void setCode_url(String code_url) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java index 537b771c5c..a2917ecc5a 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpQrCodeTicket.java @@ -11,12 +11,16 @@ */ public class WxMpQrCodeTicket implements Serializable { + /** + * + */ + private static final long serialVersionUID = 5777119669111011584L; protected String ticket; protected int expire_seconds = -1; protected String url; public String getTicket() { - return ticket; + return this.ticket; } public void setTicket(String ticket) { @@ -27,7 +31,7 @@ public void setTicket(String ticket) { * 如果返回-1说明是永久 */ public int getExpire_seconds() { - return expire_seconds; + return this.expire_seconds; } public void setExpire_seconds(int expire_seconds) { @@ -35,7 +39,7 @@ public void setExpire_seconds(int expire_seconds) { } public String getUrl() { - return url; + return this.url; } public void setUrl(String url) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java index 936cfbfed6..c8a01d3efe 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpSemanticQueryResult.java @@ -13,6 +13,10 @@ */ public class WxMpSemanticQueryResult implements Serializable { + /** + * + */ + private static final long serialVersionUID = 4811088544804441365L; private String query; private String type; private String semantic; @@ -21,7 +25,7 @@ public class WxMpSemanticQueryResult implements Serializable { private String text; public String getQuery() { - return query; + return this.query; } public void setQuery(String query) { @@ -29,7 +33,7 @@ public void setQuery(String query) { } public String getType() { - return type; + return this.type; } public void setType(String type) { @@ -37,7 +41,7 @@ public void setType(String type) { } public String getSemantic() { - return semantic; + return this.semantic; } public void setSemantic(String semantic) { @@ -45,7 +49,7 @@ public void setSemantic(String semantic) { } public String getResult() { - return result; + return this.result; } public void setResult(String result) { @@ -53,7 +57,7 @@ public void setResult(String result) { } public String getAnswer() { - return answer; + return this.answer; } public void setAnswer(String answer) { @@ -61,7 +65,7 @@ public void setAnswer(String answer) { } public String getText() { - return text; + return this.text; } public void setText(String text) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java index 29c6415fb1..76670f029b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUser.java @@ -1,8 +1,14 @@ package me.chanjar.weixin.mp.bean.result; -import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; - import java.io.Serializable; +import java.lang.reflect.Type; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * 微信用户信息 @@ -11,6 +17,10 @@ */ public class WxMpUser implements Serializable { + /** + * @fields serialVersionUID + */ + private static final long serialVersionUID = 5788154322646488738L; protected Boolean subscribe; protected String openId; protected String nickname; @@ -27,70 +37,70 @@ public class WxMpUser implements Serializable { protected Integer groupId; public Boolean getSubscribe() { - return subscribe; + return this.subscribe; } public Boolean isSubscribe() { - return subscribe; + return this.subscribe; } public void setSubscribe(Boolean subscribe) { this.subscribe = subscribe; } public String getOpenId() { - return openId; + return this.openId; } public void setOpenId(String openId) { this.openId = openId; } public String getNickname() { - return nickname; + return this.nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSex() { - return sex; + return this.sex; } public void setSex(String sex) { this.sex = sex; } public String getLanguage() { - return language; + return this.language; } public void setLanguage(String language) { this.language = language; } public String getCity() { - return city; + return this.city; } public void setCity(String city) { this.city = city; } public String getProvince() { - return province; + return this.province; } public void setProvince(String province) { this.province = province; } public String getCountry() { - return country; + return this.country; } public void setCountry(String country) { this.country = country; } public String getHeadImgUrl() { - return headImgUrl; + return this.headImgUrl; } public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; } public Long getSubscribeTime() { - return subscribeTime; + return this.subscribeTime; } public void setSubscribeTime(Long subscribeTime) { this.subscribeTime = subscribeTime; } public String getUnionId() { - return unionId; + return this.unionId; } public void setUnionId(String unionId) { this.unionId = unionId; @@ -98,7 +108,7 @@ public void setUnionId(String unionId) { public Integer getSexId() { - return sexId; + return this.sexId; } public void setSexId(Integer sexId) { @@ -106,13 +116,13 @@ public void setSexId(Integer sexId) { } public String getRemark() { - return remark; + return this.remark; } public void setRemark(String remark) { this.remark = remark; } public Integer getGroupId() { - return groupId; + return this.groupId; } public void setGroupId(Integer groupId) { this.groupId = groupId; @@ -122,22 +132,29 @@ public static WxMpUser fromJson(String json) { return WxMpGsonBuilder.INSTANCE.create().fromJson(json, WxMpUser.class); } + public static List fromJsonList(String json) { + Type collectionType = new TypeToken>() {}.getType(); + Gson gson = WxMpGsonBuilder.INSTANCE.create(); + JsonObject jsonObject = gson.fromJson(json, JsonObject.class); + return gson.fromJson(jsonObject.get("user_info_list"), collectionType); + } + @Override public String toString() { return "WxMpUser{" + - "subscribe=" + subscribe + - ", openId='" + openId + '\'' + - ", nickname='" + nickname + '\'' + - ", sex='" + sex + '\'' + - ", language='" + language + '\'' + - ", city='" + city + '\'' + - ", province='" + province + '\'' + - ", country='" + country + '\'' + - ", headImgUrl='" + headImgUrl + '\'' + - ", subscribeTime=" + subscribeTime + - ", unionId='" + unionId + '\'' + - ", remark='" + remark + '\'' + - ", groupId='" + groupId + '\'' + + "subscribe=" + this.subscribe + + ", openId='" + this.openId + '\'' + + ", nickname='" + this.nickname + '\'' + + ", sex='" + this.sex + '\'' + + ", language='" + this.language + '\'' + + ", city='" + this.city + '\'' + + ", province='" + this.province + '\'' + + ", country='" + this.country + '\'' + + ", headImgUrl='" + this.headImgUrl + '\'' + + ", subscribeTime=" + this.subscribeTime + + ", unionId='" + this.unionId + '\'' + + ", remark='" + this.remark + '\'' + + ", groupId='" + this.groupId + '\'' + '}'; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java index 842f13270d..94b51f6c35 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxMpUserList.java @@ -14,28 +14,28 @@ public class WxMpUserList { protected int total = -1; protected int count = -1; - protected List openIds = new ArrayList(); + protected List openIds = new ArrayList<>(); protected String nextOpenId; public int getTotal() { - return total; + return this.total; } public void setTotal(int total) { this.total = total; } public int getCount() { - return count; + return this.count; } public void setCount(int count) { this.count = count; } public List getOpenIds() { - return openIds; + return this.openIds; } public void setOpenIds(List openIds) { this.openIds = openIds; } public String getNextOpenId() { - return nextOpenId; + return this.nextOpenId; } public void setNextOpenId(String nextOpenId) { this.nextOpenId = nextOpenId; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java index 37121247d0..be3286683b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/result/WxRedpackResult.java @@ -47,72 +47,72 @@ public class WxRedpackResult implements Serializable { String sendListid; public String getErrCode() { - return errCode; + return this.errCode; } public String getErrCodeDes() { - return errCodeDes; + return this.errCodeDes; } public String getReturnCode() { - return returnCode; + return this.returnCode; } public String getReturnMsg() { - return returnMsg; + return this.returnMsg; } public String getSign() { - return sign; + return this.sign; } public String getResultCode() { - return resultCode; + return this.resultCode; } public String getMchBillno() { - return mchBillno; + return this.mchBillno; } public String getMchId() { - return mchId; + return this.mchId; } public String getWxappid() { - return wxappid; + return this.wxappid; } public String getReOpenid() { - return reOpenid; + return this.reOpenid; } public int getTotalAmount() { - return totalAmount; + return this.totalAmount; } public String getSendTime() { - return sendTime; + return this.sendTime; } public String getSendListid() { - return sendListid; + return this.sendListid; } @Override public String toString() { return "WxRedpackResult{" + - "returnCode=" + returnCode + - ", returnMsg=" + returnMsg + - ", sign=" + sign + - ", errCode=" + errCode + - ", errCodeDes=" + errCodeDes + - ", mchBillno=" + mchBillno + - ", mchId=" + mchId + - ", wxappid=" + wxappid + - ", reOpenid=" + reOpenid + - ", totalAmount=" + totalAmount + - ", sendTime=" + sendTime + - ", sendListid=" + sendListid + + "returnCode=" + this.returnCode + + ", returnMsg=" + this.returnMsg + + ", sign=" + this.sign + + ", errCode=" + this.errCode + + ", errCodeDes=" + this.errCodeDes + + ", mchBillno=" + this.mchBillno + + ", mchId=" + this.mchId + + ", wxappid=" + this.wxappid + + ", reOpenid=" + this.reOpenid + + ", totalAmount=" + this.totalAmount + + ", sendTime=" + this.sendTime + + ", sendListid=" + this.sendListid + '}'; } } diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java index e0529bd32d..9502afe66d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialDeleteRequestExecutor.java @@ -6,7 +6,6 @@ import me.chanjar.weixin.common.util.http.Utf8ResponseHandler; import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -24,6 +23,7 @@ public MaterialDeleteRequestExecutor() { super(); } + @Override public Boolean execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java index 313d75ac54..7a0719db05 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialNewsInfoRequestExecutor.java @@ -8,7 +8,6 @@ import me.chanjar.weixin.mp.bean.WxMpMaterialNews; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -25,6 +24,7 @@ public MaterialNewsInfoRequestExecutor() { super(); } + @Override public WxMpMaterialNews execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java index 830ef9acd7..b7f0550612 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialUploadRequestExecutor.java @@ -8,7 +8,6 @@ import me.chanjar.weixin.mp.bean.WxMpMaterial; import me.chanjar.weixin.mp.bean.result.WxMpMaterialUploadResult; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java index 1434c8ebfb..4f9f6878d4 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVideoInfoRequestExecutor.java @@ -7,7 +7,6 @@ import me.chanjar.weixin.common.util.json.WxGsonBuilder; import me.chanjar.weixin.mp.bean.result.WxMpMaterialVideoInfoResult; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -24,6 +23,7 @@ public MaterialVideoInfoRequestExecutor() { super(); } + @Override public WxMpMaterialVideoInfoResult execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java index a5d0754ad3..81bc225387 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MaterialVoiceAndImageDownloadRequestExecutor.java @@ -7,7 +7,6 @@ import me.chanjar.weixin.common.util.json.WxGsonBuilder; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -34,6 +33,7 @@ public MaterialVoiceAndImageDownloadRequestExecutor(File tmpDirFile) { this.tmpDirFile = tmpDirFile; } + @Override public InputStream execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri, String materialId) throws WxErrorException, IOException { HttpPost httpPost = new HttpPost(uri); if (httpProxy != null) { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java index 8e901443e6..496060313d 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/MediaImgUploadRequestExecutor.java @@ -7,7 +7,6 @@ import me.chanjar.weixin.mp.bean.result.WxMediaImgUploadResult; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java index 96e444e7fe..2486ca8090 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/http/QrCodeRequestExecutor.java @@ -9,7 +9,6 @@ import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket; import org.apache.http.Header; import org.apache.http.HttpHost; -import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; @@ -47,7 +46,8 @@ public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String u httpGet.setConfig(config); } - try (CloseableHttpResponse response = httpclient.execute(httpGet)) { + try (CloseableHttpResponse response = httpclient.execute(httpGet); + InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);) { Header[] contentTypeHeader = response.getHeaders("Content-Type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { // 出错 @@ -56,8 +56,6 @@ public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String u throw new WxErrorException(WxError.fromJson(responseContent)); } } - InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response); - return FileUtils.createTmpFile(inputStream, UUID.randomUUID().toString(), "jpg"); } finally { httpGet.releaseConnection(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java index b264f1f5bb..388139f2c6 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxLongTimeJsonSerializer.java @@ -4,7 +4,6 @@ import java.text.SimpleDateFormat; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java index 4e72752a6f..74a2acfe39 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpCustomMessageGsonAdapter.java @@ -18,6 +18,7 @@ public class WxMpCustomMessageGsonAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxMpCustomMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); messageJson.addProperty("touser", message.getToUser()); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGroupGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGroupGsonAdapter.java index 58e6f98dbb..a6a48ed74c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGroupGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGroupGsonAdapter.java @@ -16,6 +16,7 @@ public class WxMpGroupGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxMpGroup group, Type typeOfSrc, JsonSerializationContext context) { JsonObject json = new JsonObject(); JsonObject groupJson = new JsonObject(); @@ -26,6 +27,7 @@ public JsonElement serialize(WxMpGroup group, Type typeOfSrc, JsonSerializationC return json; } + @Override public WxMpGroup deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpGroup group = new WxMpGroup(); JsonObject groupJson = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java index 34570b30e3..bf920fff3b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpGsonBuilder.java @@ -3,6 +3,8 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import me.chanjar.weixin.mp.bean.*; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; import me.chanjar.weixin.mp.bean.result.*; public class WxMpGsonBuilder { @@ -25,8 +27,8 @@ public class WxMpGsonBuilder { INSTANCE.registerTypeAdapter(WxMpTemplateMessage.class, new WxMpTemplateMessageGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpSemanticQueryResult.class, new WxMpSemanticQueryResultAdapter()); INSTANCE.registerTypeAdapter(WxMpOAuth2AccessToken.class, new WxMpOAuth2AccessTokenAdapter()); - INSTANCE.registerTypeAdapter(WxMpUserSummary.class, new WxMpUserSummaryGsonAdapter()); - INSTANCE.registerTypeAdapter(WxMpUserCumulate.class, new WxMpUserCumulateGsonAdapter()); + INSTANCE.registerTypeAdapter(WxDataCubeUserSummary.class, new WxMpUserSummaryGsonAdapter()); + INSTANCE.registerTypeAdapter(WxDataCubeUserCumulate.class, new WxMpUserCumulateGsonAdapter()); INSTANCE.registerTypeAdapter(WxMpMaterialUploadResult.class, new WxMpMaterialUploadResultAdapter()); INSTANCE.registerTypeAdapter(WxMpMaterialVideoInfoResult.class, new WxMpMaterialVideoInfoResultAdapter()); INSTANCE.registerTypeAdapter(WxMpMassNews.WxMpMassNewsArticle.class, new WxMpMassNewsArticleGsonAdapter()); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java index 79a9a0c61f..4ad4584867 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassGroupMessageGsonAdapter.java @@ -19,6 +19,7 @@ public class WxMpMassGroupMessageGsonAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxMpMassGroupMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java index 32bda06867..e4d8840344 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsArticleGsonAdapter.java @@ -16,6 +16,7 @@ public class WxMpMassNewsArticleGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxMpMassNews.WxMpMassNewsArticle article, Type typeOfSrc, JsonSerializationContext context) { JsonObject articleJson = new JsonObject(); @@ -35,6 +36,7 @@ public JsonElement serialize(WxMpMassNews.WxMpMassNewsArticle article, Type type return articleJson; } + @Override public WxMpMassNews.WxMpMassNewsArticle deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject articleInfo = jsonElement.getAsJsonObject(); WxMpMassNews.WxMpMassNewsArticle article = new WxMpMassNews.WxMpMassNewsArticle(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java index 2a5c228308..fecf494d85 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassNewsGsonAdapter.java @@ -15,6 +15,7 @@ public class WxMpMassNewsGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxMpMassNews message, Type typeOfSrc, JsonSerializationContext context) { JsonObject newsJson = new JsonObject(); @@ -28,6 +29,7 @@ public JsonElement serialize(WxMpMassNews message, Type typeOfSrc, JsonSerializa return newsJson; } + @Override public WxMpMassNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { WxMpMassNews wxMpMassNews = new WxMpMassNews(); JsonObject json = jsonElement.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassOpenIdsMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassOpenIdsMessageGsonAdapter.java index 84063da433..cfb1f37429 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassOpenIdsMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassOpenIdsMessageGsonAdapter.java @@ -16,6 +16,7 @@ public class WxMpMassOpenIdsMessageGsonAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxMpMassOpenIdsMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassSendResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassSendResultAdapter.java index 658ac358ff..eeea9bc543 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassSendResultAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassSendResultAdapter.java @@ -21,6 +21,7 @@ */ public class WxMpMassSendResultAdapter implements JsonDeserializer { + @Override public WxMpMassSendResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpMassSendResult sendResult = new WxMpMassSendResult(); JsonObject sendResultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassUploadResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassUploadResultAdapter.java index 73f0338279..75564b6317 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassUploadResultAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassUploadResultAdapter.java @@ -21,6 +21,7 @@ */ public class WxMpMassUploadResultAdapter implements JsonDeserializer { + @Override public WxMpMassUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpMassUploadResult uploadResult = new WxMpMassUploadResult(); JsonObject uploadResultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassVideoAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassVideoAdapter.java index d4b37b816c..264a57b313 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassVideoAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMassVideoAdapter.java @@ -23,6 +23,7 @@ */ public class WxMpMassVideoAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxMpMassVideo message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); messageJson.addProperty("media_id", message.getMediaId()); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java index 93391732e9..d9657083b5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialArticleUpdateGsonAdapter.java @@ -19,6 +19,7 @@ public class WxMpMaterialArticleUpdateGsonAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxMpMaterialArticleUpdate wxMpMaterialArticleUpdate, Type typeOfSrc, JsonSerializationContext context) { JsonObject articleUpdateJson = new JsonObject(); articleUpdateJson.addProperty("media_id", wxMpMaterialArticleUpdate.getMediaId()); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java index 0178a36870..ab8a22cc41 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialCountResultAdapter.java @@ -19,6 +19,7 @@ */ public class WxMpMaterialCountResultAdapter implements JsonDeserializer { + @Override public WxMpMaterialCountResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpMaterialCountResult countResult = new WxMpMaterialCountResult(); JsonObject materialCountResultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java index 74e3edad13..a94e8f1dd6 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonAdapter.java @@ -18,6 +18,7 @@ public class WxMpMaterialFileBatchGetGsonAdapter implements JsonDeserializer { + @Override public WxMpMaterialFileBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { WxMpMaterialFileBatchGetResult wxMpMaterialFileBatchGetResult = new WxMpMaterialFileBatchGetResult(); JsonObject json = jsonElement.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java index 5be696ad3a..e5314ed6d2 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialFileBatchGetGsonItemAdapter.java @@ -17,6 +17,7 @@ public class WxMpMaterialFileBatchGetGsonItemAdapter implements JsonDeserializer { + @Override public WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem wxMaterialFileBatchGetNewsItem = new WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem(); JsonObject json = jsonElement.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java index 96cc6aabeb..7102088666 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsArticleGsonAdapter.java @@ -16,6 +16,7 @@ public class WxMpMaterialNewsArticleGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxMpMaterialNews.WxMpMaterialNewsArticle article, Type typeOfSrc, JsonSerializationContext context) { JsonObject articleJson = new JsonObject(); @@ -39,6 +40,7 @@ public JsonElement serialize(WxMpMaterialNews.WxMpMaterialNewsArticle article, T return articleJson; } + @Override public WxMpMaterialNews.WxMpMaterialNewsArticle deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject articleInfo = jsonElement.getAsJsonObject(); WxMpMaterialNews.WxMpMaterialNewsArticle article = new WxMpMaterialNews.WxMpMaterialNewsArticle(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java index eed1610b84..d45b8dc19c 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonAdapter.java @@ -18,6 +18,7 @@ public class WxMpMaterialNewsBatchGetGsonAdapter implements JsonDeserializer { + @Override public WxMpMaterialNewsBatchGetResult deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = new WxMpMaterialNewsBatchGetResult(); JsonObject json = jsonElement.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java index 8df7c20d63..0fdf0ece3b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsBatchGetGsonItemAdapter.java @@ -18,6 +18,7 @@ public class WxMpMaterialNewsBatchGetGsonItemAdapter implements JsonDeserializer { + @Override public WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem wxMaterialNewsBatchGetNewsItem = new WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem(); JsonObject json = jsonElement.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java index 93c002a48e..2513597fff 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialNewsGsonAdapter.java @@ -15,6 +15,7 @@ public class WxMpMaterialNewsGsonAdapter implements JsonSerializer, JsonDeserializer { + @Override public JsonElement serialize(WxMpMaterialNews wxMpMaterialNews, Type typeOfSrc, JsonSerializationContext context) { JsonObject newsJson = new JsonObject(); @@ -28,6 +29,7 @@ public JsonElement serialize(WxMpMaterialNews wxMpMaterialNews, Type typeOfSrc, return newsJson; } + @Override public WxMpMaterialNews deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { WxMpMaterialNews wxMpMaterialNews = new WxMpMaterialNews(); JsonObject json = jsonElement.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java index d5cd728cdd..e99c97dcb8 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialUploadResultAdapter.java @@ -19,6 +19,7 @@ */ public class WxMpMaterialUploadResultAdapter implements JsonDeserializer { + @Override public WxMpMaterialUploadResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpMaterialUploadResult uploadResult = new WxMpMaterialUploadResult(); JsonObject uploadResultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java index 6f4ce92862..a1c7c0a2ce 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpMaterialVideoInfoResultAdapter.java @@ -11,6 +11,7 @@ */ public class WxMpMaterialVideoInfoResultAdapter implements JsonDeserializer { + @Override public WxMpMaterialVideoInfoResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpMaterialVideoInfoResult uploadResult = new WxMpMaterialVideoInfoResult(); JsonObject uploadResultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpOAuth2AccessTokenAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpOAuth2AccessTokenAdapter.java index 753e22d17e..d4f8fd5526 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpOAuth2AccessTokenAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpOAuth2AccessTokenAdapter.java @@ -13,6 +13,7 @@ public class WxMpOAuth2AccessTokenAdapter implements JsonDeserializer { + @Override public WxMpOAuth2AccessToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpOAuth2AccessToken accessToken = new WxMpOAuth2AccessToken(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpSemanticQueryResultAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpSemanticQueryResultAdapter.java index 822357df40..2e35459716 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpSemanticQueryResultAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpSemanticQueryResultAdapter.java @@ -21,6 +21,7 @@ */ public class WxMpSemanticQueryResultAdapter implements JsonDeserializer { + @Override public WxMpSemanticQueryResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpSemanticQueryResult result = new WxMpSemanticQueryResult(); JsonObject resultJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java index be792df5b2..4c2d122727 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpTemplateMessageGsonAdapter.java @@ -19,6 +19,7 @@ public class WxMpTemplateMessageGsonAdapter implements JsonSerializer { + @Override public JsonElement serialize(WxMpTemplateMessage message, Type typeOfSrc, JsonSerializationContext context) { JsonObject messageJson = new JsonObject(); messageJson.addProperty("touser", message.getToUser()); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java index ab4449a6ba..fcf1d403f5 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserCumulateGsonAdapter.java @@ -10,9 +10,7 @@ import com.google.gson.*; import me.chanjar.weixin.common.util.json.GsonHelper; -import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; -import me.chanjar.weixin.mp.bean.result.WxMpUserCumulate; -import me.chanjar.weixin.mp.bean.result.WxMpUserSummary; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; import java.lang.reflect.Type; import java.text.ParseException; @@ -23,12 +21,13 @@ * @author Daniel Qian * */ -public class WxMpUserCumulateGsonAdapter implements JsonDeserializer { +public class WxMpUserCumulateGsonAdapter implements JsonDeserializer { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - public WxMpUserCumulate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - WxMpUserCumulate cumulate = new WxMpUserCumulate(); + @Override + public WxDataCubeUserCumulate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + WxDataCubeUserCumulate cumulate = new WxDataCubeUserCumulate(); JsonObject summaryJsonObject = json.getAsJsonObject(); try { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserGsonAdapter.java index 060c362a12..f580a47014 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserGsonAdapter.java @@ -16,6 +16,7 @@ public class WxMpUserGsonAdapter implements JsonDeserializer { + @Override public WxMpUser deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxMpUser wxMpUser = new WxMpUser(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java index 9db8888488..848b82ceec 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxMpUserSummaryGsonAdapter.java @@ -10,8 +10,7 @@ import com.google.gson.*; import me.chanjar.weixin.common.util.json.GsonHelper; -import me.chanjar.weixin.mp.bean.result.WxMpMassUploadResult; -import me.chanjar.weixin.mp.bean.result.WxMpUserSummary; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; import java.lang.reflect.Type; import java.text.ParseException; @@ -20,13 +19,14 @@ /** * @author Daniel Qian */ -public class WxMpUserSummaryGsonAdapter implements JsonDeserializer { +public class WxMpUserSummaryGsonAdapter implements JsonDeserializer { private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); - public WxMpUserSummary deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + @Override + public WxDataCubeUserSummary deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - WxMpUserSummary summary = new WxMpUserSummary(); + WxDataCubeUserSummary summary = new WxDataCubeUserSummary(); JsonObject summaryJsonObject = json.getAsJsonObject(); try { diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxQrCodeTicketAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxQrCodeTicketAdapter.java index 522d70d064..c08614e541 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxQrCodeTicketAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxQrCodeTicketAdapter.java @@ -21,6 +21,7 @@ */ public class WxQrCodeTicketAdapter implements JsonDeserializer { + @Override public WxMpQrCodeTicket deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { WxMpQrCodeTicket ticket = new WxMpQrCodeTicket(); JsonObject ticketJsonObject = json.getAsJsonObject(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxUserListGsonAdapter.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxUserListGsonAdapter.java index 5e2b9981e9..1c06d0745b 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxUserListGsonAdapter.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/json/WxUserListGsonAdapter.java @@ -16,6 +16,7 @@ public class WxUserListGsonAdapter implements JsonDeserializer { + @Override public WxMpUserList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject o = json.getAsJsonObject(); WxMpUserList wxMpUserList = new WxMpUserList(); diff --git a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java index 472bac55b9..61ecac4197 100644 --- a/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java +++ b/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/util/xml/XStreamTransformer.java @@ -45,7 +45,7 @@ public static String toXml(Class clazz, T object) { } private static Map configXStreamInstance() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(WxMpXmlMessage.class, config_WxMpXmlMessage()); map.put(WxMpXmlOutMusicMessage.class, config_WxMpXmlOutMusicMessage()); map.put(WxMpXmlOutNewsMessage.class, config_WxMpXmlOutNewsMessage()); diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java new file mode 100644 index 0000000000..bfb8cf5846 --- /dev/null +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpDataCubeServiceImplTest.java @@ -0,0 +1,214 @@ +package me.chanjar.weixin.mp.api.impl; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; + +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + +import com.google.inject.Inject; + +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.ApiTestModule; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeArticleTotal; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeInterfaceResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeMsgResult; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserCumulate; +import me.chanjar.weixin.mp.bean.datacube.WxDataCubeUserSummary; + +/** + * 测试统计分析相关的接口 + * Created by Binary Wang on 2016/8/23. + * @author binarywang (https://github.com/binarywang) + */ +@Guice(modules = ApiTestModule.class) +public class WxMpDataCubeServiceImplTest { + private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat( + "yyyy-MM-dd"); + + @Inject + protected WxMpServiceImpl wxService; + + @DataProvider + public Object[][] oneDay() throws ParseException { + return new Object[][] { { simpleDateFormat.parse("2016-08-22") } }; + } + + @DataProvider + public Object[][] threeDays() throws ParseException { + return new Object[][] { { simpleDateFormat.parse("2016-08-20"), + simpleDateFormat.parse("2016-08-22") } }; + } + + @DataProvider + public Object[][] sevenDays() throws ParseException { + return new Object[][] { { simpleDateFormat.parse("2016-08-16"), + simpleDateFormat.parse("2016-08-22") } }; + } + + @DataProvider + public Object[][] fifteenDays() throws ParseException { + return new Object[][] { { simpleDateFormat.parse("2016-08-14"), + simpleDateFormat.parse("2016-08-27") } }; + } + + @DataProvider + public Object[][] thirtyDays() throws ParseException { + return new Object[][] { { simpleDateFormat.parse("2016-07-30"), + simpleDateFormat.parse("2016-08-27") } }; + } + + @Test(dataProvider = "sevenDays") + public void testGetUserSummary(Date beginDate, Date endDate) + throws WxErrorException { + List summaries = this.wxService.getDataCubeService() + .getUserSummary(beginDate, endDate); + Assert.assertNotNull(summaries); + System.out.println(summaries); + } + + @Test(dataProvider = "sevenDays") + public void testGetUserCumulate(Date beginDate, Date endDate) + throws WxErrorException { + List result = this.wxService.getDataCubeService() + .getUserCumulate(beginDate, endDate); + Assert.assertNotNull(result); + System.out.println(result); + } + + @Test(dataProvider = "oneDay") + public void testGetArticleSummary(Date date) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getArticleSummary(date, date); + Assert.assertNotNull(results); + System.out.println(results); + } + + /** + * TODO 该接口,暂时没找到有数据的日期,无法测试验证 + */ + @Test(dataProvider = "oneDay") + public void testGetArticleTotal(Date date) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getArticleTotal(date, date); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "threeDays") + public void testGetUserRead(Date beginDate, Date endDate) + throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUserRead(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "oneDay") + public void testGetUserReadHour(Date date) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUserReadHour(date, date); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "sevenDays") + public void testGetUserShare(Date beginDate, Date endDate) + throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUserShare(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "oneDay") + public void testGetUserShareHour(Date date) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUserShareHour(date, date); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "sevenDays") + public void testGetUpstreamMsg(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsg(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "oneDay") + public void testGetUpstreamMsgHour(Date date) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsgHour(date, date); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "thirtyDays") + public void testGetUpstreamMsgWeek(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsgWeek(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + /** + * TODO 该接口,暂时没找到有数据的日期,无法测试验证 + */ + @Test(dataProvider = "thirtyDays") + public void testGetUpstreamMsgMonth(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsgMonth(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "fifteenDays") + public void testGetUpstreamMsgDist(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsgDist(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "thirtyDays") + public void testGetUpstreamMsgDistWeek(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsgDistWeek(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + /** + * TODO 该接口,暂时没找到有数据的日期,无法测试验证 + */ + @Test(dataProvider = "thirtyDays") + public void testGetUpstreamMsgDistMonth(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getUpstreamMsgDistMonth(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "thirtyDays") + public void testGetInterfaceSummary(Date beginDate, Date endDate) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getInterfaceSummary(beginDate, endDate); + Assert.assertNotNull(results); + System.out.println(results); + } + + @Test(dataProvider = "oneDay") + public void testGetInterfaceSummaryHour(Date date) throws WxErrorException { + List results = this.wxService.getDataCubeService() + .getInterfaceSummaryHour(date, date); + Assert.assertNotNull(results); + System.out.println(results); + } +} diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImplTest.java index 0cbae4db1b..1e0b60dd16 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMenuServiceImplTest.java @@ -1,16 +1,18 @@ package me.chanjar.weixin.mp.api.impl; -import com.google.inject.Inject; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.common.bean.WxMenu; -import me.chanjar.weixin.common.bean.WxMenu.WxMenuButton; -import me.chanjar.weixin.common.exception.WxErrorException; -import me.chanjar.weixin.mp.api.ApiTestModule; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Guice; import org.testng.annotations.Test; +import com.google.inject.Inject; + +import me.chanjar.weixin.common.api.WxConsts; +import me.chanjar.weixin.common.bean.menu.WxMenu; +import me.chanjar.weixin.common.bean.menu.WxMenuButton; +import me.chanjar.weixin.common.exception.WxErrorException; +import me.chanjar.weixin.mp.api.ApiTestModule; + /** * 测试菜单 * @author chanjarster diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java index af5289f0c1..05ac40c9df 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpUserServiceImplTest.java @@ -1,20 +1,15 @@ package me.chanjar.weixin.mp.api.impl; +import org.testng.Assert; +import org.testng.annotations.Guice; +import org.testng.annotations.Test; + import com.google.inject.Inject; + import me.chanjar.weixin.common.exception.WxErrorException; import me.chanjar.weixin.mp.api.ApiTestModule; import me.chanjar.weixin.mp.bean.result.WxMpUser; -import me.chanjar.weixin.mp.bean.result.WxMpUserCumulate; import me.chanjar.weixin.mp.bean.result.WxMpUserList; -import me.chanjar.weixin.mp.bean.result.WxMpUserSummary; -import org.testng.Assert; -import org.testng.annotations.Guice; -import org.testng.annotations.Test; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; /** * 测试用户相关的接口 @@ -61,24 +56,4 @@ public void testGroupMoveUser() throws WxErrorException { this.wxService.getGroupService().userUpdateGroup(configStorage.getOpenId(), this.wxService.getGroupService().groupGet().get(3).getId()); } - @Test - public void testGetUserSummary() throws WxErrorException, ParseException { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date beginDate = simpleDateFormat.parse("2015-01-01"); - Date endDate = simpleDateFormat.parse("2015-01-02"); - List summaries = this.wxService.getUserService().dataCubeUserSummary(beginDate, endDate); - Assert.assertNotNull(summaries); - System.out.println(summaries); - } - - @Test - public void testGetUserCumulate() throws WxErrorException, ParseException { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - Date beginDate = simpleDateFormat.parse("2015-01-01"); - Date endDate = simpleDateFormat.parse("2015-01-02"); - List cumulates = this.wxService.getUserService().dataCubeUserCumulate(beginDate, endDate); - Assert.assertNotNull(cumulates); - System.out.println(cumulates); - } - } diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/result/kefu/WxMpKfListTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfListTest.java similarity index 93% rename from weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/result/kefu/WxMpKfListTest.java rename to weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfListTest.java index cc782250ff..0f52ae0260 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/result/kefu/WxMpKfListTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfListTest.java @@ -1,11 +1,9 @@ -package me.chanjar.weixin.mp.bean.result.kefu; +package me.chanjar.weixin.mp.bean.kefu.result; import org.apache.commons.lang3.builder.ToStringBuilder; import org.testng.Assert; import org.testng.annotations.Test; -import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfList; - @Test public class WxMpKfListTest { diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/result/kefu/WxMpKfOnlineListTest.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineListTest.java similarity index 96% rename from weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/result/kefu/WxMpKfOnlineListTest.java rename to weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineListTest.java index ab04e8e00c..fa514aba7a 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/result/kefu/WxMpKfOnlineListTest.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfOnlineListTest.java @@ -1,4 +1,4 @@ -package me.chanjar.weixin.mp.bean.result.kefu; +package me.chanjar.weixin.mp.bean.kefu.result; import org.apache.commons.lang3.builder.ToStringBuilder; import org.testng.Assert; diff --git a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java index da3ec93cdf..de1c9546e6 100644 --- a/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java +++ b/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/demo/DemoOAuth2Handler.java @@ -14,14 +14,14 @@ */ public class DemoOAuth2Handler implements WxMpMessageHandler { @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map context, - WxMpService wxMpService, WxSessionManager sessionManager) { - String href = "测试oauth2"; - return WxMpXmlOutMessage - .TEXT() - .content(href) - .fromUser(wxMessage.getToUserName()) - .toUser(wxMessage.getFromUserName()).build(); + public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, + Map context, WxMpService wxMpService, + WxSessionManager sessionManager) { + String href = "测试oauth2"; + return WxMpXmlOutMessage.TEXT().content(href) + .fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName()) + .build(); } }