Przeglądaj źródła

--create common service

jiapeng 8 lat temu
rodzic
commit
17a2567f9e

+ 125 - 107
jfwUtil/src/main/java/org/jfw/util/StringUtil.java

15
import java.util.UUID;
15
import java.util.UUID;
16
16
17
public final class StringUtil {
17
public final class StringUtil {
18
	private StringUtil() {
19
	}
20
21
	public static String fromWithUTF8(InputStream in) throws IOException {
22
		char[] buf = new char[1024];
23
		Reader r = new BufferedReader(new InputStreamReader(in, ConstData.UTF8));
24
		int len = 0;
25
		StringBuilder sb = new StringBuilder();
26
		while ((len = r.read(buf)) != -1) {
27
			if (len > 0)
28
				sb.append(buf, 0, len);
29
		}
30
		return sb.toString();
31
	}
32
33
	public static String fromByUTF8AndClose(InputStream in) throws IOException {
34
		try {
35
			char[] buf = new char[1024];
36
			Reader r = new BufferedReader(new InputStreamReader(in, ConstData.UTF8));
37
			int len = 0;
38
			StringBuilder sb = new StringBuilder();
39
			while ((len = r.read(buf)) != -1) {
40
				if (len > 0)
41
					sb.append(buf, 0, len);
42
			}
43
			return sb.toString();
44
		} finally {
45
			try {
46
				in.close();
47
			} catch (Exception e) {
48
			}
49
		}
50
	}
51
52
	public static Map<String, String[]> decodeURLQueryString(String queryString) throws UnsupportedEncodingException {
53
		Map<String, String[]> result = new HashMap<String, String[]>();
54
		if (queryString != null) {
55
			List<String> list = ListUtil.splitTrimExcludeEmpty(queryString, '&');
56
			for (String str : list) {
57
				int index = str.indexOf('=');
58
				if (index > 0) {
59
					String key = str.substring(0, index);
60
					String value = str.substring(index + 1);
61
					if (value.length() > 0)
62
						value = java.net.URLDecoder.decode(str.substring(index + 1), "UTF-8");
63
					String[] values = result.get(key);
64
					if (values == null) {
65
						values = new String[] { value };
66
					} else {
67
						String[] nv = new String[values.length + 1];
68
						System.arraycopy(values, 0, nv, 0, values.length);
69
						nv[values.length] = value;
70
						values = nv;
71
					}
72
					result.put(key, values);
73
				}
74
			}
75
76
		}
77
78
		return result;
79
	}
80
81
	public static String buildUUID() {
82
		return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(Locale.US);
83
	}
84
85
	public static String md5(String str) {
86
		byte[] bytes = str.getBytes(ConstData.UTF8);
87
		MessageDigest md5 = null;
88
		try {
89
			md5 = MessageDigest.getInstance("MD5");
90
		} catch (NoSuchAlgorithmException e) {
91
			throw new RuntimeException("jdk unsupported md5???????????", e);
92
		}
93
		md5.update(bytes);
94
		byte[] tmp = md5.digest();
95
		StringBuilder sb = new StringBuilder();
96
		for (byte b : tmp) {
97
			sb.append(digits[(b & 0xf0) >> 4]);
98
			sb.append(digits[b & 0xf]);
99
		}
100
		return sb.toString();
101
	}
102
103
	public static String toHexString(byte b) {
104
		char[] cs = new char[2];
105
		cs[1] = digits[b & 0xf];
106
		cs[0] = digits[(b & 0xf0) >> 4];
107
		return new String(cs);
108
	}
109
110
	public static String toHexString(int i) {
111
		char[] cs = new char[4];
112
		cs[3] = digits[i & 0xf];
113
		cs[2] = digits[(i & 0xf0) >> 4];
114
		cs[1] = digits[(i & 0xf00) >> 8];
115
		cs[0] = digits[(i & 0xf000) >> 12];
116
		return new String(cs);
117
	}
118
119
	final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
120
121
	public static void main(String[] args) {
122
		System.out.println(toHexString(0x1fff));
123
124
	}
18
    private StringUtil() {
19
    }
20
21
    public static String fromWithUTF8(InputStream in) throws IOException {
22
        char[] buf = new char[1024];
23
        Reader r = new BufferedReader(new InputStreamReader(in, ConstData.UTF8));
24
        int len = 0;
25
        StringBuilder sb = new StringBuilder();
26
        while ((len = r.read(buf)) != -1) {
27
            if (len > 0)
28
                sb.append(buf, 0, len);
29
        }
30
        return sb.toString();
31
    }
32
33
    public static String fromByUTF8AndClose(InputStream in) throws IOException {
34
        try {
35
            char[] buf = new char[1024];
36
            Reader r = new BufferedReader(new InputStreamReader(in, ConstData.UTF8));
37
            int len = 0;
38
            StringBuilder sb = new StringBuilder();
39
            while ((len = r.read(buf)) != -1) {
40
                if (len > 0)
41
                    sb.append(buf, 0, len);
42
            }
43
            return sb.toString();
44
        } finally {
45
            try {
46
                in.close();
47
            } catch (Exception e) {
48
            }
49
        }
50
    }
51
52
    public static Map<String, String[]> decodeURLQueryString(String queryString) throws UnsupportedEncodingException {
53
        Map<String, String[]> result = new HashMap<String, String[]>();
54
        if (queryString != null) {
55
            List<String> list = ListUtil.splitTrimExcludeEmpty(queryString, '&');
56
            for (String str : list) {
57
                int index = str.indexOf('=');
58
                if (index > 0) {
59
                    String key = str.substring(0, index);
60
                    String value = str.substring(index + 1);
61
                    if (value.length() > 0)
62
                        value = java.net.URLDecoder.decode(str.substring(index + 1), "UTF-8");
63
                    String[] values = result.get(key);
64
                    if (values == null) {
65
                        values = new String[] { value };
66
                    } else {
67
                        String[] nv = new String[values.length + 1];
68
                        System.arraycopy(values, 0, nv, 0, values.length);
69
                        nv[values.length] = value;
70
                        values = nv;
71
                    }
72
                    result.put(key, values);
73
                }
74
            }
75
76
        }
77
78
        return result;
79
    }
80
81
    public static String buildUUID() {
82
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase(Locale.US);
83
    }
84
85
    public static String md5(String str) {
86
        byte[] bytes = str.getBytes(ConstData.UTF8);
87
        MessageDigest md5 = null;
88
        try {
89
            md5 = MessageDigest.getInstance("MD5");
90
        } catch (NoSuchAlgorithmException e) {
91
            throw new RuntimeException("jdk unsupported md5???????????", e);
92
        }
93
        md5.update(bytes);
94
        byte[] tmp = md5.digest();
95
        StringBuilder sb = new StringBuilder();
96
        for (byte b : tmp) {
97
            sb.append(digits[(b & 0xf0) >> 4]);
98
            sb.append(digits[b & 0xf]);
99
        }
100
        return sb.toString();
101
    }
102
103
    public static String toHexString(byte b) {
104
        char[] cs = new char[2];
105
        cs[1] = digits[b & 0xf];
106
        cs[0] = digits[(b & 0xf0) >> 4];
107
        return new String(cs);
108
    }
109
110
    public static String toHexString(int i) {
111
        char[] cs = new char[4];
112
        cs[3] = digits[i & 0xf];
113
        cs[2] = digits[(i & 0xf0) >> 4];
114
        cs[1] = digits[(i & 0xf00) >> 8];
115
        cs[0] = digits[(i & 0xf000) >> 12];
116
        return new String(cs);
117
    }
118
119
    public static String bytesToStringDesc(byte[] bytes) {
120
        if (null == bytes)
121
            return "null";
122
        StringBuilder sb = new StringBuilder();
123
        sb.append("[");
124
        char[] cs = new char[3];
125
        cs[2]=',';
126
        for (int i = 0; i < bytes.length; ++i) {
127
            byte b = bytes[i];
128
            cs[1] = digits[b & 0xf];
129
            cs[0] = digits[(b & 0xf0) >> 4];
130
            sb.append(cs);
131
132
        }
133
        sb.append("]");
134
        return sb.toString();
135
    }
136
137
    final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
138
139
    public static void main(String[] args) {
140
        System.out.println(toHexString(0x1fff));
141
142
    }
125
143
126
}
144
}

