weixin4j-server优化

This commit is contained in:
jinyu 2015-12-26 23:30:01 +08:00
parent 9c01692f57
commit 1fc5a34369
21 changed files with 156 additions and 754 deletions

View File

@ -603,4 +603,8 @@
+ weixin4j-base:MchPayRequest抽象化
+ weixin4j-server:WeixinMessageInterceptor加入weight权重接口
+ weixin4j-server:移入weixin4j下模块化
+ weixin4j-server:删除无用的工具类并重新整理

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.foxinmy</groupId>
<artifactId>weixin4j</artifactId>
<version>1.6.5</version>
<version>1.6.6</version>
<packaging>pom</packaging>
<name>weixin4j</name>
<url>https://github.com/foxinmy/weixin4j</url>
@ -43,6 +43,7 @@
<module>weixin4j-base</module>
<module>weixin4j-mp</module>
<module>weixin4j-qy</module>
<module>weixin4j-server</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -225,10 +226,6 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.foxinmy</groupId>
<artifactId>weixin4j</artifactId>
<version>1.6.5</version>
<version>1.6.6</version>
</parent>
<artifactId>weixin4j-base</artifactId>
<name>weixin4j-base</name>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.foxinmy</groupId>
<artifactId>weixin4j</artifactId>
<version>1.6.5</version>
<version>1.6.6</version>
</parent>
<artifactId>weixin4j-mp</artifactId>
<name>weixin4j-mp</name>

View File

@ -5,7 +5,7 @@
<parent>
<groupId>com.foxinmy</groupId>
<artifactId>weixin4j</artifactId>
<version>1.6.5</version>
<version>1.6.6</version>
</parent>
<artifactId>weixin4j-qy</artifactId>
<name>weixin4j-qy</name>

View File

