Skip to content

Commit 59f92a3

Browse files
committed
重构修复部分代码
1 parent 6f297ae commit 59f92a3

File tree

10 files changed

+132
-130
lines changed

10 files changed

+132
-130
lines changed

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/SHA1.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
package me.chanjar.weixin.common.util.crypto;
22

3-
import org.apache.commons.codec.digest.DigestUtils;
4-
5-
import java.security.NoSuchAlgorithmException;
63
import java.util.Arrays;
74

5+
import org.apache.commons.codec.digest.DigestUtils;
6+
87
/**
98
* Created by Daniel Qian on 14/10/19.
109
*/
@@ -13,7 +12,7 @@ public class SHA1 {
1312
/**
1413
* 串接arr参数,生成sha1 digest
1514
*/
16-
public static String gen(String... arr) throws NoSuchAlgorithmException {
15+
public static String gen(String... arr) {
1716
Arrays.sort(arr);
1817
StringBuilder sb = new StringBuilder();
1918
for (String a : arr) {
@@ -25,7 +24,7 @@ public static String gen(String... arr) throws NoSuchAlgorithmException {
2524
/**
2625
* 用&串接arr参数,生成sha1 digest
2726
*/
28-
public static String genWithAmple(String... arr) throws NoSuchAlgorithmException {
27+
public static String genWithAmple(String... arr) {
2928
Arrays.sort(arr);
3029
StringBuilder sb = new StringBuilder();
3130
for (int i = 0; i < arr.length; i++) {

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/crypto/WxCryptUtil.java

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,29 @@
1717
*/
1818
package me.chanjar.weixin.common.util.crypto;
1919

20-
import org.apache.commons.codec.binary.Base64;
21-
import org.apache.commons.codec.digest.DigestUtils;
22-
import org.w3c.dom.Document;
23-
import org.w3c.dom.Element;
24-
import org.xml.sax.InputSource;
20+
import java.io.StringReader;
21+
import java.nio.charset.Charset;
22+
import java.util.ArrayList;
23+
import java.util.Arrays;
24+
import java.util.Collections;
25+
import java.util.List;
26+
import java.util.Map;
27+
import java.util.Random;
28+
import java.util.SortedMap;
29+
import java.util.TreeMap;
2530

2631
import javax.crypto.Cipher;
2732
import javax.crypto.spec.IvParameterSpec;
2833
import javax.crypto.spec.SecretKeySpec;
2934
import javax.xml.parsers.DocumentBuilder;
3035
import javax.xml.parsers.DocumentBuilderFactory;
3136
import javax.xml.parsers.ParserConfigurationException;
32-
import java.io.StringReader;
33-
import java.nio.charset.Charset;
34-
import java.security.NoSuchAlgorithmException;
35-
import java.util.*;
37+
38+
import org.apache.commons.codec.binary.Base64;
39+
import org.apache.commons.codec.digest.DigestUtils;
40+
import org.w3c.dom.Document;
41+
import org.w3c.dom.Element;
42+
import org.xml.sax.InputSource;
3643

3744
public class WxCryptUtil {
3845

@@ -130,13 +137,9 @@ public String encrypt(String plainText) {
130137
String timeStamp = Long.toString(System.currentTimeMillis() / 1000l);
131138
String nonce = genRandomStr();
132139

133-
try {
134-
String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml);
135-
String result = generateXml(encryptedXml, signature, timeStamp, nonce);
136-
return result;
137-
} catch (NoSuchAlgorithmException e) {
138-
throw new RuntimeException(e);
139-
}
140+
String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml);
141+
String result = generateXml(encryptedXml, signature, timeStamp, nonce);
142+
return result;
140143
}
141144

142145
/**
@@ -205,14 +208,10 @@ public String decrypt(String msgSignature, String timeStamp, String nonce,
205208
// 提取密文
206209
String cipherText = extractEncryptPart(encryptedXml);
207210

208-
try {
209-
// 验证安全签名
210-
String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText);
211-
if (!signature.equals(msgSignature)) {
212-
throw new RuntimeException("加密消息签名校验失败");
213-
}
214-
} catch (NoSuchAlgorithmException e) {
215-
throw new RuntimeException(e);
211+
// 验证安全签名
212+
String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText);
213+
if (!signature.equals(msgSignature)) {
214+
throw new RuntimeException("加密消息签名校验失败");
216215
}
217216

218217
// 解密
@@ -277,7 +276,7 @@ public String decrypt(String cipherText) {
277276
*
278277
* @param number
279278
*/
280-
private byte[] number2BytesInNetworkOrder(int number) {
279+
private static byte[] number2BytesInNetworkOrder(int number) {
281280
byte[] orderBytes = new byte[4];
282281
orderBytes[3] = (byte) (number & 0xFF);
283282
orderBytes[2] = (byte) (number >> 8 & 0xFF);
@@ -291,7 +290,7 @@ private byte[] number2BytesInNetworkOrder(int number) {
291290
*
292291
* @param bytesInNetworkOrder
293292
*/
294-
private int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
293+
private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
295294
int sourceNumber = 0;
296295
for (int i = 0; i < 4; i++) {
297296
sourceNumber <<= 8;
@@ -303,7 +302,7 @@ private int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
303302
/**
304303
* 随机生成16位字符串
305304
*/
306-
private String genRandomStr() {
305+
private static String genRandomStr() {
307306
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
308307
Random random = new Random();
309308
StringBuffer sb = new StringBuffer();
@@ -323,8 +322,8 @@ private String genRandomStr() {
323322
* @param nonce 随机字符串
324323
* @return 生成的xml字符串
325324
*/
326-
private String generateXml(String encrypt, String signature, String timestamp,
327-
String nonce) {
325+
private static String generateXml(String encrypt, String signature,
326+
String timestamp, String nonce) {
328327
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
329328
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
330329
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n"

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/fs/FileUtils.java

Lines changed: 12 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,37 +17,25 @@ public class FileUtils {
1717
* @param tmpDirFile 临时文件夹目录
1818
*/
1919
public static File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException {
20-
FileOutputStream fos = null;
21-
try {
22-
File tmpFile;
23-
if (tmpDirFile == null) {
24-
tmpFile = File.createTempFile(name, '.' + ext);
25-
} else {
26-
tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile);
27-
}
28-
tmpFile.deleteOnExit();
29-
fos = new FileOutputStream(tmpFile);
20+
File tmpFile;
21+
if (tmpDirFile == null) {
22+
tmpFile = File.createTempFile(name, '.' + ext);
23+
} else {
24+
tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile);
25+
}
26+
27+
tmpFile.deleteOnExit();
28+
29+
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
3030
int read = 0;
3131
byte[] bytes = new byte[1024 * 100];
3232
while ((read = inputStream.read(bytes)) != -1) {
3333
fos.write(bytes, 0, read);
3434
}
35+
3536
fos.flush();
3637
return tmpFile;
37-
} finally {
38-
if (inputStream != null) {
39-
try {
40-
inputStream.close();
41-
} catch (IOException e) {
42-
}
43-
}
44-
if (fos != null) {
45-
try {
46-
fos.close();
47-
} catch (IOException e) {
48-
}
49-
}
50-
}
38+
}
5139
}
5240

5341
/**

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/DefaultApacheHttpClientBuilder.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package me.chanjar.weixin.common.util.http;
22

3-
import me.chanjar.weixin.common.util.StringUtils;
3+
import java.io.IOException;
4+
import java.util.concurrent.TimeUnit;
5+
46
import org.apache.http.annotation.NotThreadSafe;
57
import org.apache.http.auth.AuthScope;
68
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -21,8 +23,7 @@
2123
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
2224
import org.apache.http.protocol.HttpContext;
2325

24-
import java.io.IOException;
25-
import java.util.concurrent.TimeUnit;
26+
import me.chanjar.weixin.common.util.StringUtils;
2627

2728
/**
2829
* httpclient 连接管理器
@@ -107,6 +108,7 @@ private void prepare() {
107108
.register("https", this.sslConnectionSocketFactory)
108109
.build();
109110

111+
@SuppressWarnings("resource")
110112
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
111113
connectionManager.setMaxTotal(this.maxTotalConn);
112114
connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost);

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddGetRequestExecutor.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
package me.chanjar.weixin.common.util.http;
22

3+
import org.apache.http.HttpHost;
4+
import org.apache.http.impl.client.CloseableHttpClient;
5+
36
import jodd.http.HttpRequest;
47
import jodd.http.HttpResponse;
58
import jodd.http.ProxyInfo;
69
import jodd.http.net.SocketHttpConnectionProvider;
710
import me.chanjar.weixin.common.bean.result.WxError;
811
import me.chanjar.weixin.common.exception.WxErrorException;
9-
import org.apache.http.HttpHost;
10-
import org.apache.http.impl.client.CloseableHttpClient;
11-
12-
import java.io.IOException;
1312

1413
/**
1514
* 简单的GET请求执行器,请求的参数是String, 返回的结果也是String
@@ -20,7 +19,7 @@ public class JoddGetRequestExecutor implements RequestExecutor<String, String> {
2019

2120
@Override
2221
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri,
23-
String queryParam) throws WxErrorException, IOException {
22+
String queryParam) throws WxErrorException {
2423
if (queryParam != null) {
2524
if (uri.indexOf('?') == -1) {
2625
uri += '?';

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/JoddPostRequestExecutor.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
package me.chanjar.weixin.common.util.http;
22

3+
import org.apache.http.HttpHost;
4+
import org.apache.http.impl.client.CloseableHttpClient;
5+
36
import jodd.http.HttpRequest;
47
import jodd.http.HttpResponse;
58
import jodd.http.ProxyInfo;
69
import jodd.http.net.SocketHttpConnectionProvider;
710
import me.chanjar.weixin.common.bean.result.WxError;
811
import me.chanjar.weixin.common.exception.WxErrorException;
9-
import org.apache.http.HttpHost;
10-
import org.apache.http.impl.client.CloseableHttpClient;
11-
12-
import java.io.IOException;
1312

1413
/**
1514
* 简单的POST请求执行器,请求的参数是String, 返回的结果也是String
@@ -20,7 +19,7 @@ public class JoddPostRequestExecutor implements RequestExecutor<String, String>
2019

2120
@Override
2221
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri,
23-
String postEntity) throws WxErrorException, IOException {
22+
String postEntity) throws WxErrorException {
2423
SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider();
2524

2625
if (httpProxy != null) {

weixin-java-common/src/main/java/me/chanjar/weixin/common/util/http/MediaDownloadRequestExecutor.java

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package me.chanjar.weixin.common.util.http;
22

3-
import me.chanjar.weixin.common.bean.result.WxError;
4-
import me.chanjar.weixin.common.exception.WxErrorException;
5-
import me.chanjar.weixin.common.util.StringUtils;
6-
import me.chanjar.weixin.common.util.fs.FileUtils;
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.io.InputStream;
6+
import java.util.regex.Matcher;
7+
import java.util.regex.Pattern;
8+
79
import org.apache.http.Header;
810
import org.apache.http.HttpHost;
911
import org.apache.http.client.config.RequestConfig;
@@ -12,11 +14,10 @@
1214
import org.apache.http.entity.ContentType;
1315
import org.apache.http.impl.client.CloseableHttpClient;
1416

15-
import java.io.File;
16-
import java.io.IOException;
17-
import java.io.InputStream;
18-
import java.util.regex.Matcher;
19-
import java.util.regex.Pattern;
17+
import me.chanjar.weixin.common.bean.result.WxError;
18+
import me.chanjar.weixin.common.exception.WxErrorException;
19+
import me.chanjar.weixin.common.util.StringUtils;
20+
import me.chanjar.weixin.common.util.fs.FileUtils;
2021

2122
/**
2223
* 下载媒体文件请求执行器,请求的参数是String, 返回的结果是File
@@ -52,7 +53,9 @@ public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String u
5253
httpGet.setConfig(config);
5354
}
5455

55-
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
56+
try (CloseableHttpResponse response = httpclient.execute(httpGet);
57+
InputStream inputStream = InputStreamResponseHandler.INSTANCE
58+
.handleResponse(response)) {
5659

5760
Header[] contentTypeHeader = response.getHeaders("Content-Type");
5861
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
@@ -62,8 +65,6 @@ public File execute(CloseableHttpClient httpclient, HttpHost httpProxy, String u
6265
throw new WxErrorException(WxError.fromJson(responseContent));
6366
}
6467
}
65-
InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
66-
6768
// 视频文件不支持下载
6869
String fileName = getFileName(response);
6970
if (StringUtils.isBlank(fileName)) {

weixin-java-common/src/test/java/me/chanjar/weixin/common/session/SessionTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ public void testBackgroundProcess2(WxSessionManager sessionManager) throws Inter
106106
}
107107

108108
@Test(dataProvider = "getSessionManager")
109-
public void testMaxActive(WxSessionManager sessionManager) throws InterruptedException {
109+
public void testMaxActive(WxSessionManager sessionManager) {
110110

111111
InternalSessionManager ism = (InternalSessionManager) sessionManager;
112112
ism.setMaxActiveSessions(2);
@@ -118,7 +118,7 @@ public void testMaxActive(WxSessionManager sessionManager) throws InterruptedExc
118118
}
119119

120120
@Test(dataProvider = "getSessionManager", expectedExceptions = TooManyActiveSessionsException.class)
121-
public void testMaxActive2(WxSessionManager sessionManager) throws InterruptedException {
121+
public void testMaxActive2(WxSessionManager sessionManager) {
122122

123123
InternalSessionManager ism = (InternalSessionManager) sessionManager;
124124
ism.setMaxActiveSessions(2);

weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpCardServiceImpl.java

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package me.chanjar.weixin.mp.api.impl;
22

3-
import java.security.NoSuchAlgorithmException;
43
import java.util.Arrays;
54

65
import org.slf4j.Logger;
@@ -111,16 +110,12 @@ public WxCardApiSignature createCardApiSignature(String... optionalSignParam) th
111110
signParam[optionalSignParam.length] = String.valueOf(timestamp);
112111
signParam[optionalSignParam.length + 1] = nonceStr;
113112
signParam[optionalSignParam.length + 2] = cardApiTicket;
114-
try {
115-
String signature = SHA1.gen(signParam);
116-
WxCardApiSignature cardApiSignature = new WxCardApiSignature();
117-
cardApiSignature.setTimestamp(timestamp);
118-
cardApiSignature.setNonceStr(nonceStr);
119-
cardApiSignature.setSignature(signature);
120-
return cardApiSignature;
121-
} catch (NoSuchAlgorithmException e) {
122-
throw new WxErrorException(WxError.newBuilder().setErrorMsg(e.getMessage()).build());
123-
}
113+
String signature = SHA1.gen(signParam);
114+
WxCardApiSignature cardApiSignature = new WxCardApiSignature();
115+
cardApiSignature.setTimestamp(timestamp);
116+
cardApiSignature.setNonceStr(nonceStr);
117+
cardApiSignature.setSignature(signature);
118+
return cardApiSignature;
124119
}
125120

126121
/**

0 commit comments

Comments
 (0)