+ 107 - 0
jfwUtil/src/main/java/org/jfw/util/cache/CacheService.java

1
package org.jfw.util.cache;
2

3
import java.lang.reflect.Type;
4

5
public interface CacheService {
6
    /**
7
     * cache a object,non expired
8
     * @param obj cached object     not null
9
     * @return  key in cache area
10
     * @throws JfwCacheException
11
     */
12
    String put(Object obj) throws JfwCacheException;
13
    /**
14
     * cache object with specified expire time
15
     * @param obj cached object   not null
16
     * @param expireTime  unit is millisecond    =0 ||  expireTime > System.currMilliseconds,   0  is non expired   
17
     *                expireTime  is deadline
18
     * @return
19
     * @throws JfwCacheException
20
     */
21
    String put(Object obj,long expireTime)throws JfwCacheException;
22
    
23
    
24
    /**
25
     * cache a object,non expired
26
     * @param key 
27
     * @param obj cached object     not null
28
     * @return  key in cache area
29
     * @throws JfwCacheException
30
     */
31
    void put(String key,Object obj) throws JfwCacheException;
32
    /**
33
     * cache object with specified expire time
34
     * @param key 
35
     * @param obj cached object   not null
36
     * @param expireTime  unit is millisecond    =0 ||  expireTime > System.currMilliseconds,   0  is non expired   
37
     *                expireTime  is deadline
38
     * @return
39
     * @throws JfwCacheException
40
     */
41
    void put(String key,Object obj,long expireTime)throws JfwCacheException;
42
    
43
    /**
44
     * modify expire time with a cache object ,
45
     * @param key  key with cache object
46
     * @param newExprieTime new exprie time unit is millisecond    =0 ||  expireTime > System.currMilliseconds,   0  is non expired   
47
     *                expireTime  is deadline
48
     * @return  old exprie time , -1 is not exists 
49
     * @throws JfwCacheException
50
     */
51
    long expire(String key,long newExprieTime) throws JfwCacheException;
52
    /**
53
     * 
54
     * @param key
55
     * @return exprie time , -1 is not exists
56
     * @throws JfwCacheException
57
     */
58
    long getExprieTime(String key) throws JfwCacheException;
59
    /**
60
     * 
61
     * @param key
62
     * @return
63
     * @throws JfwCacheException
64
     */
65
    <T> T get(String key,Class<T> clazz)throws JfwCacheException;
66
    <T> T get(String key,Type typeOfT) throws JfwCacheException;
67
    Object get(String key)throws JfwCacheException;
68
    
69
    String put(int i)throws JfwCacheException;
70
    String put(byte b)throws JfwCacheException;
71
    String put(short s)throws JfwCacheException;
72
    String put(long l)throws JfwCacheException;
73
    String put(float f)throws JfwCacheException;
74
    String put(double d)throws JfwCacheException;
75
    String put(boolean b)throws JfwCacheException;
76
    String put(String s)throws JfwCacheException;
77
    String put(String key,int i)throws JfwCacheException;
78
    String put(String key,byte b)throws JfwCacheException;
79
    String put(String ket,short s)throws JfwCacheException;
80
    String put(String key,long l)throws JfwCacheException;
81
    String put(String key,float f)throws JfwCacheException;
82
    String put(String key,double d)throws JfwCacheException;
83
    String put(String key,boolean b)throws JfwCacheException;
84
    String put(String key,String s)throws JfwCacheException;
85
    
86
    int get(String key,int defaultValue)throws JfwCacheException;   
87
    byte get(String key,byte defaultValue)throws JfwCacheException;   
88
    short get(String key,short defaultValue)throws JfwCacheException;  
89
    long get(String key,long defaultValue)throws JfwCacheException;   
90
    float get(String key,float defaultValue)throws JfwCacheException;  
91
    double get(String key,double defaultValue)throws JfwCacheException; 
92
    boolean get(String key,boolean defaultValue)throws JfwCacheException;
93
    
94
    
95
    /**
96
     * remove a cached object 
97
     * @param key
98
     * @return true exists , false not exists 
99
     * @throws JfwCacheException
100
     */
101
    boolean remove(String key)throws JfwCacheException;
102
    
103
    
104
    
105

106
    
107
}

