├── .appengine-web.xml
├── .classpath
├── .project
├── .settings
└── org.eclipse.core.resources.prefs
├── README.md
├── WebRoot
├── WEB-INF
│ ├── classes
│ │ └── com
│ │ │ └── using
│ │ │ └── weixin
│ │ │ ├── action
│ │ │ └── IndexServletAction.class
│ │ │ ├── common
│ │ │ ├── ApiTools.class
│ │ │ └── HttpRequestTools.class
│ │ │ └── wxtools
│ │ │ ├── HashKit.class
│ │ │ ├── WeiXinTools.class
│ │ │ ├── parser
│ │ │ ├── WxMsgKit.class
│ │ │ ├── WxRecvEventMsgParser.class
│ │ │ ├── WxRecvGeoMsgParser.class
│ │ │ ├── WxRecvLinkMsgParser.class
│ │ │ ├── WxRecvMsgBaseParser.class
│ │ │ ├── WxRecvMsgParser.class
│ │ │ ├── WxRecvPicMsgParser.class
│ │ │ ├── WxRecvTextMsgParser.class
│ │ │ └── WxRecvVoiceMsgParser.class
│ │ │ └── vo
│ │ │ ├── WxMsg.class
│ │ │ ├── recv
│ │ │ ├── WxRecvEventMsg.class
│ │ │ ├── WxRecvGeoMsg.class
│ │ │ ├── WxRecvLinkMsg.class
│ │ │ ├── WxRecvMsg.class
│ │ │ ├── WxRecvPicMsg.class
│ │ │ ├── WxRecvTextMsg.class
│ │ │ └── WxRecvVoiceMsg.class
│ │ │ └── send
│ │ │ ├── WxSendMsg.class
│ │ │ ├── WxSendMusicMsg.class
│ │ │ ├── WxSendNewsMsg.class
│ │ │ ├── WxSendNewsMsgItem.class
│ │ │ └── WxSendTextMsg.class
│ ├── duapp-web.xml
│ └── web.xml
└── index.jsp
├── lib
├── activation.jar
├── fastjson-1.1.31.jar
├── jdom.jar
└── mail.jar
└── src
└── com
└── using
└── weixin
├── action
└── IndexServletAction.java
├── common
├── ApiTools.java
├── HttpRequestTools.java
├── JavaMail3.java
├── JdbcTools.java
├── SendGmail.java
└── WebGet.java
└── wxtools
├── HashKit.java
├── WeiXinTools.java
├── parser
├── WxMsgKit.java
├── WxRecvEventMsgParser.java
├── WxRecvGeoMsgParser.java
├── WxRecvLinkMsgParser.java
├── WxRecvMsgBaseParser.java
├── WxRecvMsgParser.java
├── WxRecvPicMsgParser.java
├── WxRecvTextMsgParser.java
└── WxRecvVoiceMsgParser.java
└── vo
├── WxMsg.java
├── recv
├── WxRecvEventMsg.java
├── WxRecvGeoMsg.java
├── WxRecvLinkMsg.java
├── WxRecvMsg.java
├── WxRecvPicMsg.java
├── WxRecvTextMsg.java
└── WxRecvVoiceMsg.java
└── send
├── WxSendMsg.java
├── WxSendMusicMsg.java
├── WxSendNewsMsg.java
├── WxSendNewsMsgItem.java
└── WxSendTextMsg.java
/.appengine-web.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | false
13 |
--------------------------------------------------------------------------------
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | bce_java_default
4 |
5 |
6 |
7 |
8 |
9 | com.genuitec.eclipse.j2eedt.core.WebClasspathBuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.jdt.core.javabuilder
15 |
16 |
17 |
18 |
19 | com.genuitec.eclipse.j2eedt.core.J2EEProjectValidator
20 |
21 |
22 |
23 |
24 | com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator
25 |
26 |
27 |
28 |
29 | org.eclipse.wst.validation.validationbuilder
30 |
31 |
32 |
33 |
34 | com.baidu.bdt.bae.java.validator.javaProjectValidator
35 |
36 |
37 |
38 |
39 |
40 | com.genuitec.eclipse.j2eedt.core.webnature
41 | org.eclipse.jdt.core.javanature
42 | org.eclipse.wst.jsdt.core.jsNature
43 | com.baidu.bdt.baeJavaNature
44 |
45 |
46 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | #Fri Mar 23 11:55:00 CST 2012
2 | eclipse.preferences.version=1
3 | encoding/=UTF-8
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/README.md
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/action/IndexServletAction.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/action/IndexServletAction.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/common/ApiTools.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/common/ApiTools.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/common/HttpRequestTools.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/common/HttpRequestTools.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/HashKit.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/HashKit.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/WeiXinTools.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/WeiXinTools.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxMsgKit.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxMsgKit.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvEventMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvEventMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvGeoMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvGeoMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvLinkMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvLinkMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvMsgBaseParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvMsgBaseParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvPicMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvPicMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvTextMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvTextMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvVoiceMsgParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/parser/WxRecvVoiceMsgParser.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/WxMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/WxMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvEventMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvEventMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvGeoMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvGeoMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvLinkMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvLinkMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvPicMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvPicMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvTextMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvTextMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvVoiceMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/recv/WxRecvVoiceMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendMusicMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendMusicMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendNewsMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendNewsMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendNewsMsgItem.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendNewsMsgItem.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendTextMsg.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/WebRoot/WEB-INF/classes/com/using/weixin/wxtools/vo/send/WxSendTextMsg.class
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/duapp-web.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/WebRoot/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 | IndexServletAction
12 | com.using.weixin.action.IndexServletAction
13 |
14 |
15 | IndexServletAction
16 | /weixin.do
17 |
18 |
19 |
20 |
21 | index.jsp
22 |
23 |
24 |
--------------------------------------------------------------------------------
/WebRoot/index.jsp:
--------------------------------------------------------------------------------
1 | <%@ page language="java" import="java.util.*,java.net.URL" pageEncoding="ISO-8859-1"%>
2 | <%
3 | String path = request.getContextPath();
4 | String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
5 | %>
6 |
7 |
8 |
9 |
10 |
11 |
12 | Hello World
13 |
14 |
15 |
16 |
17 |
18 |
21 |
22 |
23 |
24 | wechat test!
25 |
26 |
27 |
--------------------------------------------------------------------------------
/lib/activation.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/lib/activation.jar
--------------------------------------------------------------------------------
/lib/fastjson-1.1.31.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/lib/fastjson-1.1.31.jar
--------------------------------------------------------------------------------
/lib/jdom.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/lib/jdom.jar
--------------------------------------------------------------------------------
/lib/mail.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nameryan/wechat-send2kindle/90837011207cc6997d0de68f67c084f07180a5a2/lib/mail.jar
--------------------------------------------------------------------------------
/src/com/using/weixin/action/IndexServletAction.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.action;
2 |
3 | import java.io.IOException;
4 |
5 | import javax.servlet.ServletException;
6 | import javax.servlet.http.HttpServlet;
7 | import javax.servlet.http.HttpServletRequest;
8 | import javax.servlet.http.HttpServletResponse;
9 |
10 | import com.using.weixin.common.ApiTools;
11 | import com.using.weixin.wxtools.WeiXinTools;
12 | import com.using.weixin.wxtools.vo.recv.WxRecvEventMsg;
13 | import com.using.weixin.wxtools.vo.recv.WxRecvGeoMsg;
14 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
15 | import com.using.weixin.wxtools.vo.recv.WxRecvPicMsg;
16 | import com.using.weixin.wxtools.vo.recv.WxRecvTextMsg;
17 | import com.using.weixin.wxtools.vo.recv.WxRecvVoiceMsg;
18 | import com.using.weixin.wxtools.vo.send.WxSendMsg;
19 | import com.using.weixin.wxtools.vo.send.WxSendMusicMsg;
20 | import com.using.weixin.wxtools.vo.send.WxSendNewsMsg;
21 | import com.using.weixin.wxtools.vo.send.WxSendTextMsg;
22 |
23 | import com.using.weixin.common.JavaMail3;
24 | import com.using.weixin.common.SendGmail;
25 | import com.using.weixin.common.JdbcTools;
26 |
27 | import java.util.logging.Logger;
28 | import java.util.logging.Level;
29 |
30 | import java.util.regex.Matcher;
31 | import java.util.regex.Pattern;
32 |
33 |
34 | /**
35 | * 微信消息处理 请求地址 http://域名/weixin.do
36 | */
37 | public class IndexServletAction extends HttpServlet {
38 | private static final long serialVersionUID = 1L;
39 |
40 | // token标识
41 | private static final String TOKEN = "weixin141200";
42 |
43 | private final String STRING_WELLCOME = "本公众号支持将朋友圈中的文章发送到kindle设备中,您只需要复制文章地址后发送给我,我们将会把文章自动推送到您的账号所绑定的Kindle设备。\n详细使用说明:http://goo.gl/XgCvHM \n回复kindle推送email地址绑定帐号。\n";
44 |
45 | private Logger logger = Logger.getLogger("IndexServletAction");
46 |
47 | private JdbcTools jdbc = new JdbcTools();
48 |
49 | /**
50 | * post请求接受用户输入的消息,和消息回复
51 | */
52 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
53 | try {
54 | WxRecvMsg msg = WeiXinTools.recv(request.getInputStream());
55 |
56 | String fromUser = msg.getFromUser(); //获取用户Id
57 | logger.log(Level.INFO, "fromUser="+fromUser);
58 |
59 | WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(msg);
60 |
61 | /** -------------------1.接受到的文本消息,回复处理-------------------------- */
62 | if (msg instanceof WxRecvTextMsg) {
63 | WxRecvTextMsg recvMsg = (WxRecvTextMsg) msg;
64 | // 用户输入的内容
65 | String text = recvMsg.getContent().trim();
66 |
67 | if (text.equals("进度") || text.equals("帮助") || text.equals("?")) {
68 | String retMsg = "目前已经基本完成功能,正在后期测试完善阶段,也希望你提出宝贵的意见。";
69 | sendMsg = new WxSendTextMsg(sendMsg,retMsg);
70 | WeiXinTools.send(sendMsg, response.getOutputStream());
71 | return;
72 | }
73 | else if(isNameAdressFormat(text)){
74 | //用户输入的是email地址
75 | if (isNameKindleAdressFormat(text)){
76 | //用户输入的是kindle或多看地址
77 | jdbc.insertUserInfo(fromUser,text);
78 |
79 | sendMsg = new WxSendTextMsg(sendMsg,"绑定成功,您输入的kindle推送帐号是"+text);
80 | WeiXinTools.send(sendMsg, response.getOutputStream());
81 | return;
82 | }else{
83 | sendMsg = new WxSendTextMsg(sendMsg,"很抱歉,目前只支持推送到kindle账号或多看账号,不支持其他email地址!");
84 | WeiXinTools.send(sendMsg, response.getOutputStream());
85 | return;
86 | }
87 | }
88 | else if (text.indexOf("http://")>=0
89 | || text.indexOf("https://")>=0
90 | ){
91 | String emailAddr = jdbc.queryUserEmail(fromUser);
92 |
93 | final String STRING_SEND_OK = "文章内容已推送到您的kindle账户"+emailAddr+",请在kindle设备上打开wifi同步内容。";
94 | final String STRING_SEND_FAIL = "获取网页内容出错,请联系公众号。";
95 | final String STRING_NEED_EMAIL = "很抱歉,您还没有绑定您的kindle推送帐号。回复您的kindle设备的推送邮箱立刻绑定!";
96 | String retMsg;
97 | int ret = 0;
98 |
99 | //send email
100 | //SendGmail.main(null);
101 |
102 | //logger.log(Level.INFO, "emailAddr="+emailAddr);
103 | if (emailAddr == null){
104 | retMsg = STRING_NEED_EMAIL;
105 | }else{
106 | JavaMail3 mail = new JavaMail3();
107 |
108 | if(mail.main(emailAddr,text)){
109 | retMsg= STRING_SEND_OK;
110 | ret = 1;
111 | }else{
112 | retMsg = STRING_SEND_FAIL;
113 | ret = -1;
114 | }
115 | jdbc.insertUserLog(fromUser,emailAddr,text,ret);
116 | }
117 |
118 |
119 | //logger.log(Level.INFO, "retMsg="+retMsg);
120 | sendMsg = new WxSendTextMsg(sendMsg,retMsg);
121 | WeiXinTools.send(sendMsg, response.getOutputStream());
122 | return;
123 |
124 | } else {
125 | // 文本消息回复
126 | sendMsg = new WxSendTextMsg(sendMsg, "以下是你发送的内容:" + text);
127 | WeiXinTools.send(sendMsg, response.getOutputStream());
128 | return;
129 | }
130 |
131 |
132 | /** ----------- 消息回复示例:文字回复、单(多)图文回复、音乐回复 end ------------- */
133 |
134 |
135 | }
136 |
137 | /** -------------------2.接受到的事件消息-------------------------- */
138 | else if (msg instanceof WxRecvEventMsg) {
139 | WxRecvEventMsg recvMsg = (WxRecvEventMsg) msg;
140 | String event = recvMsg.getEvent();
141 |
142 | if ("subscribe".equals(event)) {
143 | // 订阅消息
144 | sendMsg = new WxSendTextMsg(sendMsg, STRING_WELLCOME);
145 | WeiXinTools.send(sendMsg, response.getOutputStream());
146 | return;
147 | } else if ("unsubscribe".equals(event)) {
148 | // 取消订阅
149 |
150 | return;
151 |
152 | } else if ("CLICK".equals(event)) {
153 | // 自定义菜单点击事件
154 | String eventKey = recvMsg.getEventKey();
155 |
156 | // 判断自定义菜单中的key回复消息
157 | if ("自定义菜单中的key".equals(eventKey)) {
158 |
159 | return;
160 | }
161 | } else {
162 | // 无法识别的事件消息
163 | return;
164 | }
165 |
166 | }
167 |
168 | /** -------------------3.接受到的地理位置信息-------------------------- */
169 | else if (msg instanceof WxRecvGeoMsg) {
170 | WxRecvGeoMsg recvMsg = (WxRecvGeoMsg) msg;
171 |
172 | return;
173 | }
174 |
175 | /** -------------------4.接受到的音频消息-------------------------- */
176 | else if (msg instanceof WxRecvVoiceMsg) {
177 | WxRecvVoiceMsg recvMsg = (WxRecvVoiceMsg) msg;
178 |
179 | return;
180 | }
181 |
182 | /** -------------------5.接受到的图片消息-------------------------- */
183 | else if (msg instanceof WxRecvPicMsg) {
184 | WxRecvPicMsg recvMsg = (WxRecvPicMsg) msg;
185 |
186 | return;
187 | }
188 |
189 | /** ------------------6.接受到的未能识别的消息-------------------- */
190 | else {
191 | return;
192 | }
193 | } catch (Exception e) {
194 | e.printStackTrace();
195 | }
196 | }
197 |
198 | /**
199 | * get请求进行验证服务器是否正常
200 | */
201 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
202 | /*
203 | * 进行接口验证
204 | */
205 | String signature = request.getParameter("signature");
206 | String timestamp = request.getParameter("timestamp");
207 | String nonce = request.getParameter("nonce");
208 | String echostr = request.getParameter("echostr");
209 | if (null != timestamp && null != nonce && null != echostr && null != signature) {
210 | if (WeiXinTools.access(TOKEN, signature, timestamp, nonce)) {
211 | response.getWriter().write(echostr);
212 | return;
213 | }
214 | return;
215 | } else {
216 | return;
217 | }
218 | }
219 |
220 | /*
221 | 在正则表达式中\w表示任意单个字符范围是a-z,A-Z,0-9,因为在java中\本来就是转义符
222 | 号,如果只写为\w则会发生歧义,甚至错误,因此要写为:\\w
223 | +的意思就是出现一次以上,所以\\w+就代表任意长度的字符串,但不包括其他特殊字符
224 | ,如_,-,$,&,*等,呵呵,如果真想进行完全的邮件有效性检查,那正则表达式就不止这
225 | 么长了,呵呵,有兴趣的可以自己写写看
226 |
227 | 后面的我想就简单了,@必须出现,而且只准出现一次,因此直接写成@就行了
228 |
229 | \\w+.任意字符串后面加上DOT,大家都知道这是域名的特点,另外就是我写成了
230 | (\\w+.)+,为什么呢,因为邮件服务器有可能是二级域名,三级域名,或者……
231 | 如果不带()+的话,abc@sina.com有效,而abc@mail.sina.com就是无效的了,因此这个
232 | 是必须的。
233 |
234 | 最后是[a-z]{2,3},考虑到一般的域名最后不会出现数字,大写也很少见(我想一般应
235 | 该忽略大小写的),并且最少不少于两位,如cn,us,等,最多不超过三位,如com,org,
236 | 等,所以就写成了如上形式
237 |
238 | */
239 |
240 |
241 | private boolean isNameAdressFormat(String email){
242 | boolean isExist = false;
243 |
244 | /*
245 | "\\w+@(\\w+.)+[a-z]{2,3}"
246 | 为了匹配xx.xx_123@xxx.com 这种情况,将\\w改为了. 匹配所有字符
247 | */
248 | Pattern p = Pattern.compile(".+@(\\w+.)+[a-z]{2,3}");
249 | Matcher m = p.matcher(email);
250 | boolean b = m.matches();
251 | if(b) {
252 | logger.log(Level.INFO, "有效的邮件地址");
253 | isExist=true;
254 | } else {
255 | logger.log(Level.INFO, "无效的邮件地址");
256 | }
257 | return isExist;
258 | }
259 |
260 | private boolean isNameKindleAdressFormat(String email){
261 | boolean isExist = false;
262 |
263 | Pattern p = Pattern.compile(".+@((free.kindle|kindle|iduokan).)+[a-z]{2,3}");
264 | Matcher m = p.matcher(email);
265 | boolean b = m.matches();
266 | if(b) {
267 | logger.log(Level.INFO, "有效的kindle或多看地址");
268 | isExist=true;
269 | } else {
270 | logger.log(Level.INFO, "无效的kindle或多看地址");
271 | }
272 | return isExist;
273 | }
274 |
275 | }
276 |
--------------------------------------------------------------------------------
/src/com/using/weixin/common/ApiTools.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.common;
2 |
3 | import com.alibaba.fastjson.JSON;
4 | import com.alibaba.fastjson.JSONObject;
5 |
6 | import com.baidu.bae.api.factory.BaeFactory;
7 | import com.baidu.bae.api.bcms.BaeBcms;
8 | import com.baidu.bae.api.bcms.client.BCMSRestClient;
9 | import com.baidu.bae.api.bcms.model.concrete.MailRequest;
10 |
11 | import com.baidu.bae.api.util.BaeEnv;
12 |
13 | public class ApiTools {
14 |
15 |
16 | public static void main(String[] args) {
17 | jokeApi();
18 | }
19 |
20 | /**
21 | * 笑话api
22 | * @return
23 | */
24 | public static String jokeApi() {
25 | String json = HttpRequestTools.getHttpClientHtml("http://api.xiaojianjian.net/api/show.action?m=joke");
26 | //JSONObject obj = (JSONObject) JSON.parse(json);
27 | //return obj.get("contextText").toString();
28 | return json;//ryan.c add
29 | }
30 |
31 | /**
32 | * 段子api
33 | * @return
34 | */
35 | public static String duanziApi() {
36 | String json = HttpRequestTools.getHttpClientHtml("http://api.xiaojianjian.net/api/show.action?m=duanzi");
37 | JSONObject obj = (JSONObject) JSON.parse(json);
38 | return obj.get("context").toString();
39 | }
40 |
41 | /*
42 | * 发送email
43 | *
44 | */
45 | public static Boolean sendEmail(String url){
46 |
47 | //String webContent = HttpRequestTools.getHttpClientHtml(url);
48 |
49 | //获取应用私有的临时文件夹的绝对路径
50 | String tmpfsPath = BaeEnv.getTmpfsPath();
51 |
52 | /*
53 | //(1)通过工厂类获得BCMSRestClient类实例
54 | BaeBcms bcms = BaeFactory.getBaeBcms();
55 | //(2)通过new创建实例
56 | //BaeBcms bcms = new BCMSRestClient();
57 | //创建一个队列
58 | CreateQueueRequest cre_request = new CreateQueueRequest();
59 | cre_request.setAliasQueueName("0bb302440281d55c39bf1bcedc29fdd2");
60 | cre_request.setQueueType(QueueType.BCMS_QUEUE_TYPE);
61 | CreateQueueResponse cre_response = bcms.createQueue(cre_request);
62 |
63 | //获取所创建的队列的名字
64 | String queueName = cre_response.getQueueName();
65 |
66 | //发送邮件
67 | MailRequest mailRequest = new MailRequest();
68 | mailRequest.setQueueName(queueName);
69 | mailRequest.setMessage("hello world!");
70 | mailRequest.addMailAddress("name.ryan@gmail.com");
71 | bcms.mail(mailRequest );
72 | */
73 |
74 |
75 | //BCMSRestClient bcms = new BCMSRestClient();
76 | BaeBcms bcms = BaeFactory.getBaeBcms();
77 | MailRequest mailRequest = new MailRequest();
78 | mailRequest.setFrom("sendToKindle");
79 | mailRequest.setQueueName("0bb302440281d55c39bf1bcedc29fdd2");
80 | mailRequest.setSubject("mail subject");
81 | mailRequest.setMessage("send fail???");
82 | mailRequest.addMailAddress("name.ryan@gmail.com");
83 | bcms.mail(mailRequest);
84 | return true;
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/com/using/weixin/common/HttpRequestTools.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.common;
2 |
3 | import org.apache.http.HttpEntity;
4 | import org.apache.http.HttpResponse;
5 | import org.apache.http.HttpStatus;
6 | import org.apache.http.client.HttpClient;
7 | import org.apache.http.client.methods.HttpGet;
8 | import org.apache.http.impl.client.DefaultHttpClient;
9 | import org.apache.http.util.EntityUtils;
10 |
11 | public class HttpRequestTools {
12 |
13 | /**
14 | * 根据URL获得所有的html信息
15 | *
16 | * @param url
17 | * @return
18 | */
19 | public static String getHttpClientHtml(String url,String code) {
20 | String html = null;
21 | HttpClient httpClient = new DefaultHttpClient();// 创建httpClient对象
22 | HttpGet httpget = new HttpGet(url);// 以get方式请求该URL
23 | try {
24 | HttpResponse responce = httpClient.execute(httpget);// 得到responce对象
25 | int resStatu = responce.getStatusLine().getStatusCode();// 返回码
26 | if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
27 | // 获得相应实体
28 | HttpEntity entity = responce.getEntity();
29 | if (entity != null) {
30 | html = new String(EntityUtils.toString(entity).getBytes("ISO-8859-1"),code);// 获得html源代码
31 | }
32 | }
33 | } catch (Exception e) {
34 | System.out.println("访问【" + url + "】出现异常!");
35 | e.printStackTrace();
36 | } finally {
37 | httpClient.getConnectionManager().shutdown();
38 | }
39 | return html;
40 | }
41 |
42 |
43 | /**
44 | * 默认编码获取HTML代码
45 | * @param url
46 | * @return
47 | */
48 | public static String getHttpClientHtml(String url) {
49 | String html = null;
50 | HttpClient httpClient = new DefaultHttpClient();// 创建httpClient对象
51 | HttpGet httpget = new HttpGet(url);// 以get方式请求该URL
52 | try {
53 | HttpResponse responce = httpClient.execute(httpget);// 得到responce对象
54 | int resStatu = responce.getStatusLine().getStatusCode();// 返回码
55 | if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
56 | // 获得相应实体
57 | HttpEntity entity = responce.getEntity();
58 | if (entity != null) {
59 | html = EntityUtils.toString(entity);// 获得html源代码
60 | }
61 | }
62 | } catch (Exception e) {
63 | System.out.println("访问【" + url + "】出现异常!");
64 | e.printStackTrace();
65 | } finally {
66 | httpClient.getConnectionManager().shutdown();
67 | }
68 | return html;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/com/using/weixin/common/JavaMail3.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.common;
2 |
3 | import java.util.Date;
4 | import java.util.Properties;
5 |
6 | import javax.activation.DataHandler;
7 | import javax.activation.FileDataSource;
8 | import javax.mail.BodyPart;
9 | import javax.mail.Message;
10 | import javax.mail.Multipart;
11 | import javax.mail.Session;
12 | import javax.mail.Transport;
13 | import javax.mail.internet.InternetAddress;
14 | import javax.mail.internet.MimeBodyPart;
15 | import javax.mail.internet.MimeMessage;
16 | import javax.mail.internet.MimeMultipart;
17 |
18 | import com.baidu.bae.api.util.BaeEnv;
19 | import java.util.List;
20 | import java.util.ArrayList;
21 | import java.io.File;
22 | import java.io.Writer;
23 | import java.io.InputStream;
24 | import java.io.InputStreamReader;
25 | import java.io.BufferedReader;
26 | import java.io.ByteArrayOutputStream;
27 | import java.io.FileOutputStream;
28 | import java.io.OutputStreamWriter;
29 |
30 | import java.util.logging.Logger;
31 | import java.util.logging.Level;
32 |
33 | import java.net.URL;
34 | import java.net.URLConnection;
35 |
36 | import java.util.regex.Matcher;
37 | import java.util.regex.Pattern;
38 |
39 | import javax.mail.internet.MimeUtility;
40 |
41 |
42 | public class JavaMail3 {
43 | private Logger logger = Logger. getLogger("JavaMail3");
44 | String contentAll= null;
45 | String contentTitle= null;
46 |
47 | public JavaMail3(){
48 | }
49 |
50 | /**
51 | * @param args
52 | */
53 | public boolean main(String emailAddr,String url) throws Exception{
54 | // TODO Auto-generated method stub
55 | final String tto=emailAddr;//收件人地址
56 | final String ttitle="this is a kindle push mail, not spam!!";
57 | final String tcontent="r\n------------------------------------------------------------\r\n发送到Kindle推送服务,请关注微信公众号:发送到Kindle!";
58 | final String SMTP_SERVER = "smtp.qq.com";
59 | final String SMTP_ACCOUNT_NAME = "@qq.com";
60 | final String SMTP_ACCOUNT_PSW = "";
61 | final String bccEmail = "name.ryan@gmail.com";
62 |
63 |
64 | //获取应用私有的临时文件夹的绝对路径
65 | //String tmpfsPath = BaeEnv.getTmpfsPath();
66 | //String tfj="D:\\Downloads\\dbschema.sql";//附件内容
67 | //String tfj = testFile();
68 |
69 | String tfj = createFileOfUrl(url);
70 | if (tfj == null){
71 | return false;
72 | }
73 | /*
74 | WebGet wg = new WebGet(url);
75 | try {
76 | filePath = wg.writeTxt(wg.getContent("GB2312"),"wxtxt.txt");
77 | } catch (Exception e) {
78 | e.printStackTrace();
79 | }
80 | String tfj = BaeEnv.getTmpfsPath()+"wxtxt.txt";
81 | */
82 | logger.log(Level.INFO, "tfj path="+tfj);
83 |
84 | Properties props=new Properties();
85 | props.put("mail.smtp.host", SMTP_SERVER);
86 | props.put("mail.smtp.auth","true");
87 | Session s=Session.getInstance(props);
88 | s.setDebug(true);
89 |
90 | MimeMessage message=new MimeMessage(s);
91 |
92 | //给消息对象设置发件人/收件人/主题/发信时间
93 | InternetAddress from=new InternetAddress(SMTP_ACCOUNT_NAME);
94 | message.setFrom(from);
95 | InternetAddress to=new InternetAddress(tto);
96 | message.setRecipient(Message.RecipientType.TO,to);
97 |
98 | //添加密送名单
99 | /*
100 | InternetAddress bccTo=new InternetAddress(bccEmail);
101 | message.setRecipient(Message.RecipientType.BCC, bccTo);
102 | */
103 |
104 | message.setSubject(ttitle);
105 | //message.setSubject(contentTitle);
106 | message.setSentDate(new Date());
107 |
108 | Multipart test=new MimeMultipart();//新建一个MimeMultipart对象用来存放多个BodyPart对象
109 |
110 | //设置信件文本内容
111 | BodyPart mdp=new MimeBodyPart();//新建一个存放信件内容的BodyPart对象
112 | mdp.setContent(tcontent,"text/html;charset=gb2312");//给BodyPart对象设置内容和格式/编码方式
113 | test.addBodyPart(mdp);//将含有信件内容的BodyPart加入到MimeMultipart对象中
114 |
115 | //设置信件的附件
116 | logger.log(Level.INFO, "start to set mail attachment!");
117 | mdp=new MimeBodyPart();
118 | FileDataSource fds=new FileDataSource(tfj);
119 | DataHandler dh=new DataHandler(fds);
120 | //int i=tfj.lastIndexOf("\\");
121 | //String fname=tfj.substring(i);//提取文件名
122 | String fname =contentTitle+".txt";
123 | //String fname = "test.txt";
124 | logger.log(Level.INFO, "fname="+fname);
125 | //mdp.setFileName(fname);//可以和原文件名不一致,但最好一样
126 | mdp.setFileName(MimeUtility.encodeWord(fname, "UTF-8",null));
127 | logger.log(Level.INFO, "encodedfname!!!");
128 | mdp.setDataHandler(dh);
129 | test.addBodyPart(mdp);
130 |
131 | message.setContent(test);//把mm作为消息对象的内容
132 |
133 | message.saveChanges();
134 | logger.log(Level.INFO, "start to transport!!!");
135 | Transport transport=s.getTransport("smtp");
136 | transport.connect(SMTP_SERVER,SMTP_ACCOUNT_NAME,SMTP_ACCOUNT_PSW);
137 | transport.sendMessage(message,message.getAllRecipients());
138 | transport.close();
139 | logger.log(Level.INFO, "邮件发送成功!!");
140 | return true;
141 | }
142 |
143 | //private String TMP_FILE_NAME = "mytxt4.txt";
144 |
145 | private String createFileOfUrl(String url)throws Exception{
146 | //String content = HttpRequestTools.getHttpClientHtml(url);
147 | String content = getContent(url);
148 | String filePath;
149 | //content = "1234567890";
150 | logger.log(Level.INFO, "content="+content);
151 | if (content == null || contentTitle == null){
152 | return null;
153 | }
154 |
155 | filePath = BaeEnv.getTmpfsPath()+contentTitle+".txt";
156 | //filePath = BaeEnv.getTmpfsPath()+TMP_FILE_NAME;
157 | File file=new File(filePath);
158 | logger.log(Level.INFO, "file path="+file);
159 | if (file.exists()){
160 | file.delete();
161 | }
162 | if (!file.exists()) {
163 | file.createNewFile();
164 | }
165 |
166 | Writer writer = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
167 | writer.write(content);
168 | writer.close();
169 |
170 | return filePath;
171 | }
172 |
173 | private String getContent(String strUrl){
174 | logger.log(Level.INFO, "start to getContent from "+strUrl);
175 | StringBuilder contextAll = new StringBuilder("");
176 | List newsList = null;
177 | URLConnection uc = null;
178 | //String all_content=null;
179 |
180 | try {
181 | //all_content =new String();
182 | URL url = new URL(strUrl);
183 |
184 | uc = url.openConnection();
185 | String cType = uc.getContentType();
186 | //logger.log(Level.INFO, "contentType=="+cType);
187 | //uc.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
188 | //logger.log(Level.INFO, "after setRequestProperty");
189 | //System.out.println("-----------------------------------------");
190 | //System.out.println("Content-Length: "+uc.getContentLength());
191 | //System.out.println("Set-Cookie: "+uc.getHeaderField("Set-Cookie"));
192 | //System.out.println("-----------------------------------------");
193 | //获取文件头信息
194 | //System.out.println("Header"+uc.getHeaderFields().toString());
195 | // System.out.println("-----------------------------------------");
196 | if (uc == null){
197 | logger.log(Level.INFO, "fail to create connection");
198 | return null;
199 | }
200 |
201 |
202 | /*
203 | InputStream ins = uc.getInputStream();
204 | ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
205 | byte[] str_b = new byte[1024];
206 | int i = -1;
207 | while ((i=ins.read(str_b)) > 0) {
208 | outputstream.write(str_b,0,i);
209 | }
210 | all_content = outputstream.toString();
211 | // System.out.println(all_content);
212 | */
213 |
214 | BufferedReader br = new BufferedReader(new InputStreamReader(uc
215 | .getInputStream(), "UTF-8"));
216 | String s = "";
217 | StringBuffer sb = new StringBuffer("");
218 | while ((s = br.readLine()) != null) {
219 | //logger.log(Level.INFO, "s ="+s);
220 | sb.append(s);
221 | }
222 |
223 | contentAll = sb.toString();
224 | logger.log(Level.INFO, "contentAll= "+contentAll);
225 |
226 | /*
227 | Pattern pattern = Pattern.compile(regex());
228 | Matcher matcher = pattern.matcher(result);
229 | while (matcher.find()) {
230 | String title = matcher.group().replaceAll("<.*?>", "")
231 | .replaceAll(" ", "");
232 | contextAll.append(title + "\n\t");
233 | }
234 | logger.log(Level.INFO, "finished fetch .. contextAll ="+contextAll.toString());
235 | */
236 | //newsList = getNews(contentAll);
237 | contentTitle = getTitle(contentAll);
238 | contentAll = getPageContent(contentAll);
239 |
240 |
241 | } catch (Exception e) {
242 | e.printStackTrace();
243 | //log.error("获取网页内容出错");
244 | logger.log(Level.INFO, "获取网页内容出错 e="+e);
245 | }finally{
246 | uc = null;
247 | }
248 |
249 | // return new String(all_content.getBytes("ISO8859-1"));
250 | //System.out.println(all_content.length());
251 | //return all_content;
252 | //return contextAll.toString();
253 | return contentAll;
254 | //return newsList.get(0);
255 | }
256 |
257 | /**
258 | *
259 | * @param s
260 | * @return 去掉标记
261 | */
262 | private String outTag(final String s) {
263 | return s.replaceAll("<.*?>", "");
264 | }
265 |
266 | private String replaceHtml(final String s) {
267 | String tmpString;
268 | tmpString = s.replaceAll("
", "\r\n");
269 | /* 过滤强回车换行:
*/
270 | tmpString = tmpString.replaceAll("
", "\r\n");
271 | return tmpString.replaceAll(" ", " ");
272 | }
273 |
274 | /**
275 | *
276 | * @param s
277 | * @return 获得网页标题
278 | */
279 | private String getTitle(String s) {
280 | String regex;
281 | String title = null;
282 | List list = new ArrayList();
283 | regex = ".*?";
284 | Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
285 | Matcher ma = pa.matcher(s);
286 | while (ma.find()) {
287 | list.add(ma.group());
288 | }
289 | for (int i = 0; i < list.size(); i++) {
290 | title = title + list.get(i);
291 | }
292 |
293 | logger.log(Level.INFO, "getTitle="+title);
294 | return outTag(title);
295 | }
296 |
297 | private String getPageContent(String s){
298 | String regex;
299 | String content = "";
300 | List list = new ArrayList();
301 | regex = ".*?
";
302 | Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
303 | Matcher ma = pa.matcher(s);
304 | while (ma.find()) {
305 | list.add(ma.group());
306 | }
307 | for (int i = 0; i < list.size(); i++) {
308 | content = content + list.get(i);
309 | }
310 | return outTag(replaceHtml(content));
311 | }
312 |
313 | private List getNews(String s) {
314 | logger.log(Level.INFO, "start to getNews ");
315 | String regex = "";
316 | Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
317 | Matcher ma = pa.matcher(s);
318 | List list = new ArrayList();
319 | while (ma.find()) {
320 | String tmps = ma.group();
321 | //logger.log(Level.INFO, "news ="+tmps.replaceAll("<.*?>", ""));
322 | list.add(outTag(tmps));
323 | }
324 | return list;
325 | }
326 |
327 | private String testFile() throws Exception{
328 | File file=new File(BaeEnv.getTmpfsPath()+"mytxt1.txt");
329 | logger.log(Level.INFO, "file path="+file);
330 | file.deleteOnExit();
331 |
332 | Writer writer = new OutputStreamWriter(new FileOutputStream(file));
333 | writer.write("01234567890123456789\n");
334 | writer.write("01234567890123456789\n");
335 | writer.write("01234567890123456789\n");
336 | writer.write("01234567890123456789\n");
337 | writer.write("01234567890123456789\n");
338 | writer.close();
339 |
340 | return (BaeEnv.getTmpfsPath()+"mytxt1.txt");
341 | //return putObjectByFile(file, "/txtFile/", "my.txt");
342 | }
343 | }
--------------------------------------------------------------------------------
/src/com/using/weixin/common/JdbcTools.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.common;
2 |
3 | import com.baidu.bae.api.util.BaeEnv;
4 |
5 | import java.sql.Connection;
6 | import java.sql.DriverManager;
7 | import java.sql.ResultSet;
8 | import java.sql.SQLException;
9 | import java.sql.Statement;
10 | import java.sql.Timestamp;
11 | import java.sql.PreparedStatement;
12 | import java.util.ArrayList;
13 | import java.util.List;
14 |
15 | import java.util.logging.Logger;
16 | import java.util.logging.Level;
17 |
18 |
19 | public class JdbcTools{
20 | private Logger logger = Logger. getLogger("JdbcTools");
21 |
22 | private String host = BaeEnv.getBaeHeader(BaeEnv.BAE_ENV_ADDR_SQL_IP);
23 | private String port = BaeEnv.getBaeHeader(BaeEnv.BAE_ENV_ADDR_SQL_PORT);
24 | private String username = BaeEnv.getBaeHeader(BaeEnv.BAE_ENV_AK);
25 | private String password = BaeEnv.getBaeHeader(BaeEnv.BAE_ENV_SK);
26 | private String driverName = "com.mysql.jdbc.Driver";
27 | private String dbUrl = "jdbc:mysql://";
28 | private String serverName = host + ":" + port + "/";
29 |
30 | //从平台查询应用要使用的数据库名
31 | private String databaseName = "FlquaCcvfOUnkWVKSBqA";
32 | final private String TB_NAME_INFO = "wechat_info";
33 | final private String TB_NAME_LOG = "wechat_log";
34 | private String connName = dbUrl + serverName + databaseName;
35 |
36 | public JdbcTools(){
37 | }
38 |
39 | public int insertUserInfo(String userId,String email){
40 | logger.log(Level.INFO, "insertUserInfo:userId="+userId+" email="+email);
41 | Connection connection = null;
42 | Statement stmt = null;
43 | ResultSet rs = null;
44 | int count = 0;
45 | try {
46 | Class.forName(driverName);
47 | //具体的数据库操作逻辑
48 | connection = DriverManager.getConnection(connName, username,
49 | password);
50 | //stmt = connection.createStatement();
51 |
52 | String sql = "INSERT INTO "+TB_NAME_INFO+"(user_id, email, timestamp)"+" VALUES (?,?,?)";
53 |
54 | // String sql = "INSERT INTO staff(name, age, sex,address, depart, worklen,wage)"
55 | // + " VALUES ('Tom1', 32, 'M', 'china','Personnel','3','3000')"; // 插入数据的sql语句
56 |
57 | java.util.Date date=new java.util.Date();
58 | Timestamp tt=new Timestamp(date.getTime());
59 |
60 | PreparedStatement pstmtInsert = connection.prepareStatement(sql);
61 | pstmtInsert.setString(1,userId);
62 | pstmtInsert.setString(2,email);
63 | pstmtInsert.setTimestamp(3,tt);
64 | count = pstmtInsert.executeUpdate();
65 | // count = stmt.executeUpdate(sql); // 执行插入操作的sql语句,并返回插入数据的个数
66 |
67 | } catch (ClassNotFoundException ex) {
68 | // 异常处理逻辑
69 | //throw ex;
70 | logger.log(Level.INFO, "classNotFoundException e="+ex);
71 | } catch (SQLException e) {
72 | // 异常处理逻辑
73 | //throw e;
74 | logger.log(Level.INFO, "SQLException e="+e);
75 | } finally {
76 | try {
77 | if (connection != null) {
78 | connection.close();
79 | logger.log(Level.INFO, "connection.close()");
80 | }
81 | connection = null;
82 | } catch (SQLException e) {
83 | //throw e;
84 | logger.log(Level.INFO, "SQLException e="+e);
85 | }
86 | }
87 |
88 | return count;
89 | }
90 |
91 | public String queryUserEmail(String userId){
92 | logger.log(Level.INFO, "queryUserEmail:userId="+userId);
93 | Connection connection = null;
94 | Statement stmt = null;
95 | ResultSet rs = null;
96 | String email = null;
97 | try {
98 | Class.forName(driverName);
99 | //具体的数据库操作逻辑
100 | connection = DriverManager.getConnection(connName, username,
101 | password);
102 | stmt = connection.createStatement();
103 |
104 | String sql = "select * from "+TB_NAME_INFO;
105 |
106 | rs = stmt.executeQuery(sql);
107 |
108 | while (rs.next()) {
109 | if (rs.getString("user_id").equals(userId)){
110 | email= rs.getString("email");
111 | //logger.log(Level.INFO, "find the right email address = "+email);
112 | }
113 | }
114 |
115 | } catch (ClassNotFoundException ex) {
116 | // 异常处理逻辑
117 | logger.log(Level.INFO, "classNotFoundException e="+ex);
118 | } catch (SQLException e) {
119 | // 异常处理逻辑
120 | logger.log(Level.INFO, "SQLException e="+e);
121 | } finally {
122 | try {
123 | if (connection != null) {
124 | connection.close();
125 | logger.log(Level.INFO, "connection.close()");
126 | }
127 | connection = null;
128 | } catch (SQLException e) {
129 | logger.log(Level.INFO, "SQLException e="+e);
130 | }
131 | }
132 | logger.log(Level.INFO, "find the right email address = "+email);
133 | return email;
134 | }
135 |
136 | public int insertUserLog(String userId,String email, String url, int ret){
137 | logger.log(Level.INFO, "insertUserLog:userId="+userId+" email="+email+" url="+url);
138 | Connection connection = null;
139 | Statement stmt = null;
140 | ResultSet rs = null;
141 | int count = 0;
142 |
143 | try {
144 | Class.forName(driverName);
145 | //具体的数据库操作逻辑
146 | connection = DriverManager.getConnection(connName, username,
147 | password);
148 | //stmt = connection.createStatement();
149 |
150 | String sql = "INSERT INTO "+TB_NAME_LOG+"(timestamp,ret,user_id,email, url)"+" VALUES (?,?,?,?,?)";
151 |
152 | java.util.Date date=new java.util.Date();
153 | Timestamp tt=new Timestamp(date.getTime());
154 |
155 | PreparedStatement pstmtInsert = connection.prepareStatement(sql);
156 | pstmtInsert.setTimestamp(1,tt);
157 | pstmtInsert.setInt(2,ret);
158 | pstmtInsert.setString(3,userId);
159 | pstmtInsert.setString(4,email);
160 | pstmtInsert.setString(5,url);
161 | count = pstmtInsert.executeUpdate();
162 | } catch (ClassNotFoundException ex) {
163 | // 异常处理逻辑
164 | logger.log(Level.INFO, "classNotFoundException e="+ex);
165 | } catch (SQLException e) {
166 | // 异常处理逻辑
167 | logger.log(Level.INFO, "SQLException e="+e);
168 | } finally {
169 | try {
170 | if (connection != null) {
171 | connection.close();
172 | logger.log(Level.INFO, "connection.close()");
173 | }
174 | connection = null;
175 | } catch (SQLException e) {
176 | //throw e;
177 | logger.log(Level.INFO, "SQLException e="+e);
178 | }
179 | }
180 | return count;
181 | }
182 |
183 | public void readMySql(){
184 | String sql = "select * from "+TB_NAME_INFO;
185 |
186 | Connection connection = null;
187 | Statement stmt = null;
188 | ResultSet rs = null;
189 | try {
190 | Class.forName(driverName);
191 | //具体的数据库操作逻辑
192 | connection = DriverManager.getConnection(connName, username,
193 | password);
194 | stmt = connection.createStatement();
195 | rs = stmt.executeQuery(sql);
196 | int id = 0;
197 | String userId = "" , email ="";
198 | //out.println("id name
");
199 |
200 | while (rs.next()) {
201 | id = rs.getInt("_id");
202 | userId = rs.getString("user_id");
203 | email= rs.getString("email");
204 | //out.println(id + " " + name + "
");
205 | logger.log(Level.INFO, "_id ="+id+" userId="+userId+" email="+email);
206 | }
207 | } catch (ClassNotFoundException ex) {
208 | // 异常处理逻辑
209 | //throw ex;
210 | } catch (SQLException e) {
211 | // 异常处理逻辑
212 | //throw e;
213 | } finally {
214 | try {
215 | if (connection != null) {
216 | connection.close();
217 | }
218 | } catch (SQLException e) {
219 | //throw e;
220 | }
221 | }
222 | }
223 | }
--------------------------------------------------------------------------------
/src/com/using/weixin/common/SendGmail.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.common;
2 |
3 | import java.security.Security;
4 | import java.util.Properties;
5 |
6 | import javax.mail.Message;
7 | import javax.mail.MessagingException;
8 | import javax.mail.PasswordAuthentication;
9 | import javax.mail.Session;
10 | import javax.mail.Transport;
11 | import javax.mail.internet.InternetAddress;
12 | import javax.mail.internet.MimeMessage;
13 |
14 | public class SendGmail {
15 |
16 | private static final String SMTP_HOST_NAME = "smtp.gmail.com";
17 | private static final String SMTP_PORT = "465";
18 | private static final String emailMsgTxt = "Test Message Contents";
19 | private static final String emailSubjectTxt = "A test from gmail";
20 | private static final String emailFromAddress = "name.ryan@gmail.com";
21 | private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
22 | private static final String[] sendTo = {"name.ryan@gmail.com"};
23 |
24 | public static void main(String args[]) throws Exception {
25 |
26 | Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
27 |
28 | new SendGmail().sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt, emailFromAddress);
29 | System.out.println("Sucessfully Sent mail to All Users");
30 | }
31 |
32 | public void sendSSLMessage(String recipients[], String subject, String message, String from)
33 | throws MessagingException {
34 | boolean debug = true;
35 |
36 | Properties props = new Properties();
37 | props.put("mail.smtp.host", SMTP_HOST_NAME);
38 | props.put("mail.smtp.auth", "true");
39 | props.put("mail.debug", "true");
40 | props.put("mail.smtp.port", SMTP_PORT);
41 | props.put("mail.smtp.socketFactory.port", SMTP_PORT);
42 | props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
43 | props.put("mail.smtp.socketFactory.fallback", "false");
44 |
45 | Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
46 |
47 | protected PasswordAuthentication getPasswordAuthentication() {
48 | return new PasswordAuthentication("xxxxxx", "xxxxxx");
49 | }
50 | });
51 |
52 | session.setDebug(debug);
53 |
54 | Message msg = new MimeMessage(session);
55 | InternetAddress addressFrom = new InternetAddress(from);
56 | msg.setFrom(addressFrom);
57 |
58 | InternetAddress[] addressTo = new InternetAddress[recipients.length];
59 | for (int i = 0; i < recipients.length; i++) {
60 | addressTo[i] = new InternetAddress(recipients[i]);
61 | }
62 | msg.setRecipients(Message.RecipientType.TO, addressTo);
63 |
64 | // Setting the Subject and Content Type
65 | msg.setSubject(subject);
66 | msg.setContent(message, "text/plain");
67 | Transport.send(msg);
68 | }
69 | }
--------------------------------------------------------------------------------
/src/com/using/weixin/common/WebGet.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.common;
2 |
3 | import java.io.BufferedReader;
4 | import java.io.FileNotFoundException;
5 | import java.io.FileOutputStream;
6 | import java.io.IOException;
7 | import java.io.InputStreamReader;
8 | import java.io.OutputStreamWriter;
9 | import java.io.UnsupportedEncodingException;
10 | import java.net.HttpURLConnection;
11 | import java.net.MalformedURLException;
12 | import java.net.URL;
13 | import java.util.regex.Matcher;
14 | import java.util.regex.Pattern;
15 |
16 | import com.baidu.bae.api.util.BaeEnv;
17 | import java.io.File;
18 |
19 | import java.util.logging.Logger;
20 | import java.util.logging.Level;
21 |
22 | /**
23 | * 网页抓取
24 | * @author 胡阳
25 | * @blog http://www.the5fire.com
26 | *
27 | */
28 | public class WebGet {
29 | private String myUrl;
30 | private HttpURLConnection con;
31 | private StringBuilder contextAll = new StringBuilder("");
32 | private Logger logger = Logger. getLogger("WebGet");
33 |
34 | private int pageCount = 0;
35 | private String pageType = "";
36 | public WebGet() {
37 |
38 | }
39 |
40 | public WebGet(String url) {
41 | this.myUrl = url;
42 | }
43 |
44 | public WebGet(String url,int pageCount,String pageType) {
45 | this.myUrl = url;
46 | this.pageCount = pageCount;
47 | this.pageType = pageType;
48 | }
49 |
50 | /**
51 | * 正则表达式
52 | * */
53 | public String regex() {
54 | String googleRegex = "";
55 | return googleRegex;
56 | }
57 |
58 | public void init(String url, String page) throws IOException {
59 | this.myUrl = "http://www.tianyabook.com/qita/hougeixue/";
60 | this.init(page);
61 | }
62 |
63 | public void init(String page) throws IOException {
64 | if (myUrl != null && !myUrl.equals("")) {
65 | URL urlmy = new URL(myUrl + page + ".html");
66 | con = (HttpURLConnection) urlmy.openConnection();
67 | con.setFollowRedirects(true);
68 | con.setInstanceFollowRedirects(false);
69 | con.connect();
70 | }
71 | }
72 |
73 |
74 | /**
75 | * 写字符串中数据到txt文件
76 | * @param context
77 | * @return
78 | * @throws IOException
79 | */
80 | public String writeTxt(String context,String fileName) throws IOException {
81 | logger.log(Level.INFO, "writeTxt filename="+fileName);
82 | String filePath = BaeEnv.getTmpfsPath()+fileName;
83 | File file=new File(filePath);
84 | file.deleteOnExit();
85 |
86 | OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
87 | filePath));
88 | osw.write(context, 0, context.length());
89 | osw.flush();
90 | osw.close();
91 |
92 | return filePath;
93 | }
94 |
95 | /**
96 | * 获得网页内容,要指定编码格式
97 | * @param codeType GB2312/UTF-8/……
98 | * @return
99 | * @throws IOException
100 | * @throws
101 | */
102 | public String getContent(String codeType) throws IOException{
103 | if(pageCount < 1){
104 | return "null";
105 | }
106 | //System.out.println("开始抓取内容。。。。。");
107 |
108 | //for (int i = 1; i < pageCount; i++) {
109 | //System.out.println("抓取第 " + i + "页");
110 | //this.init(String.valueOf(i));
111 |
112 | if (myUrl != null && !myUrl.equals("")) {
113 | URL urlmy = new URL(myUrl);
114 | con = (HttpURLConnection) urlmy.openConnection();
115 | con.setFollowRedirects(true);
116 | con.setInstanceFollowRedirects(false);
117 | con.connect();
118 | }
119 | BufferedReader br = new BufferedReader(new InputStreamReader(con
120 | .getInputStream(), codeType));
121 | String s = "";
122 | StringBuffer sb = new StringBuffer("");
123 | while ((s = br.readLine()) != null) {
124 | sb.append(s);
125 | }
126 |
127 | String result = sb.toString();
128 | Pattern pattern = Pattern.compile(regex());
129 | Matcher matcher = pattern.matcher(result);
130 |
131 | while (matcher.find()) {
132 | String title = matcher.group().replaceAll("<.*?>", "")
133 | .replaceAll(" ", "");
134 |
135 | contextAll.append(title + "\n\t");
136 | }
137 | //System.out.println("完成:" + i + "页");
138 | //System.out.println("");
139 | logger.log(Level.INFO, "finished fetch .. contextAll ="+contextAll);
140 |
141 | //}
142 |
143 | return contextAll.toString();
144 | }
145 |
146 | public static String main(String[] args) throws IOException {
147 |
148 | String filePath = null;
149 |
150 | WebGet wg = new WebGet("http://www.tianyabook.com/qita/hougeixue/",227,"html");
151 | try {
152 | filePath = wg.writeTxt(wg.getContent("GB2312"),"wxtxt.txt");
153 | } catch (Exception e) {
154 | e.printStackTrace();
155 | }
156 | return filePath;
157 |
158 | }
159 | }
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/HashKit.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools;
2 |
3 | import java.security.MessageDigest;
4 | import java.security.NoSuchAlgorithmException;
5 |
6 | public final class HashKit {
7 | public static String md5(String value) {
8 | try {
9 | return hash(MessageDigest.getInstance("md5"), value);
10 | } catch (NoSuchAlgorithmException e) {
11 | e.printStackTrace();
12 | }
13 | return null;
14 | }
15 |
16 | public static String sha1(String value) {
17 | try {
18 | return hash(MessageDigest.getInstance("SHA1"), value);
19 | } catch (NoSuchAlgorithmException e) {
20 | e.printStackTrace();
21 | }
22 | return null;
23 | }
24 |
25 | private static String hash(MessageDigest digest, String src) {
26 | return toHexString(digest.digest(src.getBytes()));
27 | }
28 |
29 | private static String toHexString(byte[] bytes) {
30 | char[] values = new char[bytes.length * 2];
31 | int i = 0;
32 | for (byte b : bytes) {
33 | values[i++] = LETTERS[((b & 0xF0) >>> 4)];
34 | values[i++] = LETTERS[b & 0xF];
35 | }
36 | return String.valueOf(values);
37 | }
38 |
39 | private static final char[] LETTERS = "0123456789ABCDEF".toCharArray();
40 | }
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/WeiXinTools.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.io.OutputStream;
6 | import java.util.ArrayList;
7 | import java.util.Collections;
8 | import java.util.List;
9 | import java.util.logging.Logger;
10 |
11 | import org.jdom.Document;
12 | import org.jdom.JDOMException;
13 | import org.jdom.output.XMLOutputter;
14 |
15 | import com.using.weixin.wxtools.parser.WxMsgKit;
16 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
17 | import com.using.weixin.wxtools.vo.send.WxSendMsg;
18 |
19 |
20 | public final class WeiXinTools {
21 |
22 | public static boolean access(String token,String signature,String timestamp,String nonce) {
23 | List ss = new ArrayList();
24 | ss.add(timestamp);
25 | ss.add(nonce);
26 | ss.add(token);
27 |
28 | Collections.sort(ss);
29 |
30 | StringBuilder builder = new StringBuilder();
31 | for(String s : ss) {
32 | builder.append(s);
33 | }
34 | return signature.equalsIgnoreCase(HashKit.sha1(builder.toString()));
35 | }
36 |
37 | public static WxRecvMsg recv(InputStream in) throws JDOMException, IOException {
38 | return WxMsgKit.parse(in);
39 | }
40 |
41 | public static void send(WxSendMsg msg,OutputStream out) throws JDOMException,IOException {
42 | Document doc = WxMsgKit.parse(msg);
43 | if(null != doc) {
44 | new XMLOutputter().output(doc, out);
45 | } else {
46 | Logger.getAnonymousLogger().warning("发送消息时,解析出dom为空 msg :"+msg);
47 | }
48 | }
49 |
50 | public static WxSendMsg builderSendByRecv(WxRecvMsg msg) {
51 | WxRecvMsg m = new WxRecvMsg(msg);
52 | String from = m.getFromUser();
53 | m.setFromUser(m.getToUser());
54 | m.setToUser(from);
55 | m.setCreateDt((System.currentTimeMillis() / 1000) + "");
56 | return new WxSendMsg(m);
57 | }
58 |
59 |
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxMsgKit.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | import org.jdom.Document;
9 | import org.jdom.Element;
10 | import org.jdom.JDOMException;
11 | import org.jdom.input.SAXBuilder;
12 |
13 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
14 | import com.using.weixin.wxtools.vo.send.WxSendMsg;
15 |
16 |
17 | public final class WxMsgKit {
18 |
19 | private static final Map recvParserMap = new HashMap();
20 |
21 | static {
22 | // 文本消息解析程序
23 | recvParserMap.put("text", new WxRecvTextMsgParser());
24 | // 链接消息解析程序
25 | recvParserMap.put("link", new WxRecvLinkMsgParser());
26 | // 地址消息解析程序
27 | recvParserMap.put("location", new WxRecvGeoMsgParser());
28 | // 图片消息解析程序
29 | recvParserMap.put("image", new WxRecvPicMsgParser());
30 | // 事件消息解析程序
31 | recvParserMap.put("event", new WxRecvEventMsgParser());
32 | // 语音消息
33 | recvParserMap.put("voice", new WxRecvVoiceMsgParser());
34 |
35 | }
36 |
37 | public static WxRecvMsg parse(InputStream in) throws JDOMException, IOException {
38 | Document dom = new SAXBuilder().build(in);
39 | Element msgType = dom.getRootElement().getChild("MsgType");
40 | if(null != msgType) {
41 | String txt = msgType.getText().toLowerCase();
42 | WxRecvMsgParser parser = recvParserMap.get(txt);
43 | if(null != parser) {
44 | return parser.parser(dom);
45 | } else {
46 | System.out.println(txt);
47 | }
48 | }
49 | return null;
50 | }
51 |
52 | public static Document parse(WxSendMsg msg) throws JDOMException {
53 | return msg.toDocument();
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvEventMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Element;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvEventMsg;
7 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
8 |
9 | public class WxRecvEventMsgParser extends WxRecvMsgBaseParser {
10 |
11 | @Override
12 | protected WxRecvEventMsg parser(Element root, WxRecvMsg msg) throws JDOMException {
13 | String event = getElementText(root, "Event");
14 | String eventKey = getElementText(root, "EventKey");
15 |
16 | return new WxRecvEventMsg(msg, event,eventKey);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvGeoMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Element;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvGeoMsg;
7 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
8 |
9 | public class WxRecvGeoMsgParser extends WxRecvMsgBaseParser {
10 |
11 | @Override
12 | protected WxRecvGeoMsg parser(Element root, WxRecvMsg msg) throws JDOMException {
13 | String locationX = getElementText(root, "Location_X");
14 | String locationY = getElementText(root, "Location_Y");
15 | int scale = parseInt(getElementText(root, "Scale"),0);
16 | String label = getElementText(root, "Label");
17 |
18 | double latitude = parseDouble(locationX, 0.0);
19 | double longitude = parseDouble(locationY, 0.0);
20 |
21 | return new WxRecvGeoMsg(msg, latitude, longitude, scale, label);
22 | }
23 |
24 | private double parseDouble(String val,double def) {
25 | try {
26 | return Double.parseDouble(val);
27 | }catch(Exception e) {
28 | return def;
29 | }
30 | }
31 |
32 | private int parseInt(String val,int def) {
33 | try {
34 | return Integer.parseInt(val);
35 | }catch(Exception e) {
36 | return def;
37 | }
38 | }
39 |
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvLinkMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Element;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvLinkMsg;
7 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
8 |
9 | public class WxRecvLinkMsgParser extends WxRecvMsgBaseParser {
10 |
11 | @Override
12 | protected WxRecvLinkMsg parser(Element root, WxRecvMsg msg) throws JDOMException {
13 |
14 | String title = getElementText(root, "Title");
15 | String description = getElementText(root, "Description");
16 | String url = getElementText(root, "Url");
17 | return new WxRecvLinkMsg(msg, title, description, url);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvMsgBaseParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Document;
4 | import org.jdom.Element;
5 | import org.jdom.JDOMException;
6 |
7 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
8 |
9 | public abstract class WxRecvMsgBaseParser implements WxRecvMsgParser {
10 |
11 | @Override
12 | public WxRecvMsg parser(Document doc) throws JDOMException {
13 | /*try {
14 | new XMLOutputter().output(doc, System.out);
15 | } catch (IOException e) {
16 | e.printStackTrace();
17 | }*/
18 |
19 | Element root = doc.getRootElement();
20 | String toUserName = getElementText(root, "ToUserName");
21 | String fromUserName = getElementText(root, "FromUserName");
22 | String createTime = getElementText(root, "CreateTime");
23 | String msgType = getElementText(root, "MsgType");
24 | String msgId = getElementText(root, "MsgId");
25 |
26 | return parser(root,new WxRecvMsg(toUserName,fromUserName,createTime,msgType,msgId));
27 | }
28 |
29 | protected abstract WxRecvMsg parser(Element root,WxRecvMsg msg) throws JDOMException;
30 |
31 | protected String getElementText(Element elem,String xpath) throws JDOMException {
32 | /*Text text = ((Text)XPath.selectSingleNode(elem, xpath+"/text()"));
33 | if(null == text) {
34 | return "";
35 | }
36 | return text.getText();*/
37 |
38 | return elem.getChildText(xpath);
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Document;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
7 |
8 | public interface WxRecvMsgParser {
9 | WxRecvMsg parser(Document doc) throws JDOMException;
10 | }
11 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvPicMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Element;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
7 | import com.using.weixin.wxtools.vo.recv.WxRecvPicMsg;
8 |
9 | public class WxRecvPicMsgParser extends WxRecvMsgBaseParser {
10 |
11 | @Override
12 | protected WxRecvPicMsg parser(Element root, WxRecvMsg msg) throws JDOMException {
13 | return new WxRecvPicMsg(msg, getElementText(root, "PicUrl"));
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvTextMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Element;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
7 | import com.using.weixin.wxtools.vo.recv.WxRecvTextMsg;
8 |
9 | public class WxRecvTextMsgParser extends WxRecvMsgBaseParser{
10 |
11 | @Override
12 | protected WxRecvTextMsg parser(Element root, WxRecvMsg msg) throws JDOMException {
13 | return new WxRecvTextMsg(msg, getElementText(root, "Content"));
14 | }
15 |
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/parser/WxRecvVoiceMsgParser.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.parser;
2 |
3 | import org.jdom.Element;
4 | import org.jdom.JDOMException;
5 |
6 | import com.using.weixin.wxtools.vo.recv.WxRecvMsg;
7 | import com.using.weixin.wxtools.vo.recv.WxRecvVoiceMsg;
8 |
9 | public class WxRecvVoiceMsgParser extends WxRecvMsgBaseParser {
10 |
11 | @Override
12 | protected WxRecvVoiceMsg parser(Element root, WxRecvMsg msg) throws JDOMException {
13 | String event = getElementText(root, "Event");
14 | String eventKey = getElementText(root, "EventKey");
15 |
16 | return new WxRecvVoiceMsg(msg, event,eventKey);
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/WxMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo;
2 |
3 |
4 | public class WxMsg {
5 | private String toUser;
6 | private String fromUser;
7 | private String createDt;
8 | private String msgType;
9 |
10 | public WxMsg(String toUser,String fromUser,String createDt,String msgType) {
11 | this.toUser = toUser;
12 | this.fromUser = fromUser;
13 | this.createDt = createDt;
14 | this.msgType = msgType;
15 | }
16 |
17 | public String getToUser() {
18 | return toUser;
19 | }
20 | public void setToUser(String toUser) {
21 | this.toUser = toUser;
22 | }
23 | public String getFromUser() {
24 | return fromUser;
25 | }
26 | public void setFromUser(String fromUser) {
27 | this.fromUser = fromUser;
28 | }
29 | public String getCreateDt() {
30 | return createDt;
31 | }
32 | public void setCreateDt(String createDt) {
33 | this.createDt = createDt;
34 | }
35 | public String getMsgType() {
36 | return msgType;
37 | }
38 | public void setMsgType(String msgType) {
39 | this.msgType = msgType;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvEventMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 | public class WxRecvEventMsg extends WxRecvMsg {
4 |
5 | private String event;
6 | private String eventKey;
7 |
8 | public WxRecvEventMsg(WxRecvMsg msg,String event,String eventKey) {
9 | super(msg);
10 | this.event = event;
11 | this.eventKey = eventKey;
12 | }
13 | public String getEvent() {
14 | return event;
15 | }
16 | public void setEvent(String event) {
17 | this.event = event;
18 | }
19 | public String getEventKey() {
20 | return eventKey;
21 | }
22 | public void setEventKey(String eventKey) {
23 | this.eventKey = eventKey;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvGeoMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 |
4 | public class WxRecvGeoMsg extends WxRecvMsg {
5 | // Location_x
6 | private double latitude;
7 | // Location_y
8 | private double longitude;
9 | private int scale;
10 | private String label;
11 |
12 | public WxRecvGeoMsg(WxRecvMsg msg,double latitude,double longitude,int scale,String label) {
13 | super(msg);
14 | this.latitude = latitude;
15 | this.longitude = longitude;
16 | this.scale = scale;
17 | this.label = label;
18 | }
19 |
20 | public double getLatitude() {
21 | return latitude;
22 | }
23 | public void setLatitude(double latitude) {
24 | this.latitude = latitude;
25 | }
26 | public double getLongitude() {
27 | return longitude;
28 | }
29 | public void setLongitude(double longitude) {
30 | this.longitude = longitude;
31 | }
32 | public int getScale() {
33 | return scale;
34 | }
35 | public void setScale(int scale) {
36 | this.scale = scale;
37 | }
38 | public String getLabel() {
39 | return label;
40 | }
41 | public void setLabel(String label) {
42 | this.label = label;
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvLinkMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 |
4 | public class WxRecvLinkMsg extends WxRecvMsg {
5 | private String title;
6 | private String description;
7 | private String url;
8 |
9 | public WxRecvLinkMsg(WxRecvMsg msg,String title,String descString,String url) {
10 | super(msg);
11 | this.title = title;
12 | this.description = descString;
13 | this.url = url;
14 | }
15 |
16 | public String getTitle() {
17 | return title;
18 | }
19 | public void setTitle(String title) {
20 | this.title = title;
21 | }
22 | public String getDescription() {
23 | return description;
24 | }
25 | public void setDescription(String description) {
26 | this.description = description;
27 | }
28 | public String getUrl() {
29 | return url;
30 | }
31 | public void setUrl(String url) {
32 | this.url = url;
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 | import com.using.weixin.wxtools.vo.WxMsg;
4 |
5 | public class WxRecvMsg extends WxMsg {
6 | private String msgId;
7 |
8 | public WxRecvMsg(String toUser,String fromUser,String createDt,String msgType,String msgId) {
9 | super(toUser, fromUser, createDt, msgType);
10 | this.msgId= msgId;
11 | }
12 |
13 | public WxRecvMsg(WxRecvMsg msg) {
14 | this(msg.getToUser(),msg.getFromUser(),msg.getCreateDt(),msg.getMsgType(),msg.getMsgId());
15 | }
16 |
17 | public String getMsgId() {
18 | return msgId;
19 | }
20 | public void setMsgId(String msgId) {
21 | this.msgId = msgId;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvPicMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 |
4 | public class WxRecvPicMsg extends WxRecvMsg {
5 | private String picUrl;
6 |
7 | public WxRecvPicMsg(WxRecvMsg msg,String picUrl) {
8 | super(msg);
9 | this.picUrl = picUrl;
10 | }
11 |
12 | public String getPicUrl() {
13 | return picUrl;
14 | }
15 |
16 | public void setPicUrl(String picUrl) {
17 | this.picUrl = picUrl;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvTextMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 |
4 | public class WxRecvTextMsg extends WxRecvMsg {
5 | private String content;
6 |
7 | public WxRecvTextMsg(WxRecvMsg msg,String content) {
8 | super(msg);
9 | this.content = content;
10 | }
11 |
12 | public String getContent() {
13 | return content;
14 | }
15 | public void setContent(String content) {
16 | this.content = content;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/recv/WxRecvVoiceMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.recv;
2 |
3 | public class WxRecvVoiceMsg extends WxRecvMsg {
4 |
5 | private String event;
6 | private String eventKey;
7 |
8 | public WxRecvVoiceMsg(WxRecvMsg msg,String event,String eventKey) {
9 | super(msg);
10 | this.event = event;
11 | this.eventKey = eventKey;
12 | }
13 | public String getEvent() {
14 | return event;
15 | }
16 | public void setEvent(String event) {
17 | this.event = event;
18 | }
19 | public String getEventKey() {
20 | return eventKey;
21 | }
22 | public void setEventKey(String eventKey) {
23 | this.eventKey = eventKey;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/send/WxSendMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.send;
2 |
3 | import org.jdom.Document;
4 | import org.jdom.Element;
5 |
6 | import com.using.weixin.wxtools.vo.WxMsg;
7 |
8 | public class WxSendMsg extends WxMsg {
9 | // FuncFlag 位0x0001被标志时,星标刚收到的消息。
10 | private boolean star;
11 |
12 | public WxSendMsg(String toUser,String fromUser,String createDt,String msgType,boolean star) {
13 | super(toUser, fromUser, createDt, msgType);
14 | this.star = star;
15 | }
16 |
17 | public WxSendMsg(WxMsg msg) {
18 | this(msg.getToUser(),msg.getFromUser(),msg.getCreateDt(),msg.getMsgType(),false);
19 | }
20 |
21 | public WxSendMsg(WxSendMsg msg) {
22 | this(msg.getToUser(), msg.getFromUser(), msg.getCreateDt(), msg.getMsgType(), msg.isStar());
23 | }
24 |
25 | public boolean isStar() {
26 | return star;
27 | }
28 | public void setStar(boolean star) {
29 | this.star = star;
30 | }
31 |
32 |
33 | public Document toDocument() {
34 | Document doc = new Document();
35 | Element root = new Element("xml");
36 | doc.setRootElement(root);
37 |
38 | createElement(root,"ToUserName", getToUser());
39 | createElement(root,"FromUserName", getFromUser());
40 | createElement(root,"CreateTime", getCreateDt());
41 | createElement(root,"MsgType", getMsgType());
42 | createElement(root,"FuncFlag", isStar()?"1":"0");
43 |
44 | return doc;
45 | }
46 |
47 | @SuppressWarnings("unchecked")
48 | protected Element createElement(Element parent,String name,String value) {
49 | Element elem = new Element(name);
50 | elem.setText(value);
51 | parent.getChildren().add(elem);
52 | return elem;
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/send/WxSendMusicMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.send;
2 |
3 | import org.jdom.Document;
4 | import org.jdom.Element;
5 |
6 | public class WxSendMusicMsg extends WxSendMsg {
7 | private String musicUrl;
8 | private String hqMusicUrl;
9 | private String description;
10 | private String title;
11 |
12 | public WxSendMusicMsg(WxSendMsg msg,String title,String description,String musicUrl,String hqMusicUrl) {
13 | super(msg);
14 | setMsgType("music");
15 | this.title = title;
16 | this.description = description;
17 | this.musicUrl = musicUrl;
18 | this.hqMusicUrl = hqMusicUrl;
19 | }
20 |
21 | public String getMusicUrl() {
22 | return musicUrl;
23 | }
24 | public void setMusicUrl(String musicUrl) {
25 | this.musicUrl = musicUrl;
26 | }
27 | public String getHqMusicUrl() {
28 | return hqMusicUrl;
29 | }
30 | public void setHqMusicUrl(String hqMusicUrl) {
31 | this.hqMusicUrl = hqMusicUrl;
32 | }
33 | public String getDescription() {
34 | return description;
35 | }
36 | public void setDescription(String description) {
37 | this.description = description;
38 | }
39 | public String getTitle() {
40 | return title;
41 | }
42 | public void setTitle(String title) {
43 | this.title = title;
44 | }
45 |
46 |
47 | @Override
48 | public Document toDocument() {
49 | Document doc = super.toDocument();
50 | Element music = createElement(doc.getRootElement(), "Music", "");
51 | createElement(music, "Description", getDescription());
52 | createElement(music, "Title", getTitle());
53 | createElement(music, "MusicUrl", getMusicUrl());
54 | createElement(music, "HQMusicUrl", getHqMusicUrl());
55 | return doc;
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/send/WxSendNewsMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.send;
2 |
3 | import java.util.LinkedList;
4 | import java.util.List;
5 |
6 | import org.jdom.Document;
7 | import org.jdom.Element;
8 |
9 | public class WxSendNewsMsg extends WxSendMsg {
10 | private List items = new LinkedList();
11 |
12 | public WxSendNewsMsg(WxSendMsg msg) {
13 | super(msg);
14 | setMsgType("news");
15 | }
16 | public void setItems(List items) {
17 | this.items = items;
18 | }
19 |
20 | public WxSendNewsMsg addItem(String title,String description,String picUrl,String url) {
21 | if(items.size() >= 10) {
22 | throw new IllegalArgumentException("只能接受最多10个item...");
23 | }
24 | items.add(new WxSendNewsMsgItem(title,description,picUrl,url));
25 | return this;
26 | }
27 |
28 | @Override
29 | public Document toDocument() {
30 | Document doc = super.toDocument();
31 | Element root = doc.getRootElement();
32 | createElement(root, "ArticleCount", String.valueOf(items.size()));
33 | Element articles = createElement(root, "Articles","");
34 | for(WxSendNewsMsgItem item : items) {
35 | Element i = createElement(articles, "item", "");
36 | createElement(i, "Title", item.getTitle());
37 | createElement(i, "Description", item.getDescription());
38 | createElement(i, "PicUrl", item.getPicUrl());
39 | createElement(i, "Url", item.getUrl());
40 | }
41 | return doc;
42 | }
43 | }
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/send/WxSendNewsMsgItem.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.send;
2 |
3 |
4 | public class WxSendNewsMsgItem {
5 | private String title;
6 | private String description;
7 | private String picUrl;
8 | private String url;
9 | public WxSendNewsMsgItem(String title, String description, String picUrl, String url) {
10 | this.title = title;
11 | this.description = description;
12 | this.picUrl = picUrl;
13 | this.url = url;
14 | }
15 | public String getTitle() {
16 | return title;
17 | }
18 | public void setTitle(String title) {
19 | this.title = title;
20 | }
21 | public String getDescription() {
22 | return description;
23 | }
24 | public void setDescription(String description) {
25 | this.description = description;
26 | }
27 | public String getPicUrl() {
28 | return picUrl;
29 | }
30 | public void setPicUrl(String picUrl) {
31 | this.picUrl = picUrl;
32 | }
33 | public String getUrl() {
34 | return url;
35 | }
36 | public void setUrl(String url) {
37 | this.url = url;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/com/using/weixin/wxtools/vo/send/WxSendTextMsg.java:
--------------------------------------------------------------------------------
1 | package com.using.weixin.wxtools.vo.send;
2 |
3 | import org.jdom.Document;
4 |
5 | public class WxSendTextMsg extends WxSendMsg {
6 | private String content;
7 |
8 | public WxSendTextMsg(WxSendMsg msg,String content) {
9 | super(msg);
10 | setMsgType("text");
11 | this.content = content;
12 | }
13 |
14 | public String getContent() {
15 | return content;
16 | }
17 | public void setContent(String content) {
18 | this.content = content;
19 | }
20 |
21 | @Override
22 | public Document toDocument() {
23 | Document doc = super.toDocument();
24 | createElement(doc.getRootElement(), "Content", getContent());
25 | return doc;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------