重构修复部分代码

This commit is contained in:
BinaryWang
2016-09-01 10:26:16 +08:00
parent 6f297ae95a
commit 59f92a3b41
10 changed files with 133 additions and 131 deletions

View File

@@ -1,10 +1,9 @@
package me.chanjar.weixin.common.util.crypto;
import org.apache.commons.codec.digest.DigestUtils;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.codec.digest.DigestUtils;
/**
* Created by Daniel Qian on 14/10/19.
*/
@@ -13,7 +12,7 @@ public class SHA1 {
/**
* 串接arr参数生成sha1 digest
*/
public static String gen(String... arr) throws NoSuchAlgorithmException {
public static String gen(String... arr) {
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (String a : arr) {
@@ -25,7 +24,7 @@ public class SHA1 {
/**
* 用&串接arr参数生成sha1 digest
*/
public static String genWithAmple(String... arr) throws NoSuchAlgorithmException {
public static String genWithAmple(String... arr) {
Arrays.sort(arr);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++) {

View File

@@ -17,11 +17,16 @@
*/
package me.chanjar.weixin.common.util.crypto;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
@@ -29,10 +34,12 @@ import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
public class WxCryptUtil {
@@ -130,13 +137,9 @@ public class WxCryptUtil {
String timeStamp = Long.toString(System.currentTimeMillis() / 1000l);
String nonce = genRandomStr();
try {
String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml);
String result = generateXml(encryptedXml, signature, timeStamp, nonce);
return result;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
String signature = SHA1.gen(this.token, timeStamp, nonce, encryptedXml);
String result = generateXml(encryptedXml, signature, timeStamp, nonce);
return result;
}
/**
@@ -205,14 +208,10 @@ public class WxCryptUtil {
// 提取密文
String cipherText = extractEncryptPart(encryptedXml);
try {
// 验证安全签名
String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText);
if (!signature.equals(msgSignature)) {
throw new RuntimeException("加密消息签名校验失败");
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
// 验证安全签名
String signature = SHA1.gen(this.token, timeStamp, nonce, cipherText);
if (!signature.equals(msgSignature)) {
throw new RuntimeException("加密消息签名校验失败");
}
// 解密
@@ -277,7 +276,7 @@ public class WxCryptUtil {
*
* @param number
*/
private byte[] number2BytesInNetworkOrder(int number) {
private static byte[] number2BytesInNetworkOrder(int number) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (number & 0xFF);
orderBytes[2] = (byte) (number >> 8 & 0xFF);
@@ -291,7 +290,7 @@ public class WxCryptUtil {
*
* @param bytesInNetworkOrder
*/
private int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
private static int bytesNetworkOrder2Number(byte[] bytesInNetworkOrder) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
@@ -303,7 +302,7 @@ public class WxCryptUtil {
/**
* 随机生成16位字符串
*/
private String genRandomStr() {
private static String genRandomStr() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
@@ -323,8 +322,8 @@ public class WxCryptUtil {
* @param nonce 随机字符串
* @return 生成的xml字符串
*/
private String generateXml(String encrypt, String signature, String timestamp,
String nonce) {
private static String generateXml(String encrypt, String signature,
String timestamp, String nonce) {
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n"

View File

@@ -17,37 +17,25 @@ public class FileUtils {
* @param tmpDirFile 临时文件夹目录
*/
public static File createTmpFile(InputStream inputStream, String name, String ext, File tmpDirFile) throws IOException {
FileOutputStream fos = null;
try {
File tmpFile;
if (tmpDirFile == null) {
tmpFile = File.createTempFile(name, '.' + ext);
} else {
tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile);
}
tmpFile.deleteOnExit();
fos = new FileOutputStream(tmpFile);
File tmpFile;
if (tmpDirFile == null) {
tmpFile = File.createTempFile(name, '.' + ext);
} else {
tmpFile = File.createTempFile(name, '.' + ext, tmpDirFile);
}
tmpFile.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
int read = 0;
byte[] bytes = new byte[1024 * 100];
while ((read = inputStream.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fos.flush();
return tmpFile;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
/**

View File

@@ -1,6 +1,8 @@
package me.chanjar.weixin.common.util.http;
import me.chanjar.weixin.common.util.StringUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -21,8 +23,7 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import me.chanjar.weixin.common.util.StringUtils;
/**
* httpclient 连接管理器
@@ -107,6 +108,7 @@ public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder {
.register("https", this.sslConnectionSocketFactory)
.build();
@SuppressWarnings("resource")
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(this.maxTotalConn);
connectionManager.setDefaultMaxPerRoute(this.maxConnPerHost);

View File

@@ -1,15 +1,14 @@
package me.chanjar.weixin.common.util.http;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.http.ProxyInfo;
import jodd.http.net.SocketHttpConnectionProvider;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
/**
* 简单的GET请求执行器请求的参数是String, 返回的结果也是String
@@ -20,7 +19,7 @@ public class JoddGetRequestExecutor implements RequestExecutor<String, String> {
@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri,
String queryParam) throws WxErrorException, IOException {
String queryParam) throws WxErrorException {
if (queryParam != null) {
if (uri.indexOf('?') == -1) {
uri += '?';

View File

@@ -1,15 +1,14 @@
package me.chanjar.weixin.common.util.http;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.http.ProxyInfo;
import jodd.http.net.SocketHttpConnectionProvider;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.IOException;
/**
* 简单的POST请求执行器请求的参数是String, 返回的结果也是String
@@ -20,7 +19,7 @@ public class JoddPostRequestExecutor implements RequestExecutor<String, String>
@Override
public String execute(CloseableHttpClient httpclient, HttpHost httpProxy, String uri,
String postEntity) throws WxErrorException, IOException {
String postEntity) throws WxErrorException {
SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider();
if (httpProxy != null) {

View File

@@ -1,9 +1,11 @@
package me.chanjar.weixin.common.util.http;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.common.util.fs.FileUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
@@ -12,11 +14,10 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.chanjar.weixin.common.bean.result.WxError;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.common.util.fs.FileUtils;
/**
* 下载媒体文件请求执行器请求的参数是String, 返回的结果是File
@@ -52,7 +53,9 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin
httpGet.setConfig(config);
}
try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
try (CloseableHttpResponse response = httpclient.execute(httpGet);
InputStream inputStream = InputStreamResponseHandler.INSTANCE
.handleResponse(response)) {
Header[] contentTypeHeader = response.getHeaders("Content-Type");
if (contentTypeHeader != null && contentTypeHeader.length > 0) {
@@ -62,8 +65,6 @@ public class MediaDownloadRequestExecutor implements RequestExecutor<File, Strin
throw new WxErrorException(WxError.fromJson(responseContent));
}
}
InputStream inputStream = InputStreamResponseHandler.INSTANCE.handleResponse(response);
// 视频文件不支持下载
String fileName = getFileName(response);
if (StringUtils.isBlank(fileName)) {

View File

@@ -106,7 +106,7 @@ public class SessionTest {
}
@Test(dataProvider = "getSessionManager")
public void testMaxActive(WxSessionManager sessionManager) throws InterruptedException {
public void testMaxActive(WxSessionManager sessionManager) {
InternalSessionManager ism = (InternalSessionManager) sessionManager;
ism.setMaxActiveSessions(2);
@@ -118,7 +118,7 @@ public class SessionTest {
}
@Test(dataProvider = "getSessionManager", expectedExceptions = TooManyActiveSessionsException.class)
public void testMaxActive2(WxSessionManager sessionManager) throws InterruptedException {
public void testMaxActive2(WxSessionManager sessionManager) {
InternalSessionManager ism = (InternalSessionManager) sessionManager;
ism.setMaxActiveSessions(2);