+ 8 - 0
jfwUtil/src/main/java/org/jfw/util/cache/JfwCacheException.java

1
package org.jfw.util.cache;
2

3
import org.jfw.util.exception.JfwBaseException;
4
//TODO : define exception 
5
public class JfwCacheException extends JfwBaseException{
6
    private static final long serialVersionUID = -4683352043487231658L;
7

8
}

+ 77 - 0
jfwUtil/src/main/java/org/jfw/util/codec/Base64CodecService.java

1
package org.jfw.util.codec;
2

3
import java.nio.charset.Charset;
4

5
import org.jfw.util.ConstData;
6

7
public class Base64CodecService implements CodecService {
8
    public static final String CODEC_TYPE="BASE64";
9
    @Override
10
    public byte[] encode(byte[] bytes) {
11
        if (bytes == null || bytes.length == 0) {
12
            return bytes;
13
        }
14
        return (new Base64(false)).encode(bytes);
15
    }
16

17
    @Override
18
    public byte[] decode(byte[] bytes) {
19
        if (bytes == null || bytes.length == 0) {
20
            return bytes;
21
        }
22
        return (new Base64(false)).decode(bytes);
23
    }
24

25
    @Override
26
    public byte[] encode(byte[] bytes, byte[] key) {
27
       return this.encode(bytes);
28
    }
29

30
    @Override
31
    public byte[] decode(byte[] bytes, byte[] key) {
32
       return this.decode(bytes);
33
    }
34

35
    @Override
36
    public String encode(String s) {
37
        return new String(this.encode(s.getBytes(ConstData.UTF8)),ConstData.UTF8);
38
    }
39

40
    @Override
41
    public String decode(String s) {
42
        return new String(this.decode(s.getBytes(ConstData.UTF8)),ConstData.UTF8);
43
    }
44

45
    @Override
46
    public String encode(String s, byte[] key) {
47
        return this.encode(s);
48
    }
49

50
    @Override
51
    public String decode(String s, byte[] key) {
52
      return this.decode(s);
53
    }
54

55
    @Override
56
    public String encode(String s, String enc) {
57
        Charset c = Charset.forName(enc);
58
        return new String(this.encode(s.getBytes(c)),c);
59
    }
60

61
    @Override
62
    public String decode(String s, String enc) {
63
        Charset c = Charset.forName(enc);
64
        return new String(this.decode(s.getBytes(c)),c);
65
    }
66

67
    @Override
68
    public String encode(String s, byte[] key, String enc) {
69
      return this.encode(s, enc);
70
    }
71

72
    @Override
73
    public String decode(String s, byte[] key, String enc) {
74
        return this.decode(s, enc);
75
    }
76

77
}