@ -2,184 +2,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.foxinmy</groupId>
<parent>
<groupId>com.foxinmy</groupId>
<artifactId>weixin4j</artifactId>
<version>1.6.6</version>
</parent>
<artifactId>weixin4j-server</artifactId>
<version>1.1.4</version>
<version>1.1.5</version>
<name>weixin4j-server</name>
<url>https://github.com/foxinmy/weixin4j/tree/master/weixin4j-server</url>
<description>微信消息netty服务器</description>
<inceptionYear>2014</inceptionYear>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
<scm>
<url>https://github.com/foxinmy/weixin4j</url>
<connection>scm:git:git://github.com/foxinmy/weixin4j.git</connection>
<developerConnection>scm:git:git@github.com:foxinmy/weixin4j.git</developerConnection>
<tag>HEAD</tag>
</scm>
<issueManagement>
<url>https://github.com/foxinmy/weixin4j/issues</url>
</issueManagement>
<developers>
<developer>
<email>hujinyuhao@163.com</email>
<id>jinyu</id>
<name>jinyu</name>
<url>https://github.com/foxinmy</url>
<timezone>+8</timezone>
<roles>
<role>java developer</role>
</roles>
</developer>
</developers>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<!-- 过滤证书文件 -->
<nonFilteredFileExtensions>
<nonFilteredFileExtension>pem</nonFilteredFileExtension>
<nonFilteredFileExtension>pfx</nonFilteredFileExtension>
<nonFilteredFileExtension>p12</nonFilteredFileExtension>
<nonFilteredFileExtension>jks</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>default-jar</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classesDirectory>target/classes</classesDirectory>
<excludes>
<exclude>*.properties</exclude>
<exclude>*.xml</exclude>
<exclude>*.txt</exclude>
<exclude>**/*.md</exclude>
</excludes>
<archive>
<addMavenDescriptor>false</addMavenDescriptor>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<show>public</show>
<charset>${project.build.sourceEncoding}</charset>
<encoding>${project.build.sourceEncoding}</encoding>
<docencoding>${project.build.sourceEncoding}</docencoding>
<links>
<link>http://docs.oracle.com/javase/7/docs/api</link>
</links>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.pem</include>
<include>**/*.p12</include>
<include>**/*.pfx</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*.xml</include>
<include>*.properties</include>
</includes>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
@ -189,8 +21,6 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
@ -215,35 +45,4 @@
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>release</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<distributionManagement>
<snapshotRepository>
<id>oss-snapshot</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</snapshotRepository>
<repository>
<id>oss-release</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
</project>

View File

@ -19,7 +19,7 @@ package com.foxinmy.weixin4j.base64;
import java.math.BigInteger;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
/**
* <p>
@ -313,7 +313,7 @@ public class Base64 extends BaseNCodec {
// @see test case Base64Test.testConstructors()
if (lineSeparator != null) {
if (containsAlphabetOrPad(lineSeparator)) {
final String sep = StringUtil.newStringUtf8(lineSeparator);
final String sep = ServerToolkits.newStringUtf8(lineSeparator);
throw new IllegalArgumentException(
"lineSeparator must not contain base64 characters: ["
+ sep + "]");
@ -600,7 +600,7 @@ public class Base64 extends BaseNCodec {
* @since 1.5
*/
public static boolean isBase64(final String base64) {
return isBase64(StringUtil.getBytesUtf8(base64));
return isBase64(ServerToolkits.getBytesUtf8(base64));
}
/**
@ -649,7 +649,7 @@ public class Base64 extends BaseNCodec {
* @since 1.4 (NOTE: 1.4 chunked the output, whereas 1.5 does not).
*/
public static String encodeBase64String(final byte[] binaryData) {
return StringUtil.newStringUtf8(encodeBase64(binaryData, false));
return ServerToolkits.newStringUtf8(encodeBase64(binaryData, false));
}
/**
@ -678,7 +678,7 @@ public class Base64 extends BaseNCodec {
* @since 1.4
*/
public static String encodeBase64URLSafeString(final byte[] binaryData) {
return StringUtil.newStringUtf8(encodeBase64(binaryData, false, true));
return ServerToolkits.newStringUtf8(encodeBase64(binaryData, false, true));
}
/**

View File

@ -22,7 +22,7 @@ import io.netty.handler.codec.EncoderException;
import java.util.Arrays;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
/**
* <p>
@ -372,7 +372,7 @@ public abstract class BaseNCodec {
* @return A String containing only Base-N character data
*/
public String encodeToString(final byte[] pArray) {
return StringUtil.newStringUtf8(encode(pArray));
return ServerToolkits.newStringUtf8(encode(pArray));
}
/**
@ -385,7 +385,7 @@ public abstract class BaseNCodec {
* alphabet.
*/
public String encodeAsString(final byte[] pArray) {
return StringUtil.newStringUtf8(encode(pArray));
return ServerToolkits.newStringUtf8(encode(pArray));
}
/**
@ -420,7 +420,7 @@ public abstract class BaseNCodec {
* @return a byte array containing binary data
*/
public byte[] decode(final String pArray) {
return decode(StringUtil.getBytesUtf8(pArray));
return decode(ServerToolkits.getBytesUtf8(pArray));
}
/**
@ -517,7 +517,7 @@ public abstract class BaseNCodec {
* @see #isInAlphabet(byte[], boolean)
*/
public boolean isInAlphabet(final String basen) {
return isInAlphabet(StringUtil.getBytesUtf8(basen), true);
return isInAlphabet(ServerToolkits.getBytesUtf8(basen), true);
}
/**

View File

@ -35,7 +35,7 @@ import com.foxinmy.weixin4j.socket.WeixinMessageTransfer;
import com.foxinmy.weixin4j.util.ClassUtil;
import com.foxinmy.weixin4j.util.Consts;
import com.foxinmy.weixin4j.util.HttpUtil;
import com.foxinmy.weixin4j.util.ReflectionUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
/**
* 微信消息分发器
@ -247,7 +247,7 @@ public class WeixinMessageDispatcher {
try {
Constructor<?> ctor = clazz
.getDeclaredConstructor();
ReflectionUtil.makeAccessible(ctor);
ServerToolkits.makeConstructorAccessible(ctor);
messageHandlerList.add((WeixinMessageHandler) ctor
.newInstance((Object[]) null));
} catch (Exception ex) {
@ -306,7 +306,7 @@ public class WeixinMessageDispatcher {
try {
Constructor<?> ctor = clazz
.getDeclaredConstructor();
ReflectionUtil.makeAccessible(ctor);
ServerToolkits.makeConstructorAccessible(ctor);
messageInterceptorList
.add((WeixinMessageInterceptor) ctor
.newInstance((Object[]) null));

View File

@ -3,7 +3,7 @@ package com.foxinmy.weixin4j.dispatcher;
import java.io.Serializable;
import com.foxinmy.weixin4j.type.AccountType;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
/**
* 微信消息key
@ -48,10 +48,10 @@ public class WeixinMessageKey implements Serializable {
result = prime * result
+ ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result
+ ((StringUtil.isBlank(eventType)) ? 0 : eventType.hashCode());
+ ((ServerToolkits.hasText(eventType)) ? 0 : eventType.hashCode());
result = prime
* result
+ ((StringUtil.isBlank(messageType)) ? 0 : messageType
+ ((ServerToolkits.hasText(messageType)) ? 0 : messageType
.hashCode());
return result;
}

View File

@ -16,7 +16,7 @@ import com.foxinmy.weixin4j.type.EncryptType;
import com.foxinmy.weixin4j.util.AesToken;
import com.foxinmy.weixin4j.util.Consts;
import com.foxinmy.weixin4j.util.MessageUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
import com.foxinmy.weixin4j.xml.EncryptMessageHandler;
/**
@ -68,9 +68,9 @@ public class WeixinMessageDecoder extends
"weixin_id").get(0) : null;
AesToken aesToken = aesTokenMap.get(weixinId);
String encryptContent = null;
if (!StringUtil.isBlank(messageContent)
if (!ServerToolkits.hasText(messageContent)
&& encryptType == EncryptType.AES) {
if (StringUtil.isBlank(aesToken.getAesKey())) {
if (ServerToolkits.hasText(aesToken.getAesKey())) {
throw new WeixinException(
"AESEncodingKey not be null in AES mode");
}

View File

@ -19,7 +19,7 @@ import com.foxinmy.weixin4j.util.AesToken;
import com.foxinmy.weixin4j.util.Consts;
import com.foxinmy.weixin4j.util.HttpUtil;
import com.foxinmy.weixin4j.util.MessageUtil;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
import com.foxinmy.weixin4j.xml.MessageTransferHandler;
/**
@ -57,8 +57,8 @@ public class WeixinRequestHandler extends
throws WeixinException {
final AesToken aesToken = request.getAesToken();
if (aesToken == null
|| (StringUtil.isBlank(request.getSignature()) && StringUtil
.isBlank(request.getMsgSignature()))) {
|| (ServerToolkits.hasText(request.getSignature()) && ServerToolkits
.hasText(request.getMsgSignature()))) {
ctx.writeAndFlush(HttpUtil.createHttpResponse(BAD_REQUEST))
.addListener(ChannelFutureListener.CLOSE);
return;
@ -68,14 +68,14 @@ public class WeixinRequestHandler extends
* 企业号:无论Get,Post都带msg_signature参数
**/
if (request.getMethod().equals(HttpMethod.GET.name())) {
if (!StringUtil.isBlank(request.getSignature())
if (!ServerToolkits.hasText(request.getSignature())
&& MessageUtil.signature(aesToken.getToken(),
request.getTimeStamp(), request.getNonce()).equals(
request.getSignature())) {
ctx.write(new SingleResponse(request.getEchoStr()));
return;
}
if (!StringUtil.isBlank(request.getMsgSignature())
if (!ServerToolkits.hasText(request.getMsgSignature())
&& MessageUtil.signature(aesToken.getToken(),
request.getTimeStamp(), request.getNonce(),
request.getEchoStr()).equals(
@ -88,7 +88,7 @@ public class WeixinRequestHandler extends
.addListener(ChannelFutureListener.CLOSE);
return;
} else if (request.getMethod().equals(HttpMethod.POST.name())) {
if (!StringUtil.isBlank(request.getSignature())
if (!ServerToolkits.hasText(request.getSignature())
&& !MessageUtil.signature(aesToken.getToken(),
request.getTimeStamp(), request.getNonce()).equals(
request.getSignature())) {

View File

@ -15,7 +15,7 @@ import com.foxinmy.weixin4j.util.AesToken;
import com.foxinmy.weixin4j.util.Consts;
import com.foxinmy.weixin4j.util.HttpUtil;
import com.foxinmy.weixin4j.util.MessageUtil;
import com.foxinmy.weixin4j.util.RandomUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
/**
* 微信回复编码类
@ -55,7 +55,7 @@ public class WeixinResponseEncoder extends
content.append("</xml>");
if (encryptType == EncryptType.AES) {
AesToken aesToken = messageTransfer.getAesToken();
String nonce = RandomUtil.generateString(32);
String nonce = ServerToolkits.generateRandomString(32);
String timestamp = Long
.toString(System.currentTimeMillis() / 1000l);
String encrtypt = MessageUtil.aesEncrypt(aesToken.getWeixinId(),

View File

@ -1,60 +0,0 @@
package com.foxinmy.weixin4j.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 签名工具类
*
* @className DigestUtil
* @author jy
* @date 2015年5月6日
* @since JDK 1.6
* @see
*/
public final class DigestUtils {
private static MessageDigest getDigest(final String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (final NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
}
/**
* SHA1签名
*
* @param content
* 待签名字符串
* @return 签名后的字符串
*/
public static String SHA1(String content) {
byte[] data = StringUtil.getBytesUtf8(content);
return HexUtil.encodeHexString(getDigest(Consts.SHA1).digest(data));
}
/**
* SHA签名
*
* @param content
* 待签名字符串
* @return 签名后的字符串
*/
public static String SHA(String content) {
byte[] data = StringUtil.getBytesUtf8(content);
return HexUtil.encodeHexString(getDigest(Consts.SHA).digest(data));
}
/**
* MD5签名
*
* @param content
* 待签名字符串
* @return 签名后的字符串
*/
public static String MD5(String content) {
byte[] data = StringUtil.getBytesUtf8(content);
return HexUtil.encodeHexString(getDigest(Consts.MD5).digest(data));
}
}

View File

@ -18,7 +18,6 @@ import com.foxinmy.weixin4j.exception.WeixinException;
* @see
*/
public final class MessageUtil {
/**
* 验证微信签名
*
@ -35,7 +34,7 @@ public final class MessageUtil {
for (String str : para) {
sb.append(str);
}
return DigestUtils.SHA1(sb.toString());
return ServerToolkits.digestSHA1(sb.toString());
}
/**
@ -58,16 +57,16 @@ public final class MessageUtil {
*
* random(16B)为16字节的随机字符串msg_len为msg长度占4个字节(网络字节序)$AppId为公众账号的AppId
*/
byte[] randomBytes = StringUtil.getBytesUtf8(RandomUtil
.generateString(16));
byte[] xmlBytes = StringUtil.getBytesUtf8(xmlContent);
byte[] randomBytes = ServerToolkits.getBytesUtf8(ServerToolkits
.generateRandomString(16));
byte[] xmlBytes = ServerToolkits.getBytesUtf8(xmlContent);
int xmlLength = xmlBytes.length;
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (xmlLength & 0xFF);
orderBytes[2] = (byte) (xmlLength >> 8 & 0xFF);
orderBytes[1] = (byte) (xmlLength >> 16 & 0xFF);
orderBytes[0] = (byte) (xmlLength >> 24 & 0xFF);
byte[] appidBytes = StringUtil.getBytesUtf8(appId);
byte[] appidBytes = ServerToolkits.getBytesUtf8(appId);
int byteLength = randomBytes.length + xmlLength + orderBytes.length
+ appidBytes.length;
@ -90,7 +89,7 @@ public final class MessageUtil {
byteLength += appidBytes.length;
System.arraycopy(padBytes, 0, unencrypted, byteLength, padBytes.length);
try {
byte[] aesKey = Base64.decodeBase64(encodingAesKey + "=");
byte[] aesKey = NettyBase64.decodeBase64(encodingAesKey + "=");
// 设置加密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, Consts.AES);
@ -120,7 +119,7 @@ public final class MessageUtil {
*/
public static String aesDecrypt(String appId, String encodingAesKey,
String encryptContent) throws WeixinException {
byte[] aesKey = Base64.decodeBase64(encodingAesKey + "=");
byte[] aesKey = NettyBase64.decodeBase64(encodingAesKey + "=");
byte[] original;
try {
// 设置解密模式为AES的CBC模式
@ -130,7 +129,7 @@ public final class MessageUtil {
0, 16));
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(encryptContent);
byte[] encrypted = NettyBase64.decodeBase64(encryptContent);
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
@ -151,9 +150,9 @@ public final class MessageUtil {
int xmlLength = lengthByte[3] & 0xff | (lengthByte[2] & 0xff) << 8
| (lengthByte[1] & 0xff) << 16
| (lengthByte[0] & 0xff) << 24;
xmlContent = StringUtil.newStringUtf8(Arrays.copyOfRange(bytes, 20,
xmlContent = ServerToolkits.newStringUtf8(Arrays.copyOfRange(bytes, 20,
20 + xmlLength));
fromAppId = StringUtil.newStringUtf8(Arrays.copyOfRange(bytes,
fromAppId = ServerToolkits.newStringUtf8(Arrays.copyOfRange(bytes,
20 + xmlLength, bytes.length));
} catch (Exception e) {
throw new WeixinException("-40008", "xml内容不合法:" + e.getMessage());

View File

@ -5,15 +5,15 @@ import io.netty.buffer.Unpooled;
import io.netty.handler.codec.base64.Base64Dialect;
/**
* Base64
* NettyBase64
*
* @className Base64
* @className NettyBase64
* @author jy
* @date 2015年5月17日
* @since JDK 1.6
* @see
*/
public final class Base64 {
public final class NettyBase64 {
private static byte[] byteBuf2Array(ByteBuf byteBuf) {
if (byteBuf.hasArray()) {
@ -26,7 +26,7 @@ public final class Base64 {
}
public static byte[] decodeBase64(final String content) {
byte[] data = StringUtil.getBytesUtf8(content);
byte[] data = ServerToolkits.getBytesUtf8(content);
ByteBuf des = io.netty.handler.codec.base64.Base64.decode(
Unpooled.copiedBuffer(data), Base64Dialect.STANDARD);
return byteBuf2Array(des);
@ -40,6 +40,6 @@ public final class Base64 {
public static String encodeBase64String(final byte[] bytes) {
byte[] data = encodeBase64(bytes);
return StringUtil.newStringUtf8(data);
return ServerToolkits.newStringUtf8(data);
}
}

View File

@ -1,107 +0,0 @@
package com.foxinmy.weixin4j.util;
import java.util.Random;
import java.util.UUID;
/**
* 随机码工具类
*
* @className RandomUtil
* @author jy
* @date 2014年10月22日
* @since JDK 1.6
* @see
*/
public class RandomUtil {
private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LETTERCHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String NUMBERCHAR = "0123456789";
/**
* 返回一个定长的随机字符串(包含数字和大小写字母)
*
* @param length
* 随机数的长度
* @return
*/
public static String generateString(int length) {
StringBuilder sb = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯数字字符串(只包含数字)
*
* @param length
* 随机数的长度
* @return
*/
public static String generateStringByNumberChar(int length) {
StringBuilder sb = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(NUMBERCHAR.charAt(random.nextInt(NUMBERCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯字母字符串(只包含大小写字母)
*
* @param length
* 随机数的长度
* @return
*/
public static String generateStringByLetterCharr(int length) {
StringBuilder sb = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(LETTERCHAR.charAt(random.nextInt(LETTERCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
*
* @param length
* 随机数的长度
* @return
*/
public static String generateLowerString(int length) {
return generateStringByLetterCharr(length).toLowerCase();
}
/**
* 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
*
* @param length
* 随机数的长度
* @return
*/
public static String generateUpperString(int length) {
return generateStringByLetterCharr(length).toUpperCase();
}
/**
* 随机获取UUID字符串(无中划线)
*
* @return UUID字符串
*/
public static String getUUID() {
String uuid = UUID.randomUUID().toString();
return uuid.substring(0, 8) + uuid.substring(9, 13)
+ uuid.substring(14, 18) + uuid.substring(19, 23)
+ uuid.substring(24);
}
public static void main(String[] args) {
System.out.println(System.nanoTime());
System.out.println(System.currentTimeMillis());
}
}

View File

@ -1,228 +0,0 @@
package com.foxinmy.weixin4j.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* @title 反射工具类
* @description 提供对类,字段的反射调用
* @author jy.hu , 2012-10-26
*/
public class ReflectionUtil {
/**
* 获取包包名
*
* @param obj
* @return
*/
public static String getPackageName(Object obj) {
return obj.getClass().getPackage().getName();
}
/**
* 获取字段的泛型参数类型
*
* @param obj
* @param fieldName
* @return
*/
public static Class<?> getFieldGenericType(Object obj, String fieldName) {
Field field = getAccessibleField(obj, fieldName);
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
return (Class<?>) ((ParameterizedType) type)
.getActualTypeArguments()[0];
}
return null;
}
/**
* 调用方法
*
* @param object
* 对象
*
* @param propertyName
* 属性名称
*/
public static Object invokeMethod(Object object, String propertyName) {
try {
Method getterMethod = object.getClass().getMethod(propertyName);
return getterMethod.invoke(object);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Object invokeMethod(Object object, String propertyName,
Object... args) {
try {
Method getterMethod = object.getClass().getMethod(propertyName);
return getterMethod.invoke(object, args);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 调用Getter方法
*
* @param object
* 对象
*
* @param propertyName
* 属性名称
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object invokeGetterMethod(Object object, String propertyName)
throws Exception {
String getterMethodName = null;
Method getterMethod = null;
String propertyNa = null;
if (propertyName.contains(".")) {
propertyNa = StringUtil.substringBefore(propertyName, ".");
getterMethodName = "get" + StringUtil.capitalize(propertyNa);
getterMethod = object.getClass().getMethod(getterMethodName);
return invokeGetterMethod(getterMethod.invoke(object),
StringUtil.substringAfter(propertyName, "."));
} else {
getterMethodName = "get" + StringUtil.capitalize(propertyName);
getterMethod = object.getClass().getMethod(getterMethodName);
return getterMethod.invoke(object);
}
}
/**
* 调用Setter方法
*
* @param object
* 对象
*
* @param propertyName
* 属性名称
*
* @param propertyValue
* 属性值
*/
public static void invokeSetterMethod(Object object, String propertyName,
Object propertyValue) {
Class<?> setterMethodClass = propertyValue.getClass();
invokeSetterMethod(object, propertyName, propertyValue,
setterMethodClass);
}
/**
* 调用Setter方法
*
* @param object
* 对象
*
* @param propertyName
* 属性名称
*
* @param propertyValue
* 属性值
*
* @param setterMethodClass
* 参数类型
*/
public static void invokeSetterMethod(Object object, String propertyName,
Object propertyValue, Class<?> setterMethodClass) {
String setterMethodName = "set" + StringUtil.capitalize(propertyName);
try {
Method setterMethod = object.getClass().getMethod(setterMethodName,
setterMethodClass);
setterMethod.invoke(object, propertyValue);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取对象属性值,无视private/protected/getter
*
* @param object
* 对象
*
* @param fieldName
* 属性名称
*/
public static Object getFieldValue(Object object, String fieldName) {
Field field = getAccessibleField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field "
+ fieldName);
}
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException e) {
}
return result;
}
/**
* 设置对象属性值,无视private/protected/setter
*
* @param object
* 对象
*
* @param fieldName
* 属性名称
*/
public static void setFieldValue(Object object, String fieldName,
Object value) {
Field field = getAccessibleField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field "
+ fieldName);
}
try {
field.set(object, value);
} catch (IllegalAccessException e) {
}
}
// 获取字段的类型
public static String getFieldType(Object object, String fieldName) {
Field field = getAccessibleField(object, fieldName);
return field.getType().getSimpleName();
}
@SuppressWarnings("unused")
private static Field getAccessibleField(final Object object,
final String fieldName) {
for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
return null;
}
}
return null;
}
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
&& !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
}

View File

@ -0,0 +1,97 @@
package com.foxinmy.weixin4j.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
/**
* 工具包
*
* @className ServerToolkits
* @author jy
* @date 2015年12月26日
* @since JDK 1.7
* @see
*/
public final class ServerToolkits {
private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 返回一个定长的随机字符串(包含数字和大小写字母)
*
* @param length
* 随机数的长度
* @return
*/
public static String generateRandomString(int length) {
StringBuilder sb = new StringBuilder(length);
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 构造器设置为可见
*
* @param ctor
*/
public static void makeConstructorAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor
.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
/**
* SHA1签名
*
* @param content
* 待签名字符串
* @return 签名后的字符串
*/
public static String digestSHA1(String content) {
byte[] data = ServerToolkits.getBytesUtf8(content);
try {
return HexUtil.encodeHexString(MessageDigest.getInstance(
Consts.SHA1).digest(data));
} catch (NoSuchAlgorithmException e) {
return null;
}
}
private static String newString(final byte[] bytes, final Charset charset) {
return bytes == null ? null : new String(bytes, charset);
}
public static byte[] getBytesUtf8(final String content) {
return content != null ? content.getBytes(Consts.UTF_8) : null;
}
public static String newStringUtf8(final byte[] bytes) {
return newString(bytes, Consts.UTF_8);
}
/**
* 判断字符串是否为空
*
* @param cs
* @return
*/
public static boolean hasText(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
}

View File

@ -1,99 +0,0 @@
package com.foxinmy.weixin4j.util;
import java.nio.charset.Charset;
/**
* 字符串工具类
*
* @className StringUtil
* @author jy
* @date 2015年5月17日
* @since JDK 1.6
* @see
*/
public final class StringUtil {
public static final String EMPTY = "";
public static final int INDEX_NOT_FOUND = -1;
private static byte[] getBytes(final String content, final Charset charset) {
if (content == null) {
return null;
}
return content.getBytes(charset);
}
private static String newString(final byte[] bytes, final Charset charset) {
return bytes == null ? null : new String(bytes, charset);
}
public static byte[] getBytesUtf8(final String content) {
return getBytes(content, Consts.UTF_8);
}
public static String newStringUtf8(final byte[] bytes) {
return newString(bytes, Consts.UTF_8);
}
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) {
return false;
}
}
return true;
}
public static String capitalize(final String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
char firstChar = str.charAt(0);
if (Character.isTitleCase(firstChar)) {
// already capitalized
return str;
}
return new StringBuilder(strLen)
.append(Character.toTitleCase(firstChar))
.append(str.substring(1)).toString();
}
public static String substringBefore(final String str,
final String separator) {
if (isEmpty(str) || separator == null) {
return str;
}
if (separator.isEmpty()) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return str;
}
return str.substring(0, pos);
}
public static String substringAfter(final String str, final String separator) {
if (isEmpty(str)) {
return str;
}
if (separator == null) {
return EMPTY;
}
final int pos = str.indexOf(separator);
if (pos == INDEX_NOT_FOUND) {
return EMPTY;
}
return str.substring(pos + separator.length());
}
}

View File

@ -15,7 +15,7 @@ import com.foxinmy.weixin4j.request.WeixinRequest;
import com.foxinmy.weixin4j.socket.WeixinMessageTransfer;
import com.foxinmy.weixin4j.type.AccountType;
import com.foxinmy.weixin4j.util.Consts;
import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.util.ServerToolkits;
/**
* 微信消息
@ -76,7 +76,7 @@ public class MessageTransferHandler extends DefaultHandler {
if (isQY) {
return AccountType.QY;
}
if (StringUtil.isBlank(msgType) && StringUtil.isBlank(eventType)) {
if (ServerToolkits.hasText(msgType) && ServerToolkits.hasText(eventType)) {
return null;
}
return AccountType.MP;