1 package com.zone.weixin4j.util;
2
3 import com.zone.weixin4j.socket.WeixinMessageTransfer;
4 import java.lang.reflect.Constructor;
5 import java.lang.reflect.Modifier;
6 import java.nio.charset.Charset;
7 import java.security.MessageDigest;
8 import java.security.NoSuchAlgorithmException;
9 import java.util.Random;
10
11
12
13
14
15
16
17
18
19
20 public final class ServerToolkits {
21 private static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
22 public static final Charset UTF_8 = Charset.forName("UTF-8");
23 public static final String AES = "AES";
24 public static final String SHA1 = "SHA-1";
25 public static final String PROTOCOL_FILE = "file";
26 public static final String PROTOCOL_JAR = "jar";
27 public static final String CONTENTTYPE$APPLICATION_XML = "application/xml";
28 public static final String CONTENTTYPE$TEXT_PLAIN = "text/plain";
29
30
31
32
33
34
35
36
37 public static String generateRandomString(int length) {
38 StringBuilder sb = new StringBuilder(length);
39 Random random = new Random();
40 for (int i = 0; i < length; i++) {
41 sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
42 }
43 return sb.toString();
44 }
45
46
47
48
49
50
51 public static void makeConstructorAccessible(Constructor<?> ctor) {
52 if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor
53 .getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
54 ctor.setAccessible(true);
55 }
56 }
57
58
59
60
61
62
63
64
65 public static String digestSHA1(String content) {
66 byte[] data = ServerToolkits.getBytesUtf8(content);
67 try {
68 return HexUtil.encodeHexString(MessageDigest.getInstance(SHA1)
69 .digest(data));
70 } catch (NoSuchAlgorithmException e) {
71 return null;
72 }
73 }
74
75 private static String newString(final byte[] bytes, final Charset charset) {
76 return bytes == null ? null : new String(bytes, charset);
77 }
78
79 public static byte[] getBytesUtf8(final String content) {
80 return content != null ? content.getBytes(UTF_8) : null;
81 }
82
83 public static String newStringUtf8(final byte[] bytes) {
84 return newString(bytes, UTF_8);
85 }
86
87
88
89
90
91
92
93 public static boolean isBlank(final CharSequence cs) {
94 int strLen;
95 if (cs == null || (strLen = cs.length()) == 0) {
96 return true;
97 }
98 for (int i = 0; i < strLen; i++) {
99 if (Character.isWhitespace(cs.charAt(i)) == false) {
100 return false;
101 }
102 }
103 return true;
104 }
105 }