+ 77 - 0
jfwUtil/src/main/java/org/jfw/util/codec/CodecService.java

1
package org.jfw.util.codec;
2

3
public interface CodecService {
4
    /**
5
     * Encodes a byte array  using default key
6
     * @param bytes  byte array to be encoded.
7
     * @return the encoded byte array
8
     */
9
    byte[] encode(byte[] bytes)throws JfwCodecException;
10
    /**
11
     * Decodes a byte array  using default key
12
     * @param bytes  byte array to be Decoded.
13
     * @return the decoded byte array
14
     */
15
    byte[] decode(byte[] bytes)throws JfwCodecException;
16
    /**
17
     * Encodes a byte array  using specified key
18
     * @param bytes  byte array to be encoded.
19
     * @return the encoded byte array
20
     * @throws JfwCodecKeyException 
21
     */
22
    byte[] encode(byte[] bytes,byte[] key)throws JfwCodecException;
23
    /**
24
     * Decodes a byte array  using specified key
25
     * @param bytes  byte array to be decoded.
26
     * @return the decoded byte array
27
     */
28
    byte[] decode(byte[] bytes,byte[] key)throws JfwCodecException;
29
    /**
30
     * Encode a string  by UTF-8  using default key
31
     * @param s String to be encoded.
32
     * @return the encoded String
33
     */
34
    String encode(String s)throws JfwCodecException;
35
    /**
36
     * Decodes a String by UTF-8  using default key
37
     * @param s  a String to be decoded.
38
     * @return the decoded String
39
     */  
40
    String decode(String s)throws JfwCodecException;
41
    /**
42
     * Encodes a String by UTF-8  using specified key
43
     * @param s  a String  to be encoded.
44
     * @return the encoded byte array
45
     */
46
    String encode(String s,byte[] key)throws JfwCodecException;
47
    /**
48
     * Decodes a String by UTF-8  using specified key
49
     * @param s  a String to be decoded.
50
     * @return the decoded String
51
     */ 
52
    String decode(String s,byte[] key)throws JfwCodecException;
53
    /**
54
     * Encode a string  by specified charset  using default key
55
     * @param s String to be encoded.
56
     * @return the encoded String
57
     */
58
    String encode(String s,String enc)throws JfwCodecException;
59
    /**
60
     * Decodes a String by specified  using default key
61
     * @param s  a String to be decoded.
62
     * @return the decoded String
63
     */  
64
    String decode(String s,String enc)throws JfwCodecException;
65
    /**
66
     * Encode a string  by specified charset  using specified key
67
     * @param s String to be encoded.
68
     * @return the encoded String
69
     */
70
    String encode(String s,byte[] key,String enc)throws JfwCodecException;
71
    /**
72
     * Decodes a String by specified  using specified key
73
     * @param s  a String to be decoded.
74
     * @return the decoded String
75
     */  
76
    String decode(String s,byte[] key,String enc)throws JfwCodecException;   
77
}

+ 169 - 0
jfwUtil/src/main/java/org/jfw/util/codec/DesCodecService.java

1
package org.jfw.util.codec;
2

3
import java.security.InvalidKeyException;
4
import java.security.NoSuchAlgorithmException;
5
import java.security.SecureRandom;
6
import java.security.spec.InvalidKeySpecException;
7
import java.util.Random;
8

9
import javax.crypto.Cipher;
10
import javax.crypto.SecretKey;
11
import javax.crypto.SecretKeyFactory;
12
import javax.crypto.spec.DESKeySpec;
13

14
import org.jfw.util.StringUtil;
15

16
public class DesCodecService implements CodecService {
17

18
    public static final byte[] DEFAULT_KEY_BYTES = new byte[] { 65, 66, 67, 68, 69, 70, 71, 72 };
19
    public static final String CODEC_TYPE="DES";
20
    
21

22
    public static DESKeySpec createKey(byte[] key) throws JfwCodecException{
23
        try {
24
            return  new DESKeySpec(key);
25
        } catch (InvalidKeyException e) {
26
            throw new JfwInvalidCodecKeyException(CODEC_TYPE, key, e);
27
        }
28
    }
29

30
    @Override
31
    public byte[] encode(byte[] bytes) throws JfwCodecException {
32
        return this.encode(bytes,DEFAULT_KEY_BYTES);
33
    }
34

35
    @Override
36
    public byte[] decode(byte[] bytes) throws JfwCodecException {
37
       return this.decode(bytes,DEFAULT_KEY_BYTES);
38
    }
39

40
    @Override
41
    public byte[] encode(byte[] bytes, byte[] key) throws JfwCodecException {
42
        SecureRandom random = new SecureRandom();
43
        DESKeySpec desKey = createKey(key);
44
        SecretKeyFactory keyFactory;
45
        try {
46
            keyFactory = SecretKeyFactory.getInstance("DES");
47
        } catch (NoSuchAlgorithmException e) {
48
            throw new RuntimeException(e);
49
        }
50
        SecretKey securekey;
51
        try {
52
            securekey = keyFactory.generateSecret(desKey);
53
        } catch (InvalidKeySpecException e) {
54
            throw new JfwInvalidCodecKeyException(CODEC_TYPE, key, e);
55
        }
56
        Cipher cipher;
57
        try {
58
            cipher = Cipher.getInstance("DES");
59
        } catch (Exception e) {
60
            throw new RuntimeException(e);
61
        } 
62
        try {
63
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
64
        } catch (InvalidKeyException e) {
65
            throw new JfwInvalidCodecKeyException(CODEC_TYPE, key, e);
66
        }
67

68
        try {
69
            return cipher.doFinal(bytes);
70
        } catch (Exception e) {
71
            throw new JfwCodecException(CODEC_TYPE, 402, "encode error", e);
72
        } 
73
    }
74

75
    @Override
76
    public byte[] decode(byte[] bytes, byte[] key) throws JfwCodecException {
77
        SecureRandom random = new SecureRandom();
78
        DESKeySpec desKey = createKey(key);
79
        SecretKeyFactory keyFactory;
80
        try {
81
            keyFactory = SecretKeyFactory.getInstance("DES");
82
        } catch (NoSuchAlgorithmException e) {
83
            throw new RuntimeException(e);
84
        }
85
        SecretKey securekey;
86
        try {
87
            securekey = keyFactory.generateSecret(desKey);
88
        } catch (InvalidKeySpecException e) {
89
            throw new JfwInvalidCodecKeyException(CODEC_TYPE, key, e);
90
        }
91
        Cipher cipher;
92
        try {
93
            cipher = Cipher.getInstance("DES");
94
        } catch (Exception e) {
95
            throw new RuntimeException(e);
96
        } 
97
        try {
98
            cipher.init(Cipher.DECRYPT_MODE, securekey, random);
99
        } catch (InvalidKeyException e) {
100
            throw new JfwInvalidCodecKeyException(CODEC_TYPE, key, e);
101
        }
102

103
        try {
104
            return cipher.doFinal(bytes);
105
        } catch (Exception e) {
106
            throw new JfwCodecException(CODEC_TYPE, 403, "decode error", e);
107
        } 
108
    }
109

110
    @Override
111
    public String encode(String s) throws JfwCodecException {
112
        throw new UnsupportedOperationException();
113
    }
114

115
    @Override
116
    public String decode(String s) throws JfwCodecException {
117
        throw new UnsupportedOperationException();
118
    }
119

120
    @Override
121
    public String encode(String s, byte[] key) throws JfwCodecException {
122
        throw new UnsupportedOperationException();
123
    }
124

125
    @Override
126
    public String decode(String s, byte[] key) throws JfwCodecException {
127
        throw new UnsupportedOperationException();
128
    }
129

130
    @Override
131
    public String encode(String s, String enc) throws JfwCodecException {
132
        throw new UnsupportedOperationException();
133
    }
134

135
    @Override
136
    public String decode(String s, String enc) throws JfwCodecException {
137
        throw new UnsupportedOperationException();
138
    }
139

140
    @Override
141
    public String encode(String s, byte[] key, String enc) throws JfwCodecException {
142
        throw new UnsupportedOperationException();
143
    }
144

145
    @Override
146
    public String decode(String s, byte[] key, String enc) throws JfwCodecException {
147
        throw new UnsupportedOperationException();
148
    }
149

150
   
151
    
152
    public static void main(String[] args)throws Exception{
153
        Random ra =new Random();
154
        CodecService cs = new DesCodecService();
155
        int len = 256;
156
        byte[] source = new byte[len];
157
        for(int i = 0 ; i < len;++i){
158
            source[i] =(byte)(ra.nextInt(255)-128);
159
        }
160
      byte[] key= new byte[]{1,2,3,4,5,6,7,8};
161
        System.out.println(StringUtil.bytesToStringDesc(source));
162
        byte[] dest = cs.encode(source,key);
163
        System.out.println(""+dest.length+StringUtil.bytesToStringDesc(dest));
164
        
165
        byte[] es = cs.decode(dest,key);
166
        
167
        System.out.println(""+es.length+StringUtil.bytesToStringDesc(es));
168
    }
169
}

+ 57 - 0
jfwUtil/src/main/java/org/jfw/util/codec/JfwCodecException.java

1
package org.jfw.util.codec;
2

3
import org.jfw.util.exception.JfwBaseException;
4

5
public class JfwCodecException extends JfwBaseException {
6
    private static final long serialVersionUID = 6032614432891886439L;
7
    private String codecType;
8

9
    public JfwCodecException(String codecType) {
10
        super();
11
        this.codecType = codecType;
12
    }
13

14
    public JfwCodecException(String codecType, int code, String message, Throwable cause) {
15
        super(code, message, cause);
16
        this.codecType = codecType;
17
    }
18

19
    public JfwCodecException(String codecType, int code, String message) {
20
        super(code, message);
21
        this.codecType = codecType;
22
    }
23

24
    public JfwCodecException(String codecType, int code, Throwable cause) {
25
        super(code, cause);
26
        this.codecType = codecType;
27
    }
28

29
    public JfwCodecException(String codecType, int code) {
30
        super(code);
31
        this.codecType = codecType;
32
    }
33

34
    public JfwCodecException(String codecType, String message, Throwable cause) {
35
        super(message, cause);
36
        this.codecType = codecType;
37
    }
38

39
    public JfwCodecException(String codecType, String message) {
40
        super(message);
41
        this.codecType = codecType;
42
    }
43

44
    public JfwCodecException(String codecType, Throwable cause) {
45
        super(cause);
46
        this.codecType = codecType;
47
    }
48

49
    public String getCodecType() {
50
        return codecType;
51
    }
52

53
    public void setCodecType(String codecType) {
54
        this.codecType = codecType;
55
    }
56
    
57
}

+ 21 - 0
jfwUtil/src/main/java/org/jfw/util/codec/JfwInvalidCodecKeyException.java

1
package org.jfw.util.codec;
2

3
import org.jfw.util.StringUtil;
4

5
public class JfwInvalidCodecKeyException extends JfwCodecException {
6
    private static final long serialVersionUID = 2397737655762171304L;
7
    private byte[] key;
8

9
    public byte[] getKey() {
10
        return key;
11
    }
12

13
    public void setKey(byte[] key) {
14
        this.key = key;
15
    }
16

17
    public JfwInvalidCodecKeyException(String codecType,byte[] key,Throwable cause ) {
18
        super(codecType,401,"Invalid codec key:"+StringUtil.bytesToStringDesc(key),cause);
19
        this.key = key;
20
    }
21
}

+ 22 - 0
jfwUtil/src/main/java/org/jfw/util/codec/UrlSafeBase64CodecService.java

1
package org.jfw.util.codec;
2

3
public class UrlSafeBase64CodecService extends Base64CodecService {
4
    public static final String CODEC_TYPE="BASE64_URLSAFE";
5
    @Override
6
    public byte[] encode(byte[] bytes) {
7
        if (bytes == null || bytes.length == 0) {
8
            return bytes;
9
        }
10
        return (new Base64(true)).encode(bytes);
11
    }
12

13
    @Override
14
    public byte[] decode(byte[] bytes) {
15
        if (bytes == null || bytes.length == 0) {
16
            return bytes;
17
        }
18
        return (new Base64(true)).decode(bytes);
19
    }
20
    
21

22
}

+ 34 - 0
jfwUtil/src/main/java/org/jfw/util/pojo/BuildTimeObj.java

1
package org.jfw.util.pojo;
2

3
public class BuildTimeObj<T> {
4
    protected long buildTime;
5
    protected T value;
6

7
    public BuildTimeObj() {
8
        this.buildTime = System.currentTimeMillis();
9
    }
10

11
    public BuildTimeObj(T obj) {
12
       
13
        this.buildTime = System.currentTimeMillis();
14
        this.value = obj;
15
    }
16

17
    public long getBuildTime() {
18
        return buildTime;
19
    }
20

21
    public void setBuildTime(long buildTime) {
22
        if (buildTime >= 0)
23
            this.buildTime = buildTime;
24
    }
25

26
    public T getValue() {
27
        return value;
28
    }
29

30
    public void setValue(T value) {
31
        this.value = value;
32
    }
33

34
}

+ 24 - 0
jfwUtil/src/main/java/org/jfw/util/pojo/Entity.java

1
package org.jfw.util.pojo;
2

3
public class Entity<K,V> {
4
    protected K key;
5
    protected V value;
6
    
7
    public Entity(){}
8
    public Entity(K key,V value){
9
        this.key = key;
10
        this.value = value;
11
    }
12
    public K getKey() {
13
        return key;
14
    }
15
    public void setKey(K key) {
16
        this.key = key;
17
    }
18
    public V getValue() {
19
        return value;
20
    }
21
    public void setValue(V value) {
22
        this.value = value;
23
    }
24
}

+ 26 - 0
jfwUtil/src/main/java/org/jfw/util/pojo/ExpireObj.java

1
package org.jfw.util.pojo;
2

3
public class ExpireObj<T> extends BuildTimeObj<T> {
4
    protected long expireTime;
5
    public ExpireObj(){
6
        super();
7
        this.expireTime = Long.MAX_VALUE;
8
    }
9
    public ExpireObj(T obj){
10
        super(obj);
11
        this.expireTime = Long.MAX_VALUE;
12
    }
13
    public long getExpireTime() {
14
        return expireTime;
15
    }
16
    public void setExpireTime(long expireTime) {
17
        this.expireTime = expireTime;
18
    }
19
    public void setSurvivalTime(long time){
20
        long max = Long.MAX_VALUE - this.getBuildTime();
21
        if(max>= time) this.expireTime = this.buildTime+time;
22
    }
23
    public boolean isExpired(){
24
        return this.expireTime < System.currentTimeMillis();
25
    }
26
}

+ 73 - 0
jfwUtil/src/main/java/org/jfw/util/secure/DefaultSecureService.java

1
package org.jfw.util.secure;
2

3
import java.lang.reflect.Type;
4

5
import org.jfw.util.ConstData;
6
import org.jfw.util.codec.CodecService;
7
import org.jfw.util.codec.DesCodecService;
8
import org.jfw.util.codec.UrlSafeBase64CodecService;
9
import org.jfw.util.exception.JfwBaseException;
10
import org.jfw.util.serializer.DefaultJsonSerializeService;
11
import org.jfw.util.serializer.SerializeService;
12

13
public class DefaultSecureService implements SecureService {
14
    private CodecService base64Codec  = new UrlSafeBase64CodecService();
15
    private CodecService secureCodec = new DesCodecService();
16
    private SerializeService serializeService = new DefaultJsonSerializeService();
17
    
18

19
    public SerializeService getSerializeService() {
20
        return serializeService;
21
    }
22

23
    public void setSerializeService(SerializeService serializeService) {
24
        this.serializeService = serializeService;
25
    }
26

27
    public CodecService getBase64Codec() {
28
        return base64Codec;
29
    }
30

31
    public void setBase64Codec(CodecService base64Codec) {
32
        this.base64Codec = base64Codec;
33
    }
34

35
    public CodecService getSecureCodec() {
36
        return secureCodec;
37
    }
38

39
    public void setSecureCodec(CodecService secureCodec) {
40
        this.secureCodec = secureCodec;
41
    }
42

43
    @Override
44
    public byte[] serialize(Object obj) throws JfwBaseException {
45
       return this.secureCodec.encode(this.serializeService.serialize(obj));
46
    }
47

48
    @Override
49
    public <T> T deSerialize(byte[] bytes, Class<T> clazz) throws JfwBaseException {
50
        return this.serializeService.deSerialize(this.secureCodec.decode(bytes), clazz);
51
    }
52

53
    @Override
54
    public <T> T deSerialize(byte[] bytes, Type type) throws JfwBaseException {
55
        return this.serializeService.deSerialize(this.secureCodec.decode(bytes), type);
56
    }
57

58
    @Override
59
    public String serializeToString(Object obj) throws JfwBaseException {
60
       return new String(this.base64Codec.encode(this.serialize(obj)),ConstData.UTF8);
61
    }
62

63
    @Override
64
    public <T> T deSerialize(String s, Class<T> clazz) throws JfwBaseException {
65
       return this.deSerialize(s.getBytes(ConstData.UTF8), clazz);
66
    }
67

68
    @Override
69
    public <T> T deSerialize(String s, Type type) throws JfwBaseException {
70
        return this.deSerialize(s.getBytes(ConstData.UTF8), type);
71
    }
72

73
}

+ 14 - 0
jfwUtil/src/main/java/org/jfw/util/secure/SecureService.java

1
package org.jfw.util.secure;
2

3
import java.lang.reflect.Type;
4

5
import org.jfw.util.exception.JfwBaseException;
6

7
public interface SecureService {
8
    byte[] serialize(Object obj) throws JfwBaseException;
9
    <T> T deSerialize(byte[] bytes,Class<T> clazz) throws JfwBaseException;
10
    <T> T deSerialize(byte[] bytes,Type type)throws JfwBaseException;
11
    String serializeToString(Object obj) throws JfwBaseException;
12
    <T> T deSerialize(String s,Class<T> clazz) throws JfwBaseException;
13
    <T> T deSerialize(String s,Type type)throws JfwBaseException;    
14
}

+ 74 - 0
jfwUtil/src/main/java/org/jfw/util/serializer/DefaultJsonSerializeService.java

1
package org.jfw.util.serializer;
2

3
import java.io.InputStream;
4
import java.io.InputStreamReader;
5
import java.io.OutputStream;
6
import java.io.OutputStreamWriter;
7
import java.lang.reflect.Type;
8

9
import org.jfw.util.ConstData;
10
import org.jfw.util.exception.JfwBaseException;
11

12
import com.google.gson.Gson;
13
import com.google.gson.JsonIOException;
14
import com.google.gson.JsonSyntaxException;
15

16
public class DefaultJsonSerializeService implements SerializeService{
17

18
    private final static Gson gson = new Gson();;
19
    @Override
20
    public byte[] serialize(Object obj) {
21
       if(obj==null) throw new NullPointerException();
22
       return gson.toJson(obj).getBytes(ConstData.UTF8);
23
    }
24

25
    @Override
26
    public SerializeService serialize(Object obj, OutputStream out) throws JfwBaseException {
27
      try {
28
        gson.toJson(obj, new OutputStreamWriter(out, ConstData.UTF8));
29
    } catch (JsonIOException e) {
30
        //TODO:  define JfwSerializeException
31
        throw new JfwBaseException(e);    }
32
      return this;
33
    }
34

35
    @Override
36
    public <T> T deSerialize(byte[] bytes, Class<T> clazz) throws JfwBaseException {
37
        try {
38
            return gson.fromJson(new String(bytes,ConstData.UTF8), clazz);
39
        } catch (JsonSyntaxException e) {
40
            //TODO:  define JfwSerializeException
41
            throw new JfwBaseException(e);    
42
        }
43
    }
44

45
    @Override
46
    public <T> T deSerialize(byte[] bytes, Type type) throws JfwBaseException {
47
        try {
48
            return gson.fromJson(new String(bytes,ConstData.UTF8), type);
49
        } catch (JsonSyntaxException e) {
50
            //TODO:  define JfwSerializeException
51
            throw new JfwBaseException(e);    
52
        }
53
    }
54

55
    @Override
56
    public <T> T deSerialize(InputStream in, Class<T> clazz) throws JfwBaseException {
57
        try {
58
            return gson.fromJson(new InputStreamReader(in,ConstData.UTF8), clazz);
59
        } catch (JsonSyntaxException e) {
60
            //TODO:  define JfwSerializeException
61
            throw new JfwBaseException(e);    
62
        }
63
    }
64

65
    @Override
66
    public <T> T deSerialize(InputStream in, Type type) throws JfwBaseException {
67
        try {
68
            return gson.fromJson(new InputStreamReader(in,ConstData.UTF8), type);
69
        } catch (JsonSyntaxException e) {
70
            //TODO:  define JfwSerializeException
71
            throw new JfwBaseException(e);    
72
        }
73
    }
74
}

+ 29 - 0
jfwUtil/src/main/java/org/jfw/util/serializer/SerializeService.java

1
package org.jfw.util.serializer;
2

3
import java.io.InputStream;
4
import java.io.OutputStream;
5
import java.lang.reflect.Type;
6

7
import org.jfw.util.exception.JfwBaseException;
8
//TODO:  define JfwSerializeException
9
public interface SerializeService {
10
    /**
11
     * serialize a object
12
     * 
13
     * @param obj
14
     *            is not null
15
     * @return
16
     */
17
    byte[] serialize(Object obj);
18

19
    SerializeService serialize(Object obj, OutputStream out) throws JfwBaseException;
20

21
    <T> T deSerialize(byte[] bytes, Class<T> clazz) throws JfwBaseException;
22

23
    <T> T deSerialize(byte[] bytes, Type type) throws JfwBaseException;
24

25
    <T> T deSerialize(InputStream in, Class<T> clazz) throws JfwBaseException;
26

27
    <T> T deSerialize(InputStream in, Type type) throws JfwBaseException;
28

29
}