当前位置 : 主页 > 编程语言 > java >

工具类

来源:互联网 收集:自由互联 发布时间:2021-06-28
平时收集别人的一些代码工具类 代码工具 CodeUtil.java package cn.edu.nuc.article.util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import
平时收集别人的一些代码工具类
代码工具
CodeUtil.java
package cn.edu.nuc.article.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 生成验证码工具
 * @author 王凯
 *
 */
public final class CodeUtil {

	/**
	 * 验证码字体
	 */
	private static Font[] codeFont = {
			new Font("Times New Roman", Font.PLAIN,30),
			new Font("Times New Roman", Font.PLAIN,30),
			new Font("Times New Roman", Font.PLAIN,30),
			new Font("Times New Roman", Font.PLAIN,30)
	};
	
	/**
	 * 验证码字符颜色
	 */
	private static Color[] color = {
		Color.BLACK,  Color.RED,  Color.DARK_GRAY,  Color.BLUE	
	};

	/**
	 * 生成验证码的字符(A-Z,a-z,0-9),验证码形成时将会从这里选取字符
	 */
	private static final String IMAGE_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
			+ "abcdefghijkmnpqrstuvwxyz23456789";
	
	/**
	 * 生成验证码图片的宽度
	 */
	private static final Integer IMAGE_WIDTH = 160;
	
	/**
	 * 生成验证码图片的高度
	 */
	private static final Integer IMAGE_HEIGHT = 40;
	
	/**
	* 功能函数:绘制验证码的一个字符
	* @param graphics 绘图对象(画笔)
	* @param i 验证码字符序号
	*/
	private static String drawCode(Graphics graphics, int i){
		Random random = new Random();
		//产生随机切割序号 0-61.9999
		Integer j = random.nextInt((IMAGE_CHAR.length()));
		//切割随机数
		String number = IMAGE_CHAR.substring(j, j+1);
		
		//设置验证码字符的字体和颜色
		graphics.setFont(codeFont[i]);
		graphics.setColor(color[i]);


		//绘制验证码到图片X、Y(每个字体x每步进13的倍数,y不变,大小6*6)
		//number是要绘制字符的值,
		//6 + i * 13 是要绘制的x轴坐标,x轴递增13实现字符之间间距为13
		//16是指字符绘制的y轴坐标
		graphics.drawString(number, 22 + i * 26, 28);

		return number;
	}

	/**
	* 产生随机背景色
	* @param fc 颜色基调
	* @param bc 颜色边界
	* @return 随机产生的背景色
	*/
	private static Color getRandColor(int fc,int bc){
		//随机对象
		Random random = new Random();
		//随机初始数值不得大于255
		if(fc > 255)
			fc = 255;
		//随机初始数值不得大于255
		if(bc > 255)
			bc = 255;
		//产生随机红蓝绿色调
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r,g,b);
	}

	/**
	* 功能函数:绘制干扰线
	* @param graphics 绘图对象(画笔)
	* @param lineNumber 干扰线条数
	*/
	private static void drawNoise(Graphics graphics, int lineNumber){
		//干扰线颜色
		graphics.setColor(getRandColor(160, 200));
		
		for (int i = 0; i < lineNumber; i++) {
			//线的起始X轴(只在80,20的范围内随机,由于从0开始,所以要加1)
			int pointX1 = 1 + (int) (Math.random() * 160);
			//Math类的random()方法生成0.0-1.0之间的随机数
			//线的起始Y轴(只在80,20的范围内随机,由于从0开始,所以要加1)
			int pointY1 = 1 + (int) (Math.random() * 40);
			//线的终止X轴(只在80,20的范围内随机,由于从0开始,所以要加1)
			int pointX2 = 1 + (int) (Math.random() * 160);
			//线的终止Y轴(只在80,20的范围内随机,由于从0开始,所以要加1)
			int pointY2 = 1 + (int) (Math.random() * 40);
			
			graphics.drawLine(pointX1, pointY1, pointX2, pointY2);
		}
	}

	/**
	* 覆写doGet方法,完成验证码的生成
	*/
	public static void drawCode(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/gif");
		
		//不设置缓存,页面不使用缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
			
		//创建一个图像,验证码显示图片大小
		BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, 
				BufferedImage.TYPE_INT_RGB);
		//BufferedImage.TYPE_INT_RGB表示图片中的每一个像素都可以由红绿蓝三种色调
		
		//获取图片绘制对象(画笔)
		Graphics g = image.getGraphics();
		
		//绘制图片背景颜色
		g.setColor(getRandColor(200, 250));
		
		//绘制背景图片
		g.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
		//前两个参数是指图形区域开始(左上角)的横纵坐标
		//后两个参数是指图形区域的宽度和高度
		
		String codeNumbers = "";
		//循环产生4位随机数
		for (int i = 0; i < 4; i++) {
			codeNumbers = codeNumbers + drawCode(g, i);
		}
		
		//添加干扰线
		drawNoise(g, 12);
		
		//将验证码内容保存进session中,用于验证用户输入是否正确时使用
		HttpSession session = request.getSession(true);
		session.removeAttribute("code");
		session.setAttribute("code", codeNumbers);
		
		//利用ImagieIO类的write方法对图像进行编码
		ServletOutputStream sos = response.getOutputStream();
		ImageIO.write(image, "GIF", sos);
		sos.close();
	}

}
MD5Helper.java
package cn.edu.nuc.article.util;  

/** 
 * 采用MD5加密解密 
 * @author 王凯 
 * @datetime 2011-10-13 
 */  
public class MD5Helper {  
	
	public static void main(String[] args) {
		System.out.println(new MD5Helper().getTwiceMD5ofString("123456"));
	}
    
    // 标准的构造函数,调用md5Init函数进行初始化工作  
    public MD5Helper() {  
        md5Init();  
        return;  
    }  
      
    // RFC1321中定义的标准4*4矩阵的常量定义。  
    static final int S11 = 7, S12 = 12, S13 = 17, S14 = 22;  
    static final int S21 = 5, S22 = 9, S23 = 14, S24 = 20;  
    static final int S31 = 4, S32 = 11, S33 = 16, S34 = 23;  
    static final int S41 = 6, S42 = 10, S43 = 15, S44 = 21;  
  
    // 按RFC1321标准定义不可变byte型数组PADDING  
    static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };  
  
    // MD5计算过程中的3组核心数据,采用数组形式存放  
    private long[] state = new long[4]; // 计算状态(分别对应a b c d)  
  
    private byte[] buffer = new byte[64]; // 分配64个字节私有缓冲区  
  
    private long[] count = new long[2]; // 位个数  
  
    // 最新一次计算结果的16进制ASCII字符串表示,代表了16个字符串形式的MD5值  
    public String resultStr;  
  
    // 最新一次计算结果的2进制数组表示,一共16个字节,代表了128bit形式的MD5值  
    public byte[] digest = new byte[16];  
  
      
    /** 
     * 获得两次MD5加密的字符串 
     * @param str 
     * @return 
     */  
    public String getTwiceMD5ofString(String str){  
        return getMD5ofStr(getMD5ofStr(str));  
    }  
      
    /** 
     * MD5_Encoding类提供的主要的接口函数getMD5ofStr,用来进行数据加密变换。调用其可对任意字符串进行加密运算,并以字符串形式返回加密结果。 
     * @param in 
     * @return 
     */  
    public String getMD5ofStr(String in) {  
        md5Init(); // 初始化  
        md5Update(in.getBytes(), in.length());// 调用MD5的主计算过程  
        md5Final(); // 输出结果到digest数组中  
        for (int i = 0; i < 16; i++) {  
            resultStr += byteToHEX(digest[i]); // 将digest数组中的每个byte型数据转为16进制形式的字符串  
        }  
        return resultStr;  
    }  
  
  
    // md5初始化函数.初始化核心变量.  
    private void md5Init() {  
        state[0] = 0x67452301L; // 定义state为RFC1321中定义的标准幻数  
        state[1] = 0xefcdab89L; // 定义state为RFC1321中定义的标准幻数  
        state[2] = 0x98badcfeL; // 定义state为RFC1321中定义的标准幻数  
        state[3] = 0x10325476L; // 定义state为RFC1321中定义的标准幻数  
        count[0] = count[1] = 0L; // 初始化为0  
        resultStr = "";// 初始化resultStr字符串为空  
        for (int i = 0; i < 16; i++)  
            digest[i] = 0;// 初始化digest数组元素为0  
        return;  
    }  
  
    // 定义F G H I 为4个基数 ,即为4个基本的MD5函数,进行简单的位运算  
    private long F(long x, long y, long z) {  
        return (x & y) | ((~x) & z);  
    }  
  
    private long G(long x, long y, long z) {  
        return (x & z) | (y & (~z));  
    }  
  
    private long H(long x, long y, long z) {  
        return x ^ y ^ z;  
    }  
  
    private long I(long x, long y, long z) {  
        return y ^ (x | (~z));  
    }  
  
    // FF,GG,HH和II调用F,G,H,I函数进行进一步变换  
    private long FF(long a, long b, long c, long d, long x, long s, long ac) {  
        a += F(b, c, d) + x + ac;  
        a = ((int) a << s) | ((int) a >>> (32 - s)); // 这里long型数据右移时使用无符号右移运算符>>>  
        a += b;  
        return a;  
    }  
  
    private long GG(long a, long b, long c, long d, long x, long s, long ac) {  
        a += G(b, c, d) + x + ac;  
        a = ((int) a << s) | ((int) a >>> (32 - s)); // 这里long型数据右移时使用无符号右移运算符>>>  
        a += b;  
        return a;  
    }  
  
    private long HH(long a, long b, long c, long d, long x, long s, long ac) {  
        a += H(b, c, d) + x + ac;  
        a = ((int) a << s) | ((int) a >>> (32 - s));// 这里long型数据右移时使用无符号右移运算符>>>  
        a += b;  
        return a;  
    }  
  
    private long II(long a, long b, long c, long d, long x, long s, long ac) {  
        a += I(b, c, d) + x + ac;  
        a = ((int) a << s) | ((int) a >>> (32 - s));// 这里long型数据右移时使用无符号右移运算符>>>  
        a += b;  
        return a;  
    }  
  
    // MD5的主计算过程,input是需要变换的二进制字节串,inputlen是长度  
    private void md5Update(byte[] input, int inputLen) {  
        int i = 0, index, partLen;  
        byte[] block = new byte[64]; // 分配64个字节缓冲区  
        // 根据count计算index值。这里long型数据右移时使用无符号右移运算符>>>  
        index = (int) (count[0] >>> 3) & 0x3F;  
        if ((count[0] += (inputLen << 3)) < (inputLen << 3))  
            count[1]++;  
        count[1] += (inputLen >>> 29); // 这里int型数据右移时使用无符号右移运算符>>>  
        partLen = 64 - index; // 计算partLen值  
        if (inputLen >= partLen) {  
            md5Memcpy(buffer, input, index, 0, partLen);  
            md5Transform(buffer);  
            for (i = partLen; i + 63 < inputLen; i += 64) {  
                md5Memcpy(block, input, 0, i, 64);  
                md5Transform(block);  
            }  
            index = 0;  
        } else  
            i = 0;  
        md5Memcpy(buffer, input, index, i, inputLen - i);  
    }  
  
    // 整理和填写输出结果,结果放到数组digest中。  
    private void md5Final() {  
        byte[] bits = new byte[8];  
        int index, padLen;  
        Encode(bits, count, 8);  
        index = (int) (count[0] >>> 3) & 0x3f; // 这里long型数据右移时使用无符号右移运算符>>>  
        padLen = (index < 56) ? (56 - index) : (120 - index);  
        md5Update(PADDING, padLen);  
        md5Update(bits, 8);  
        Encode(digest, state, 16);  
    }  
  
    // byte数组的块拷贝函数,将input数组中的起始位置为inpos,长度len的数据拷贝到output数组起始位置outpos处。  
    private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos, int len) {  
        int i;  
        for (i = 0; i < len; i++)  
            output[outpos + i] = input[inpos + i];  
    }  
  
    // MD5核心变换计算程序,由md5Update函数调用,block是分块的原始字节数组  
    private void md5Transform(byte block[]) {  
        long a = state[0], b = state[1], c = state[2], d = state[3];  
        long[] x = new long[16];  
        Decode(x, block, 64);  
        // 进行4级级联运算  
        // 第1级  
        a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */  
        d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */  
        c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */  
        b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */  
        a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */  
        d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */  
        c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */  
        b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */  
        a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */  
        d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */  
        c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */  
        b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */  
        a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */  
        d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */  
        c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */  
        b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */  
  
        // 第2级  
        a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */  
        d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */  
        c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */  
        b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */  
        a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */  
        d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */  
        c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */  
        b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */  
        a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */  
        d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */  
        c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */  
        b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */  
        a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */  
        d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */  
        c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */  
        b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */  
  
        // 第3级  
        a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */  
        d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */  
        c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */  
        b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */  
        a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */  
        d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */  
        c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */  
        b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */  
        a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */  
        d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */  
        c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */  
        b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */  
        a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */  
        d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */  
        c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */  
        b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */  
  
        // 第4级  
        a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */  
        d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */  
        c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */  
        b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */  
        a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */  
        d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */  
        c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */  
        b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */  
        a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */  
        d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */  
        c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */  
        b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */  
        a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */  
        d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */  
        c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */  
        b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */  
  
        // 分别累加到state[0],state[1],state[2],state[3]  
        state[0] += a;  
        state[1] += b;  
        state[2] += c;  
        state[3] += d;  
    }  
  
    // 把byte型数据转换为无符号long型数据  
    private static long byteToul(byte b) {  
        return b > 0 ? b : (b & 0x7F + 128);  
    }  
  
    // 把byte类型的数据转换成十六进制ASCII字符表示  
    private static String byteToHEX(byte in) {  
        char[] DigitStr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
        char[] out = new char[2];  
        out[0] = DigitStr[(in >> 4) & 0x0F]; // 取高4位  
        out[1] = DigitStr[in & 0x0F]; // 取低4位  
        String s = new String(out);  
        return s;  
    }  
  
    // 将long型数组按顺序拆成byte型数组,长度为len  
    private void Encode(byte[] output, long[] input, int len) {  
        int i, j;  
        for (i = 0, j = 0; j < len; i++, j += 4) {  
            output[j] = (byte) (input[i] & 0xffL);  
            output[j + 1] = (byte) ((input[i] >>> 8) & 0xffL);  
            output[j + 2] = (byte) ((input[i] >>> 16) & 0xffL);  
            output[j + 3] = (byte) ((input[i] >>> 24) & 0xffL);  
        }  
    }  
  
    // 将byte型数组按顺序合成long型数组,长度为len  
    private void Decode(long[] output, byte[] input, int len) {  
        int i, j;  
        for (i = 0, j = 0; j < len; i++, j += 4)  
            output[i] = byteToul(input[j]) | (byteToul(input[j + 1]) << 8) | (byteToul(input[j + 2]) << 16) | (byteToul(input[j + 3]) << 24);  
        return;  
    }  
  
}
DES.java
/*
 * DES		20091106
 * 
 * Copyright (c) 2009 北京数字政通科技股份有限公司
 * 版权所有
 * 
 * 文件功能描述:DES加密解密类
 *
 * 修改标识:史先方20091106
 * 修改描述:创建
 */
package com.github.lazylibrary.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 将字符串进行DES加密解密
 * 
 * @version	0.1	20091106
 * @author	史先方
 */
public class DES {
	
	/** 加密KEY */
	private static final byte[] KEY = "7;9Ku7;:84VG*B78".getBytes();
	/** 算法 */
	private static final String ALGORITHM = "DES";
	/** IV */
	private static final byte[] IV = "sHjrydLq".getBytes();
	/** TRANSFORMATION */
	private static final String TRANSFORMATION = "DES/CBC/PKCS5Padding";
	
	private int code = 0;
	
	public DES() {
	}

	/**
	 * 构造函数
	 * @param code 加密方式:0-“ISO-8859-1”编码,1-base64编码,其它-默认编码(utf-8)
	 */
	public DES(int code) {
		this.code = code;
	}

	/**
	 * 将字符串进行DES加密
	 * @param source 未加密源字符串
	 * @return 加密后字符串
	 */
	public String encrypt(String source)  {
		byte[] retByte = null;

		// Create SecretKey object
		DESKeySpec dks = null;
		try {
			dks = new DESKeySpec(KEY);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			SecretKey securekey = keyFactory.generateSecret(dks);

			// Create IvParameterSpec object with initialization vector
			IvParameterSpec spec = new IvParameterSpec(IV);

			// Create Cipter object
			Cipher cipher = Cipher.getInstance(TRANSFORMATION);

			// Initialize Cipher object
			cipher.init(Cipher.ENCRYPT_MODE, securekey, spec);

			// Decrypting data
			retByte = cipher.doFinal(source.getBytes());

			String result = "";
			if (code == 0) {
				result = new String(retByte, "ISO-8859-1");
			} else if (code == 1) {
				result = Base64.encodeToString(retByte,false);
			} else {
				result = new String(retByte);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 将DES加密的字符串解密
	 * @param encrypted 加密过的字符串
	 * @return 未加密源字符串
	 */
	public String decrypt(String encrypted) {
		byte[] retByte = null;

		// Create SecretKey object
		DESKeySpec dks = null;
		try {
			dks = new DESKeySpec(KEY);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
			SecretKey securekey = keyFactory.generateSecret(dks);

			// Create IvParameterSpec object with initialization vector
			IvParameterSpec spec = new IvParameterSpec(IV);

			// Create Cipter object
			Cipher cipher = Cipher.getInstance(TRANSFORMATION);

			// Initialize Cipher object
			cipher.init(Cipher.DECRYPT_MODE, securekey, spec);

			if (code == 0) {
				retByte = encrypted.getBytes("ISO-8859-1");
			} else if (code == 1) {
				retByte = Base64.decode(encrypted);
			} else {
				retByte = encrypted.getBytes();
			}

			// Decrypting data
			retByte = cipher.doFinal(retByte);
			return new String(retByte, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
	
}
ArrayUtils.java
/*
 * Copyright (C) 2013 Peng fei Pan 
 
  
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.lazylibrary.util;

import java.util.Stack;

/**
 * 
  

数组工具类,提供一些有关数组的便捷方法

* *
1、增删移动相关 *
    (1.01)、以无损的方式,将数组objects的元素从索引headIndex处开始到endIndex索引处结束的元素,向后移动number位:static * void backwardByLossless(Object[] objects, int headIndex, int endIndex, int * number) *
    (1.02)、以无损的方式,将数组objects的元素从索引headIndex处开始到endIndex索引处结束的元素,向前移动number位:static * void forwardByLossless(Object[] objects, int headIndex, int endIndex, int * number) *
    (1.03)、以有损的方式,将数组objects的元素从索引headIndex处开始到endIndex索引处结束的元素,向后移动number位:static * void backwardLoss(Object[] objects, int headIndex, int endIndex, int number) *
    (1.04)、以有损的方式,将数组objects的元素从索引headIndex处开始到endIndex索引处结束的元素,向前移动number位:static * void forwardLoss(Object[] objects, int headIndex, int endIndex, int number) *
    (1.05)、以有损的方式在数组objects的索引insertToIndex处插入元素element:static * void insert(Object[] objects, int insertToIndex, Object element) *
    (1.06)、将数组objects中索引removeIndex出的元素删除:static * Object remove(Object[] objects, int removeIndex) *
    (1.07)、返回数组objects的字符串表示形式:static String * toString(Object[] objects) *
    (1.08)、在数组哦objects中搜索元素element:static int * search(Object[] objects, Object element) *
    (1.09)、将数组objects中索引setIndex出的元素用element替换:static * Object set(Object[] objects, Object element, int setIndex) *
*
2、Int数组排序相关 *
    (2.01)、使用选择排序法,对数组intArray进行排序:static void * SortingByChoose(int[] intArray, int type) *
    (2.02)、使用插入排序法,对数组intArray进行排序:static void * SortingByInsert(int[] intArray, int type) *
    (2.03)、使用冒泡排序法,对数组intArray进行排序:static void * SortingByBubbling(int[] intArray, int type) *
    (2.04)、使用递归快排法,对数组intArray进行排序:static void * SortingByFastRecursion(int[] intArray, int start, int end, int type) *
    (2.05)、使用栈快排法,对数组intArray进行排序:static void * SortingByFastStack(int[] intArray, int type) */ public class ArrayUtils { /** * (1.08)、在数组objects中搜索元素element * * @param objects 待操作的数组 * @param element 待匹配的元素 * @return 索引,如不存在,-1 */ public static int search(Object[] objects, Object element) { int e = -1; for (int w = 0; w < objects.length; w++) { if (!element.equals(objects[w])) { continue; } else { e = w; break; } } return e; } /* **************************************************************1、增删移动相关over************************************************************ */ /* **************************************************************2、Int数组排序相关start************************************************************ */ /** * (2.01)、使用选择排序法,对数组intArray进行排序 * * @param intArray 待排序的数组 * @param ascending 升序 */ public static void sortingByChoose(int[] intArray, boolean ascending) { for (int cankaozhi = 0; cankaozhi < intArray.length - 1; cankaozhi++) { int zhongjian = intArray[cankaozhi]; int zuixiao = 0; for (int zujian = cankaozhi + 1; zujian <= intArray.length - 1; zujian++) { boolean typee = true; if (ascending) { typee = zhongjian > intArray[zujian]; } else { typee = zhongjian < intArray[zujian]; } if (typee) { zhongjian = intArray[zujian]; zuixiao = zujian; } } if (zuixiao != 0) { int f = intArray[zuixiao]; intArray[zuixiao] = intArray[cankaozhi]; intArray[cankaozhi] = f; } } } /** * (2.02)、使用插入排序法,对数组intArray进行排序 * * @param intArray 待排序的数组 * @param ascending 升序 */ public static void sortingByInsert(int[] intArray, boolean ascending) { for (int i = 1; i < intArray.length; i++) { int t = intArray[i]; int y = -1; for (int j = i - 1; j >= 0; j--) { boolean typee = true; if (ascending) { typee = t < intArray[j]; } else { typee = t > intArray[j]; } if (!typee) break; intArray[j + 1] = intArray[j]; y = j; } if (y > -1) intArray[y] = t; } } /** * (2.03)、使用冒泡排序法,对数组intArray进行排序 * * @param intArray 待排序的数组 * @param ascending 升序 */ public static void sortingByBubbling(int[] intArray, boolean ascending) { for (int e = 0; e < intArray.length - 1; e++) { for (int r = 0; r < intArray.length - 1; r++) { boolean typee = true; if (ascending) { typee = intArray[r] > intArray[r + 1]; } else { typee = intArray[r] < intArray[r + 1]; } if (typee) { int t = intArray[r]; intArray[r] = intArray[r + 1]; intArray[r + 1] = t; } } } } /** * (2.04)、使用递归快排法,对数组intArray进行排序 * * @param intArray 待排序的数组 * @param ascending 排序的方式,用本类中的静态字段指定 */ public static void sortingByFastRecursion(int[] intArray, int start, int end, boolean ascending) { int tmp = intArray[start]; int i = start; if (ascending) { for (int j = end; i < j; ) { while (intArray[j] > tmp && i < j) { j--; } if (i < j) { intArray[i] = intArray[j]; i++; } for (; intArray[i] < tmp && i < j; i++) { ; } if (i < j) { intArray[j] = intArray[i]; j--; } } } else { for (int j = end; i < j; ) { while (intArray[j] < tmp && i < j) { j--; } if (i < j) { intArray[i] = intArray[j]; i++; } for (; intArray[i] > tmp && i < j; i++) { ; } if (i < j) { intArray[j] = intArray[i]; j--; } } } intArray[i] = tmp; if (start < i - 1) { sortingByFastRecursion(intArray, start, i - 1, ascending); } if (end > i + 1) { sortingByFastRecursion(intArray, i + 1, end, ascending); } } /** * (2.05)、使用栈快排法,对数组intArray进行排序 * * @param intArray 待排序的数组 * @param ascending 升序 */ public static void sortingByFastStack(int[] intArray, boolean ascending) { Stack sa = new Stack (); sa.push(0); sa.push(intArray.length - 1); while (!sa.isEmpty()) { int end = ((Integer) sa.pop()).intValue(); int start = ((Integer) sa.pop()).intValue(); int i = start; int j = end; int tmp = intArray[i]; if (ascending) { while (i < j) { while (intArray[j] > tmp && i < j) { j--; } if (i < j) { intArray[i] = intArray[j]; i++; } for (; intArray[i] < tmp && i < j; i++) { ; } if (i < j) { intArray[j] = intArray[i]; j--; } } } else { while (i < j) { while (intArray[j] < tmp && i < j) { j--; } if (i < j) { intArray[i] = intArray[j]; i++; } for (; intArray[i] > tmp && i < j; i++) { ; } if (i < j) { intArray[j] = intArray[i]; j--; } } } intArray[i] = tmp; if (start < i - 1) { sa.push(Integer.valueOf(start)); sa.push(Integer.valueOf(i - 1)); } if (end > i + 1) { sa.push(Integer.valueOf(i + 1)); sa.push(Integer.valueOf(end)); } } } /* **************************************************************2、Int数组排序相关over************************************************************ */ /** * 将数组颠倒 */ public static Object[] upsideDown(Object[] objects) { int length = objects.length; Object tem; for (int w = 0; w < length / 2; w++) { tem = objects[w]; objects[w] = objects[length - 1 - w]; objects[length - 1 - w] = tem; tem = null; } return objects; } /** * Inteher数组转换成int数组 */ public static int[] integersToInts(Integer[] integers) { int[] ints = new int[integers.length]; for (int w = 0; w < integers.length; w++) { ints[w] = integers[w]; } return ints; } /** * 将给定的数组转换成字符串 * * @param integers 给定的数组 * @param startSymbols 开始符号 * @param separator 分隔符 * @param endSymbols 结束符号 * @return 例如开始符号为"{",分隔符为", ",结束符号为"}",那么结果为:{1, 2, 3} */ public static String toString(int[] integers, String startSymbols, String separator, String endSymbols) { boolean addSeparator = false; StringBuffer sb = new StringBuffer(); //如果开始符号不为null且不空 if (StringUtils.isNotEmpty(startSymbols)) { sb.append(startSymbols); } //循环所有的对象 for (int object : integers) { //如果需要添加分隔符 if (addSeparator) { sb.append(separator); addSeparator = false; } sb.append(object); addSeparator = true; } //如果结束符号不为null且不空 if (StringUtils.isNotEmpty(endSymbols)) { sb.append(endSymbols); } return sb.toString(); } /** * 将给定的数组转换成字符串 * * @param integers 给定的数组 * @param separator 分隔符 * @return 例如分隔符为", "那么结果为:1, 2, 3 */ public static String toString(int[] integers, String separator) { return toString(integers, null, separator, null); } /** * 将给定的数组转换成字符串,默认分隔符为", " * * @param integers 给定的数组 * @return 例如:1, 2, 3 */ public static String toString(int[] integers) { return toString(integers, null, ", ", null); } /** * 将给定的数组转换成字符串 * * @param objects 给定的数组 * @param startSymbols 开始符号 * @param separator 分隔符 * @param endSymbols 结束符号 * @return 例如开始符号为"{",分隔符为", ",结束符号为"}",那么结果为:{1, 2, 3} */ public static String toString(Object[] objects, String startSymbols, String separator, String endSymbols) { boolean addSeparator = false; StringBuffer sb = new StringBuffer(); //如果开始符号不为null且不空 if (StringUtils.isNotEmpty(startSymbols)) { sb.append(startSymbols); } //循环所有的对象 for (Object object : objects) { //如果需要添加分隔符 if (addSeparator) { sb.append(separator); addSeparator = false; } sb.append(object); addSeparator = true; } //如果结束符号不为null且不空 if (StringUtils.isNotEmpty(endSymbols)) { sb.append(endSymbols); } return sb.toString(); } /** * 将给定的数组转换成字符串 * * @param objects 给定的数组 * @param separator 分隔符 * @return 例如分隔符为", "那么结果为:1, 2, 3 */ public static String toString(Object[] objects, String separator) { return toString(objects, null, separator, null); } /** * 将给定的数组转换成字符串,默认分隔符为", " * * @param objects 给定的数组 * @return 例如:1, 2, 3 */ public static String toString(Object[] objects) { return toString(objects, null, ", ", null); } }
BadgeUtil.java
package com.github.lazylibrary.util;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BadgeUtil {
    /**
     * 设置Badge 目前支持Launcher:
     * MIUI
     * Sony
     * Samsung
     * LG
     * HTC
     * Nova 需要这些权限
     * @param context context
     * @param count   count
     * @param icon    icon应用的图标
     */
  /*  
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 
    
 */
    public static void setBadgeCount(Context context, int count,int icon) {

        // TODO 生成器模式重构
        if (count <= 0) {
            count = 0;
        } else {
            count = Math.max(0, Math.min(count, 99));
        }
        if (Build.MANUFACTURER.equalsIgnoreCase("xiaomi")) {
            setBadgeOfMIUI(context, count,icon);
        } else if (Build.MANUFACTURER.equalsIgnoreCase("sony")) {
            setBadgeOfSony(context, count);
        } else if (Build.MANUFACTURER.toLowerCase().contains("samsung") ||
                Build.MANUFACTURER.toLowerCase().contains("lg")) {
            setBadgeOfSumsung(context, count);
        } else if (Build.MANUFACTURER.toLowerCase().contains("htc")) {
            setBadgeOfHTC(context, count);
        } else if (Build.MANUFACTURER.toLowerCase().contains("nova")) {
            setBadgeOfNova(context, count);
        } else {
            Toast.makeText(context, "Not Found Support Launcher", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 设置MIUI的Badge
     *
     * @param context context
     * @param count   count
     * @param icon    icon
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private static void setBadgeOfMIUI(Context context, int count, int icon) {

        Log.d("xys", "Launcher : MIUI");
        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(context)
                .setContentTitle("title").setContentText("text").setSmallIcon(icon);
        Notification notification = builder.build();
        try {
            Field field = notification.getClass().getDeclaredField("extraNotification");
            Object extraNotification = field.get(notification);
            Method method = extraNotification.getClass().getDeclaredMethod("setMessageCount", int.class);
            method.invoke(extraNotification, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mNotificationManager.notify(0, notification);
    }

    /**
     * 设置索尼的Badge
     * 

* 需添加权限: * * @param context context * @param count count */ private static void setBadgeOfSony(Context context, int count) { String launcherClassName = AppInfoUtil.getLauncherClassName(context); if (launcherClassName == null) { return; } boolean isShow = true; if (count == 0) { isShow = false; } Intent localIntent = new Intent(); localIntent.setAction("com.sonyericsson.home.action.UPDATE_BADGE"); localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", isShow);//是否显示 localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);//启动页 localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String .valueOf(count));//数字 localIntent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());//包名 context.sendBroadcast(localIntent); } /** * 设置三星的Badge\设置LG的Badge * * @param context context * @param count count */ private static void setBadgeOfSumsung(Context context, int count) { // 获取你当前的应用 String launcherClassName = AppInfoUtil.getLauncherClassName(context); if (launcherClassName == null) { return; } Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE"); intent.putExtra("badge_count", count); intent.putExtra("badge_count_package_name", context.getPackageName()); intent.putExtra("badge_count_class_name", launcherClassName); context.sendBroadcast(intent); } /** * 设置HTC的Badge * * @param context context * @param count count */ private static void setBadgeOfHTC(Context context, int count) { Intent intentNotification = new Intent("com.htc.launcher.action.SET_NOTIFICATION"); ComponentName localComponentName = new ComponentName(context.getPackageName(), AppInfoUtil.getLauncherClassName(context)); intentNotification.putExtra("com.htc.launcher.extra.COMPONENT", localComponentName.flattenToShortString()); intentNotification.putExtra("com.htc.launcher.extra.COUNT", count); context.sendBroadcast(intentNotification); Intent intentShortcut = new Intent("com.htc.launcher.action.UPDATE_SHORTCUT"); intentShortcut.putExtra("packagename", context.getPackageName()); intentShortcut.putExtra("count", count); context.sendBroadcast(intentShortcut); } /** * 设置Nova的Badge * * @param context context * @param count count */ private static void setBadgeOfNova(Context context, int count) { ContentValues contentValues = new ContentValues(); contentValues.put("tag", context.getPackageName() + "/" + AppInfoUtil.getLauncherClassName(context)); contentValues.put("count", count); context.getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), contentValues); } public static void setBadgeOfMadMode(Context context, int count, String packageName, String className) { Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE"); intent.putExtra("badge_count", count); intent.putExtra("badge_count_package_name", packageName); intent.putExtra("badge_count_class_name", className); context.sendBroadcast(intent); } /** * 重置Badge * * @param context context * @param icon icon */ public static void resetBadgeCount(Context context,int icon) { setBadgeCount(context, 0,icon); } }
Base64.java
package com.github.lazylibrary.util;

import java.util.Arrays;

public class Base64 {
	private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
	private static final int[] IA = new int[256];
	static {
		Arrays.fill(IA, -1);
		for (int i = 0, iS = CA.length; i < iS; i++)
			IA[CA[i]] = i;
		IA['='] = 0;
	}
	private static final byte[] encodingTable = { (byte) 'A', (byte) 'B',
			(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
			(byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
			(byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q',
			(byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V',
			(byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a',
			(byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
			(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k',
			(byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
			(byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
			(byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
			(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
			(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
			(byte) '+', (byte) '/' };
	private static final byte[] decodingTable;
	static {
		decodingTable = new byte[128];
		for (int i = 0; i < 128; i++) {
			decodingTable[i] = (byte) -1;
		}
		for (int i = 'A'; i <= 'Z'; i++) {
			decodingTable[i] = (byte) (i - 'A');
		}
		for (int i = 'a'; i <= 'z'; i++) {
			decodingTable[i] = (byte) (i - 'a' + 26);
		}
		for (int i = '0'; i <= '9'; i++) {
			decodingTable[i] = (byte) (i - '0' + 52);
		}
		decodingTable['+'] = 62;
		decodingTable['/'] = 63;
	}

	public static byte[] encode(byte[] data) {
		byte[] bytes;
		int modulus = data.length % 3;
		if (modulus == 0) {
			bytes = new byte[(4 * data.length) / 3];
		} else {
			bytes = new byte[4 * ((data.length / 3) + 1)];
		}
		int dataLength = (data.length - modulus);
		int a1;
		int a2;
		int a3;
		for (int i = 0, j = 0; i < dataLength; i += 3, j += 4) {
			a1 = data[i] & 0xff;
			a2 = data[i + 1] & 0xff;
			a3 = data[i + 2] & 0xff;
			bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];
			bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];
			bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];
			bytes[j + 3] = encodingTable[a3 & 0x3f];
		}
		int b1;
		int b2;
		int b3;
		int d1;
		int d2;
		switch (modulus) {
		case 0: /* nothing left to do */
			break;
		case 1:
			d1 = data[data.length - 1] & 0xff;
			b1 = (d1 >>> 2) & 0x3f;
			b2 = (d1 << 4) & 0x3f;
			bytes[bytes.length - 4] = encodingTable[b1];
			bytes[bytes.length - 3] = encodingTable[b2];
			bytes[bytes.length - 2] = (byte) '=';
			bytes[bytes.length - 1] = (byte) '=';
			break;
		case 2:
			d1 = data[data.length - 2] & 0xff;
			d2 = data[data.length - 1] & 0xff;
			b1 = (d1 >>> 2) & 0x3f;
			b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
			b3 = (d2 << 2) & 0x3f;
			bytes[bytes.length - 4] = encodingTable[b1];
			bytes[bytes.length - 3] = encodingTable[b2];
			bytes[bytes.length - 2] = encodingTable[b3];
			bytes[bytes.length - 1] = (byte) '=';
			break;
		}
		return bytes;
	}

	public static byte[] decode(byte[] data) {
		byte[] bytes;
		byte b1;
		byte b2;
		byte b3;
		byte b4;
		data = discardNonBase64Bytes(data);
		if (data[data.length - 2] == '=') {
			bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
		} else if (data[data.length - 1] == '=') {
			bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
		} else {
			bytes = new byte[((data.length / 4) * 3)];
		}
		for (int i = 0, j = 0; i < (data.length - 4); i += 4, j += 3) {
			b1 = decodingTable[data[i]];
			b2 = decodingTable[data[i + 1]];
			b3 = decodingTable[data[i + 2]];
			b4 = decodingTable[data[i + 3]];
			bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[j + 2] = (byte) ((b3 << 6) | b4);
		}
		if (data[data.length - 2] == '=') {
			b1 = decodingTable[data[data.length - 4]];
			b2 = decodingTable[data[data.length - 3]];
			bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
		} else if (data[data.length - 1] == '=') {
			b1 = decodingTable[data[data.length - 4]];
			b2 = decodingTable[data[data.length - 3]];
			b3 = decodingTable[data[data.length - 2]];
			bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
		} else {
			b1 = decodingTable[data[data.length - 4]];
			b2 = decodingTable[data[data.length - 3]];
			b3 = decodingTable[data[data.length - 2]];
			b4 = decodingTable[data[data.length - 1]];
			bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
		}
		return bytes;
	}

	public static byte[] decode(String data) {
		byte[] bytes;
		byte b1;
		byte b2;
		byte b3;
		byte b4;
		data = discardNonBase64Chars(data);
		if (data.charAt(data.length() - 2) == '=') {
			bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
		} else if (data.charAt(data.length() - 1) == '=') {
			bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
		} else {
			bytes = new byte[((data.length() / 4) * 3)];
		}
		for (int i = 0, j = 0; i < (data.length() - 4); i += 4, j += 3) {
			b1 = decodingTable[data.charAt(i)];
			b2 = decodingTable[data.charAt(i + 1)];
			b3 = decodingTable[data.charAt(i + 2)];
			b4 = decodingTable[data.charAt(i + 3)];
			bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[j + 2] = (byte) ((b3 << 6) | b4);
		}
		if (data.charAt(data.length() - 2) == '=') {
			b1 = decodingTable[data.charAt(data.length() - 4)];
			b2 = decodingTable[data.charAt(data.length() - 3)];
			bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
		} else if (data.charAt(data.length() - 1) == '=') {
			b1 = decodingTable[data.charAt(data.length() - 4)];
			b2 = decodingTable[data.charAt(data.length() - 3)];
			b3 = decodingTable[data.charAt(data.length() - 2)];
			bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
		} else {
			b1 = decodingTable[data.charAt(data.length() - 4)];
			b2 = decodingTable[data.charAt(data.length() - 3)];
			b3 = decodingTable[data.charAt(data.length() - 2)];
			b4 = decodingTable[data.charAt(data.length() - 1)];
			bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
			bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
			bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
		}
		return bytes;
	}

	private static byte[] discardNonBase64Bytes(byte[] data) {
		byte[] temp = new byte[data.length];
		int bytesCopied = 0;
		for (int i = 0; i < data.length; i++) {
			if (isValidBase64Byte(data[i])) {
				temp[bytesCopied++] = data[i];
			}
		}
		byte[] newData = new byte[bytesCopied];
		System.arraycopy(temp, 0, newData, 0, bytesCopied);
		return newData;
	}

	private static String discardNonBase64Chars(String data) {
		StringBuffer sb = new StringBuffer();
		int length = data.length();
		for (int i = 0; i < length; i++) {
			if (isValidBase64Byte((byte) (data.charAt(i)))) {
				sb.append(data.charAt(i));
			}
		}
		return sb.toString();
	}

	private static boolean isValidBase64Byte(byte b) {
		if (b == '=') {
			return true;
		} else if ((b < 0) || (b >= 128)) {
			return false;
		} else if (decodingTable[b] == -1) {
			return false;
		}
		return true;
	}

	/** Encodes a raw byte array into a BASE64  representation i accordance with RFC 2045.
	 * @param sArr The bytes to convert. If  or length 0 an empty array will be returned.
	 * @param lineSep Optional "\r\n" after 76 characters, unless end of file.
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a * little faster. * @return A BASE64 encoded array. Never . */ public final static String encodeToString(byte[] sArr, boolean lineSep) { // Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower. return new String(encodeToChar(sArr, lineSep)); } /** Encodes a raw byte array into a BASE64 representation i accordance with RFC 2045. * @param sArr The bytes to convert. If or length 0 an empty array will be returned. * @param lineSep Optional "\r\n" after 76 characters, unless end of file.
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a * little faster. * @return A BASE64 encoded array. Never . */ public final static char[] encodeToChar(byte[] sArr, boolean lineSep) { // Check special case int sLen = sArr != null ? sArr.length : 0; if (sLen == 0) return new char[0]; int eLen = (sLen / 3) * 3; // Length of even 24-bits. int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array char[] dArr = new char[dLen]; // Encode even 24-bits for (int s = 0, d = 0, cc = 0; s < eLen;) { // Copy next three bytes into lower 24 bits of int, paying attension to sign. int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff); // Encode the int into four chars dArr[d++] = CA[(i >>> 18) & 0x3f]; dArr[d++] = CA[(i >>> 12) & 0x3f]; dArr[d++] = CA[(i >>> 6) & 0x3f]; dArr[d++] = CA[i & 0x3f]; // Add optional line separator if (lineSep && ++cc == 19 && d < dLen - 2) { dArr[d++] = '\r'; dArr[d++] = '\n'; cc = 0; } } // Pad and encode last bits if source isn't even 24 bits. int left = sLen - eLen; // 0 - 2. if (left > 0) { // Prepare the int int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0); // Set last four chars dArr[dLen - 4] = CA[i >> 12]; dArr[dLen - 3] = CA[(i >>> 6) & 0x3f]; dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '='; dArr[dLen - 1] = '='; } return dArr; } }Stringnullnullchar[]nullnull
ByteUtils.java
/*
 * Copyright (C) 2013 Peng fei Pan 
 
  
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.lazylibrary.util;

/**
 * 
  

字节工具类,提供一些有关字节的便捷方法

* *
    (01)、位移加密:static void byteJiaMi(byte[] bytes) *
    (02)、从bytes上截取一段:static byte[] cutOut(byte[] bytes, int off, int length) */ public class ByteUtils { /** * (01)、位移加密 * @param bytes */ public static void byteJiaMi(byte[] bytes){ for (int w = 0; w < bytes.length; w++){ int a = bytes[w]; a = ~a; bytes[w] = (byte)a; } } /** * (02)、从bytes上截取一段 * @param bytes 母体 * @param off 起始 * @param length 个数 * @return byte[] */ public static byte[] cutOut(byte[] bytes, int off, int length){ byte[] bytess = new byte[length]; System.arraycopy(bytes, off, bytess, 0, length); return bytess; } /** * 将字节转换为二进制字符串 * @param bytes 字节数组 * @return 二进制字符串 */ public static String byteToBit(byte... bytes){ StringBuffer sb = new StringBuffer(); int z, len; String str; for(int w = 0; w < bytes.length ; w++){ z = bytes[w]; z |= 256; str = Integer.toBinaryString(z); len = str.length(); sb.append(str.substring(len-8, len)); } return sb.toString(); } /** * 字节数组转换成16进制字符串 * @param raw * @return */ public static String getHex(byte [] raw ) { String HEXES = "0123456789ABCDEF"; if ( raw == null ) { return null; } final StringBuilder hex = new StringBuilder( 2 * raw.length ); for ( final byte b : raw ) { hex.append(HEXES.charAt((b & 0xF0) >> 4)) .append(HEXES.charAt((b & 0x0F))); } return hex.toString(); } /** * 将一个short转换成字节数组 * @param sh short * @return 字节数组 */ public static byte[] valueOf(short sh){ byte[] shortBuf = new byte[2]; for(int i=0;i<2;i++) { int offset = (shortBuf.length - 1 -i)*8; shortBuf[i] = (byte)((sh>>>offset)&0xff); } return shortBuf; } /** * 将一个int转换成字节数组 * @param in int * @return 字节数组 */ public static byte[] valueOf(int in){ byte[] b = new byte[4]; for (int i = 0; i < 4; i++) { int offset = (b.length - 1 - i) * 8; b[i] = (byte) ((in >>> offset) & 0xFF); } return b; } }
ClassUtils.java
/*
 * Copyright 2011-2013 HTTL Team.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.lazylibrary.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * ClassUtils. (Tool, Static, ThreadSafe)
 *
 * @author Liang Fei (liangfei0201 AT gmail DOT com)
 */
public class ClassUtils {

    public static final String CLASS_EXTENSION = ".class";

    public static final String JAVA_EXTENSION = ".java";

    private static final ConcurrentMap
 
  , Map
  
   > GETTER_CACHE = new ConcurrentHashMap
   
    , Map
    
     >(); private static final ConcurrentMap
     
      > CLASS_CACHE = new ConcurrentHashMap
      
       >(); static { CLASS_CACHE.put("boolean", boolean.class); CLASS_CACHE.put("char", char.class); CLASS_CACHE.put("byte", byte.class); CLASS_CACHE.put("short", short.class); CLASS_CACHE.put("int", int.class); CLASS_CACHE.put("long", long.class); CLASS_CACHE.put("float", float.class); CLASS_CACHE.put("double", double.class); CLASS_CACHE.put("void", void.class); CLASS_CACHE.put("Boolean", Boolean.class); CLASS_CACHE.put("Character", Character.class); CLASS_CACHE.put("Byte", Byte.class); CLASS_CACHE.put("Short", Short.class); CLASS_CACHE.put("Integer", Integer.class); CLASS_CACHE.put("Long", Long.class); CLASS_CACHE.put("Float", Float.class); CLASS_CACHE.put("Double", Double.class); CLASS_CACHE.put("Number", Number.class); CLASS_CACHE.put("String", String.class); CLASS_CACHE.put("Object", Object.class); CLASS_CACHE.put("Class", Class.class); CLASS_CACHE.put("Void", Void.class); CLASS_CACHE.put("java.lang.Boolean", Boolean.class); CLASS_CACHE.put("java.lang.Character", Character.class); CLASS_CACHE.put("java.lang.Byte", Byte.class); CLASS_CACHE.put("java.lang.Short", Short.class); CLASS_CACHE.put("java.lang.Integer", Integer.class); CLASS_CACHE.put("java.lang.Long", Long.class); CLASS_CACHE.put("java.lang.Float", Float.class); CLASS_CACHE.put("java.lang.Double", Double.class); CLASS_CACHE.put("java.lang.Number", Number.class); CLASS_CACHE.put("java.lang.String", String.class); CLASS_CACHE.put("java.lang.Object", Object.class); CLASS_CACHE.put("java.lang.Class", Class.class); CLASS_CACHE.put("java.lang.Void", Void.class); CLASS_CACHE.put("java.util.Date", Date.class); CLASS_CACHE.put("boolean[]", boolean[].class); CLASS_CACHE.put("char[]", char[].class); CLASS_CACHE.put("byte[]", byte[].class); CLASS_CACHE.put("short[]", short[].class); CLASS_CACHE.put("int[]", int[].class); CLASS_CACHE.put("long[]", long[].class); CLASS_CACHE.put("float[]", float[].class); CLASS_CACHE.put("double[]", double[].class); CLASS_CACHE.put("Boolean[]", Boolean[].class); CLASS_CACHE.put("Character[]", Character[].class); CLASS_CACHE.put("Byte[]", Byte[].class); CLASS_CACHE.put("Short[]", Short[].class); CLASS_CACHE.put("Integer[]", Integer[].class); CLASS_CACHE.put("Long[]", Long[].class); CLASS_CACHE.put("Float[]", Float[].class); CLASS_CACHE.put("Double[]", Double[].class); CLASS_CACHE.put("Number[]", Number[].class); CLASS_CACHE.put("String[]", String[].class); CLASS_CACHE.put("Object[]", Object[].class); CLASS_CACHE.put("Class[]", Class[].class); CLASS_CACHE.put("Void[]", Void[].class); CLASS_CACHE.put("java.lang.Boolean[]", Boolean[].class); CLASS_CACHE.put("java.lang.Character[]", Character[].class); CLASS_CACHE.put("java.lang.Byte[]", Byte[].class); CLASS_CACHE.put("java.lang.Short[]", Short[].class); CLASS_CACHE.put("java.lang.Integer[]", Integer[].class); CLASS_CACHE.put("java.lang.Long[]", Long[].class); CLASS_CACHE.put("java.lang.Float[]", Float[].class); CLASS_CACHE.put("java.lang.Double[]", Double[].class); CLASS_CACHE.put("java.lang.Number[]", Number[].class); CLASS_CACHE.put("java.lang.String[]", String[].class); CLASS_CACHE.put("java.lang.Object[]", Object[].class); CLASS_CACHE.put("java.lang.Class[]", Class[].class); CLASS_CACHE.put("java.lang.Void[]", Void[].class); CLASS_CACHE.put("java.util.Date[]", Date[].class); } public static Object newInstance(String name) { try { return forName(name).newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new IllegalStateException(e.getMessage(), e); } } public static Class
        forName(String[] packages, String className) { // import class if (packages != null && packages.length > 0 && !className.contains(".") && !CLASS_CACHE.containsKey(className)) { for (String pkg : packages) { try { return _forName(pkg + "." + className); } catch (ClassNotFoundException e2) { } } try { return _forName("java.lang." + className); } catch (ClassNotFoundException e2) { } } try { return _forName(className); } catch (ClassNotFoundException e) { // inner class int i = className.lastIndexOf('.'); if (i > 0 && i < className.length() - 1) { try { return _forName(className.substring(0, i) + "$" + className.substring(i + 1)); } catch (ClassNotFoundException e2) { } } throw new IllegalStateException(e.getMessage(), e); } } public static Class
        forName(String className) { try { return _forName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException(e.getMessage(), e); } } private static Class
        _forName(String name) throws ClassNotFoundException { if (StringUtils.isEmpty(name)) return null; String key = name; Class
        clazz = CLASS_CACHE.get(key); if (clazz == null) { int index = name.indexOf('['); if (index > 0) { int i = (name.length() - index) / 2; name = name.substring(0, index); StringBuilder sb = new StringBuilder(); while (i-- > 0) { sb.append("["); // int[][] } if ("void".equals(name)) { sb.append("V"); } else if ("boolean".equals(name)) { sb.append("Z"); } else if ("byte".equals(name)) { sb.append("B"); } else if ("char".equals(name)) { sb.append("C"); } else if ("double".equals(name)) { sb.append("D"); } else if ("float".equals(name)) { sb.append("F"); } else if ("int".equals(name)) { sb.append("I"); } else if ("long".equals(name)) { sb.append("J"); } else if ("short".equals(name)) { sb.append("S"); } else { sb.append('L').append(name).append(';'); } name = sb.toString(); } try { clazz = Class.forName(name, true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException cne) { clazz = Class.forName(name); } Class
        old = CLASS_CACHE.putIfAbsent(key, clazz); if (old != null) { clazz = old; } } return clazz; } public static Class
        getUnboxedClass(Class
        type) { if (type == Boolean.class) { return boolean.class; } else if (type == Character.class) { return char.class; } else if (type == Byte.class) { return byte.class; } else if (type == Short.class) { return short.class; } else if (type == Integer.class) { return int.class; } else if (type == Long.class) { return long.class; } else if (type == Float.class) { return float.class; } else if (type == Double.class) { return double.class; } else { return type; } } public static Class
        getBoxedClass(Class
        type) { if (type == boolean.class) { return Boolean.class; } else if (type == char.class) { return Character.class; } else if (type == byte.class) { return Byte.class; } else if (type == short.class) { return Short.class; } else if (type == int.class) { return Integer.class; } else if (type == long.class) { return Long.class; } else if (type == float.class) { return Float.class; } else if (type == double.class) { return Double.class; } else { return type; } } public static Boolean boxed(boolean v) { return Boolean.valueOf(v); } public static Character boxed(char v) { return Character.valueOf(v); } public static Byte boxed(byte v) { return Byte.valueOf(v); } public static Short boxed(short v) { return Short.valueOf(v); } public static Integer boxed(int v) { return Integer.valueOf(v); } public static Long boxed(long v) { return Long.valueOf(v); } public static Float boxed(float v) { return Float.valueOf(v); } public static Double boxed(double v) { return Double.valueOf(v); } public static 
       
         T boxed(T v) { return v; } public static boolean unboxed(Boolean v) { return v == null ? false : v.booleanValue(); } public static char unboxed(Character v) { return v == null ? '\0' : v.charValue(); } public static byte unboxed(Byte v) { return v == null ? 0 : v.byteValue(); } public static short unboxed(Short v) { return v == null ? 0 : v.shortValue(); } public static int unboxed(Integer v) { return v == null ? 0 : v.intValue(); } public static long unboxed(Long v) { return v == null ? 0 : v.longValue(); } public static float unboxed(Float v) { return v == null ? 0 : v.floatValue(); } public static double unboxed(Double v) { return v == null ? 0 : v.doubleValue(); } public static 
        
          T unboxed(T v) { return v; } public static boolean isTrue(boolean object) { return object; } public static boolean isTrue(char object) { return object != '\0'; } public static boolean isTrue(byte object) { return object != (byte) 0; } public static boolean isTrue(short object) { return object != (short) 0; } public static boolean isTrue(int object) { return object != 0; } public static boolean isTrue(long object) { return object != 0l; } public static boolean isTrue(float object) { return object != 0f; } public static boolean isTrue(double object) { return object != 0d; } public static boolean isTrue(Object object) { if (object instanceof Boolean) { return ((Boolean) object).booleanValue(); } return getSize(object) != 0; } public static boolean isNotEmpty(Object object) { return isTrue(object); } public static int getSize(Object object) { if (object == null) { return 0; } else if (object instanceof Collection
         ) { return ((Collection
         ) object).size(); } else if (object instanceof Map
         ) { return ((Map
         ) object).size(); } else if (object instanceof Object[]) { return ((Object[]) object).length; } else if (object instanceof int[]) { return ((int[]) object).length; } else if (object instanceof long[]) { return ((long[]) object).length; } else if (object instanceof float[]) { return ((float[]) object).length; } else if (object instanceof double[]) { return ((double[]) object).length; } else if (object instanceof short[]) { return ((short[]) object).length; } else if (object instanceof byte[]) { return ((byte[]) object).length; } else if (object instanceof char[]) { return ((char[]) object).length; } else if (object instanceof boolean[]) { return ((boolean[]) object).length; } else { return -1; } } public static URI toURI(String name) { try { return new URI(name); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public static String getMethodFullName(String name, Class
         [] parameterTypes) { StringBuilder buf = new StringBuilder(); buf.append(name); buf.append("("); if (parameterTypes != null && parameterTypes.length > 0) { boolean first = true; for (Class
          type : parameterTypes) { if (type != null) { if (first) { first = false; } else { buf.append(","); } buf.append(type.getCanonicalName()); } } } buf.append(")"); return buf.toString(); } public static Class
          getGenericClass(Class
          cls) { return getGenericClass(cls, 0); } public static Class
          getGenericClass(Class
          cls, int i) { try { ParameterizedType parameterizedType; if (cls.getGenericInterfaces().length > 0 && cls.getGenericInterfaces()[0] instanceof ParameterizedType) { parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]); } else if (cls.getGenericSuperclass() instanceof ParameterizedType) { parameterizedType = (ParameterizedType) cls.getGenericSuperclass(); } else { parameterizedType = null; } if (parameterizedType != null) { Object genericClass = parameterizedType.getActualTypeArguments()[i]; if (genericClass instanceof ParameterizedType) { // 处理多级泛型 return (Class
         ) ((ParameterizedType) genericClass).getRawType(); } else if (genericClass instanceof GenericArrayType) { // 处理数组泛型 Class
          componentType = (Class
         ) ((GenericArrayType) genericClass).getGenericComponentType(); if (componentType.isArray()) { return componentType; } else { return Array.newInstance(componentType, 0).getClass(); } } else if (genericClass instanceof Class) { return (Class
         ) genericClass; } } } catch (Exception e) { } if (cls.getSuperclass() != null && cls.getSuperclass() != Object.class) { return getGenericClass(cls.getSuperclass(), i); } else { throw new IllegalArgumentException( cls.getName() + " generic type undefined!"); } } public static String getJavaVersion() { return System.getProperty("java.specification.version"); } public static boolean isBeforeJava5(String javaVersion) { return (StringUtils.isEmpty(javaVersion) || "1.0".equals(javaVersion) || "1.1".equals(javaVersion) || "1.2".equals(javaVersion) || "1.3".equals(javaVersion) || "1.4".equals(javaVersion)); } public static boolean isBeforeJava6(String javaVersion) { return isBeforeJava5(javaVersion) || "1.5".equals(javaVersion); } public static String toString(Throwable e) { StringWriter w = new StringWriter(); PrintWriter p = new PrintWriter(w); p.print(e.getClass().getName() + ": "); if (e.getMessage() != null) { p.print(e.getMessage() + "\n"); } p.println(); try { e.printStackTrace(p); return w.toString(); } finally { p.close(); } } private static final int JIT_LIMIT = 5 * 1024; public static void checkBytecode(String name, byte[] bytecode) { if (bytecode.length > JIT_LIMIT) { System.err.println( "The template bytecode too long, may be affect the JIT compiler. template class: " + name); } } public static String getSizeMethod(Class
          cls, String[] sizers) { for (String sizer : sizers) { try { return cls.getMethod(sizer, new Class
         [0]).getName() + "()"; } catch (NoSuchMethodException e) { } } return null; } public static String getMethodName(Method method, Class
         [] parameterClasses, String rightCode) { if (method.getParameterTypes().length > parameterClasses.length) { Class
         [] types = method.getParameterTypes(); StringBuilder buf = new StringBuilder(rightCode); for (int i = parameterClasses.length; i < types.length; i++) { if (buf.length() > 0) { buf.append(","); } Class
          type = types[i]; String def; if (type == boolean.class) { def = "false"; } else if (type == char.class) { def = "\'\\0\'"; } else if (type == byte.class || type == short.class || type == int.class || type == long.class || type == float.class || type == double.class) { def = "0"; } else { def = "null"; } buf.append(def); } } return method.getName() + "(" + rightCode + ")"; } @SuppressWarnings("unchecked") public static Object searchProperty(Object leftParameter, String name) throws Exception { Class
          leftClass = leftParameter.getClass(); Object result; if (leftParameter.getClass().isArray() && "length".equals(name)) { result = Array.getLength(leftParameter); } else if (leftParameter instanceof Map) { result = ((Map
         
          ) leftParameter).get(name); } else { try { String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); Method method = leftClass.getMethod(getter, new Class
          [0]); if (!method.isAccessible()) { method.setAccessible(true); } result = method.invoke(leftParameter, new Object[0]); } catch (NoSuchMethodException e2) { try { String getter = "is" + name.substring(0, 1).toUpperCase() + name.substring(1); Method method = leftClass.getMethod(getter, new Class
          [0]); if (!method.isAccessible()) { method.setAccessible(true); } result = method.invoke(leftParameter, new Object[0]); } catch (NoSuchMethodException e3) { Field field = leftClass.getField(name); result = field.get(leftParameter); } } } return result; } public static Method searchMethod(Class
           currentClass, String name, Class
          [] parameterTypes) throws NoSuchMethodException { return searchMethod(currentClass, name, parameterTypes, false); } public static Method searchMethod(Class
           currentClass, String name, Class
          [] parameterTypes, boolean boxed) throws NoSuchMethodException { if (currentClass == null) { throw new NoSuchMethodException("class == null"); } try { return currentClass.getMethod(name, parameterTypes); } catch (NoSuchMethodException e) { Method likeMethod = null; for (Method method : currentClass.getMethods()) { if (method.getName().equals(name) && parameterTypes.length == method.getParameterTypes().length && Modifier.isPublic(method.getModifiers())) { if (parameterTypes.length > 0) { Class
          [] types = method.getParameterTypes(); boolean eq = true; boolean like = true; for (int i = 0; i < parameterTypes.length; i++) { Class
           type = types[i]; Class
           parameterType = parameterTypes[i]; if (type != null && parameterType != null && !type.equals(parameterType)) { eq = false; if (boxed) { type = ClassUtils.getBoxedClass(type); parameterType = ClassUtils.getBoxedClass( parameterType); } if (!type.isAssignableFrom(parameterType)) { eq = false; like = false; break; } } } if (!eq) { if (like && (likeMethod == null || likeMethod.getParameterTypes()[0].isAssignableFrom( method.getParameterTypes()[0]))) { likeMethod = method; } continue; } } return method; } } if (likeMethod != null) { return likeMethod; } throw e; } } public static String getInitCode(Class
           type) { if (byte.class.equals(type) || short.class.equals(type) || int.class.equals(type) || long.class.equals(type) || float.class.equals(type) || double.class.equals(type)) { return "0"; } else if (char.class.equals(type)) { return "'\\0'"; } else if (boolean.class.equals(type)) { return "false"; } else { return "null"; } } public static String getInitCodeWithType(Class
           type) { if (byte.class.equals(type)) { return "(byte) 0"; } else if (short.class.equals(type)) { return "(short) 0"; } else if (int.class.equals(type)) { return "0"; } else if (long.class.equals(type)) { return "0l"; } else if (float.class.equals(type)) { return "0f"; } else if (double.class.equals(type)) { return "0d"; } else if (char.class.equals(type)) { return "'\\0'"; } else if (boolean.class.equals(type)) { return "false"; } else { return "(" + type.getCanonicalName() + ") null"; } } public static boolean toBoolean(Object value) { if (value instanceof Boolean) { return (Boolean) value; } return value == null ? false : toBoolean(String.valueOf(value)); } public static char toChar(Object value) { if (value instanceof Character) { return (Character) value; } return value == null ? '\0' : toChar(String.valueOf(value)); } public static byte toByte(Object value) { if (value instanceof Number) { return ((Number) value).byteValue(); } return value == null ? 0 : toByte(String.valueOf(value)); } public static short toShort(Object value) { if (value instanceof Number) { return ((Number) value).shortValue(); } return value == null ? 0 : toShort(String.valueOf(value)); } public static int toInt(Object value) { if (value instanceof Number) { return ((Number) value).intValue(); } return value == null ? 0 : toInt(String.valueOf(value)); } public static long toLong(Object value) { if (value instanceof Number) { return ((Number) value).longValue(); } return value == null ? 0 : toLong(String.valueOf(value)); } public static float toFloat(Object value) { if (value instanceof Number) { return ((Number) value).floatValue(); } return value == null ? 0 : toFloat(String.valueOf(value)); } public static double toDouble(Object value) { if (value instanceof Number) { return ((Number) value).doubleValue(); } return value == null ? 0 : toDouble(String.valueOf(value)); } public static Class
           toClass(Object value) { if (value instanceof Class) { return (Class
          ) value; } return value == null ? null : toClass(String.valueOf(value)); } public static boolean toBoolean(String value) { return StringUtils.isEmpty(value) ? false : Boolean.parseBoolean(value); } public static char toChar(String value) { return StringUtils.isEmpty(value) ? '\0' : value.charAt(0); } public static byte toByte(String value) { return StringUtils.isEmpty(value) ? 0 : Byte.parseByte(value); } public static short toShort(String value) { return StringUtils.isEmpty(value) ? 0 : Short.parseShort(value); } public static int toInt(String value) { return StringUtils.isEmpty(value) ? 0 : Integer.parseInt(value); } public static long toLong(String value) { return StringUtils.isEmpty(value) ? 0 : Long.parseLong(value); } public static float toFloat(String value) { return StringUtils.isEmpty(value) ? 0 : Float.parseFloat(value); } public static double toDouble(String value) { return StringUtils.isEmpty(value) ? 0 : Double.parseDouble(value); } public static Class
           toClass(String value) { return StringUtils.isEmpty(value) ? null : ClassUtils.forName(value); } public static Method getGetter(Object bean, String property) { Map
          
            cache = GETTER_CACHE.get(bean.getClass()); if (cache == null) { cache = new ConcurrentHashMap
           
            (); for (Method method : bean.getClass().getMethods()) { if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && !void.class.equals(method.getReturnType()) && method.getParameterTypes().length == 0) { String name = method.getName(); if (name.length() > 3 && name.startsWith("get")) { cache.put(name.substring(3, 4).toLowerCase() + name.substring(4), method); } else if (name.length() > 2 && name.startsWith("is")) { cache.put(name.substring(2, 3).toLowerCase() + name.substring(3), method); } } } Map
            
              old = GETTER_CACHE.putIfAbsent(bean.getClass(), cache); if (old != null) { cache = old; } } return cache.get(property); } public static Object getProperty(Object bean, String property) { if (bean == null || StringUtils.isEmpty(property)) { return null; } try { Method getter = getGetter(bean, property); if (getter != null) { if (!getter.isAccessible()) { getter.setAccessible(true); } return getter.invoke(bean, new Object[0]); } return null; } catch (Exception e) { return null; } } public static void setProperties(Object bean, Map
             
               properties) { for (Method method : bean.getClass().getMethods()) { String name = method.getName(); if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 1 && method.getDeclaringClass() != Object.class) { String key = name.substring(3, 4).toLowerCase() + name.substring(4); try { Object value = properties.get(key); if (value != null) { method.invoke(bean, new Object[] { convertCompatibleType(value, method.getParameterTypes()[0]) }); } } catch (Exception e) { } } } } public static Map
              
                getProperties(Object bean) { Map
               
                 map = new HashMap
                
                 (); for (Method method : bean.getClass().getMethods()) { String name = method.getName(); if ((name.length() > 3 && name.startsWith("get") || name.length() > 2 && name.startsWith("is")) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && method.getDeclaringClass() != Object.class) { int i = name.startsWith("get") ? 3 : 2; String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); try { map.put(key, method.invoke(bean, new Object[0])); } catch (Exception e) { } } } return map; } public static 
                 
                   Set
                  
                   > entrySet(Map
                   
                     map) { return map == null ? null : map.entrySet(); } public static String dumpException(Throwable e) { StringWriter sw = new StringWriter(160); sw.write(e.getClass().getName()); sw.write(":\n"); e.printStackTrace(new PrintWriter(sw)); return sw.toString(); } public static String filterJavaKeyword(String name) { if ("abstract".equals(name) || "assert".equals(name) || "boolean".equals(name) || "break".equals(name) || "byte".equals(name) || "case".equals(name) || "catch".equals(name) || "char".equals(name) || "class".equals(name) || "continue".equals(name) || "default".equals(name) || "do".equals(name) || "double".equals(name) || "else".equals(name) || "enum".equals(name) || "extends".equals(name) || "final".equals(name) || "finally".equals(name) || "float".equals(name) || "for".equals(name) || "if".equals(name) || "implements".equals(name) || "import".equals(name) || "instanceof".equals(name) || "int".equals(name) || "interface".equals(name) || "long".equals(name) || "native".equals(name) || "new".equals(name) || "package".equals(name) || "private".equals(name) || "protected".equals(name) || "public".equals(name) || "return".equals(name) || "strictfp".equals(name) || "short".equals(name) || "static".equals(name) || "super".equals(name) || "switch".equals(name) || "synchronized".equals(name) || "this".equals(name) || "throw".equals(name) || "throws".equals(name) || "transient".equals(name) || "try".equals(name) || "void".equals(name) || "volatile".equals(name) || "while".equals(name)) { return "$" + name; } return name; } private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 兼容类型转换。null值是OK的。如果不需要转换,则返回原来的值。 * 进行的兼容类型转换如下:(基本类对应的Wrapper类型不再列出。) * @param value 转换的类型 * @param type 字节码 * @return 返回转换之后的对象 */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static Object convertCompatibleType(Object value, Class
                     type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format( "CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class
                    
                     ) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse( (String) value); } catch (ParseException e) { throw new IllegalStateException( "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { return ClassUtils.forName((String) value); } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList
                     (collection); } else if (type == Set.class) { return new HashSet(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList(); } } else if (type == Set.class) { collection = new HashSet(); } else { collection = new ArrayList(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } private ClassUtils() {} } 
                          
                           Colors.java
                           
package com.github.lazylibrary.util; /**
 * Copyright 2014 Zhenguo Jin (jinzhenguo1990@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * 颜色工具类 包括常用的色值
 *
 * @author jingle1267@163.com
 */
public final class Colors {

    /**
     * Don't let anyone instantiate this class.
     */
    private Colors() {
        throw new Error("Do not need instantiate!");
    }

    /**
     * 白色
     */
    public static final int WHITE = 0xffffffff;

    /**
     * 白色 - 半透明
     */
    public static final int WHITE_TRANSLUCENT = 0x80ffffff;

    /**
     * 黑色
     */
    public static final int BLACK = 0xff000000;

    /**
     * 黑色 - 半透明
     */
    public static final int BLACK_TRANSLUCENT = 0x80000000;

    /**
     * 透明
     */
    public static final int TRANSPARENT = 0x00000000;

    /**
     * 红色
     */
    public static final int RED = 0xffff0000;

    /**
     * 红色 - 半透明
     */
    public static final int RED_TRANSLUCENT = 0x80ff0000;

    /**
     * 红色 - 深的
     */
    public static final int RED_DARK = 0xff8b0000;

    /**
     * 红色 - 深的 - 半透明
     */
    public static final int RED_DARK_TRANSLUCENT = 0x808b0000;

    /**
     * 绿色
     */
    public static final int GREEN = 0xff00ff00;

    /**
     * 绿色 - 半透明
     */
    public static final int GREEN_TRANSLUCENT = 0x8000ff00;

    /**
     * 绿色 - 深的
     */
    public static final int GREEN_DARK = 0xff003300;

    /**
     * 绿色 - 深的 - 半透明
     */
    public static final int GREEN_DARK_TRANSLUCENT = 0x80003300;

    /**
     * 绿色 - 浅的
     */
    public static final int GREEN_LIGHT = 0xffccffcc;

    /**
     * 绿色 - 浅的 - 半透明
     */
    public static final int GREEN_LIGHT_TRANSLUCENT = 0x80ccffcc;

    /**
     * 蓝色
     */
    public static final int BLUE = 0xff0000ff;

    /**
     * 蓝色 - 半透明
     */
    public static final int BLUE_TRANSLUCENT = 0x800000ff;

    /**
     * 蓝色 - 深的
     */
    public static final int BLUE_DARK = 0xff00008b;

    /**
     * 蓝色 - 深的 - 半透明
     */
    public static final int BLUE_DARK_TRANSLUCENT = 0x8000008b;

    /**
     * 蓝色 - 浅的
     */
    public static final int BLUE_LIGHT = 0xff36a5E3;

    /**
     * 蓝色 - 浅的 - 半透明
     */
    public static final int BLUE_LIGHT_TRANSLUCENT = 0x8036a5E3;

    /**
     * 天蓝
     */
    public static final int SKYBLUE = 0xff87ceeb;

    /**
     * 天蓝 - 半透明
     */
    public static final int SKYBLUE_TRANSLUCENT = 0x8087ceeb;

    /**
     * 天蓝 - 深的
     */
    public static final int SKYBLUE_DARK = 0xff00bfff;

    /**
     * 天蓝 - 深的 - 半透明
     */
    public static final int SKYBLUE_DARK_TRANSLUCENT = 0x8000bfff;

    /**
     * 天蓝 - 浅的
     */
    public static final int SKYBLUE_LIGHT = 0xff87cefa;

    /**
     * 天蓝 - 浅的 - 半透明
     */
    public static final int SKYBLUE_LIGHT_TRANSLUCENT = 0x8087cefa;

    /**
     * 灰色
     */
    public static final int GRAY = 0xff969696;

    /**
     * 灰色 - 半透明
     */
    public static final int GRAY_TRANSLUCENT = 0x80969696;

    /**
     * 灰色 - 深的
     */
    public static final int GRAY_DARK = 0xffa9a9a9;

    /**
     * 灰色 - 深的 - 半透明
     */
    public static final int GRAY_DARK_TRANSLUCENT = 0x80a9a9a9;

    /**
     * 灰色 - 暗的
     */
    public static final int GRAY_DIM = 0xff696969;

    /**
     * 灰色 - 暗的 - 半透明
     */
    public static final int GRAY_DIM_TRANSLUCENT = 0x80696969;

    /**
     * 灰色 - 浅的
     */
    public static final int GRAY_LIGHT = 0xffd3d3d3;

    /**
     * 灰色 - 浅的 - 半透明
     */
    public static final int GRAY_LIGHT_TRANSLUCENT = 0x80d3d3d3;

    /**
     * 橙色
     */
    public static final int ORANGE = 0xffffa500;

    /**
     * 橙色 - 半透明
     */
    public static final int ORANGE_TRANSLUCENT = 0x80ffa500;

    /**
     * 橙色 - 深的
     */
    public static final int ORANGE_DARK = 0xffff8800;

    /**
     * 橙色 - 深的 - 半透明
     */
    public static final int ORANGE_DARK_TRANSLUCENT = 0x80ff8800;

    /**
     * 橙色 - 浅的
     */
    public static final int ORANGE_LIGHT = 0xffffbb33;

    /**
     * 橙色 - 浅的 - 半透明
     */
    public static final int ORANGE_LIGHT_TRANSLUCENT = 0x80ffbb33;

    /**
     * 金色
     */
    public static final int GOLD = 0xffffd700;

    /**
     * 金色 - 半透明
     */
    public static final int GOLD_TRANSLUCENT = 0x80ffd700;

    /**
     * 粉色
     */
    public static final int PINK = 0xffffc0cb;

    /**
     * 粉色 - 半透明
     */
    public static final int PINK_TRANSLUCENT = 0x80ffc0cb;

    /**
     * 紫红色
     */
    public static final int FUCHSIA = 0xffff00ff;

    /**
     * 紫红色 - 半透明
     */
    public static final int FUCHSIA_TRANSLUCENT = 0x80ff00ff;

    /**
     * 灰白色
     */
    public static final int GRAYWHITE = 0xfff2f2f2;

    /**
     * 灰白色 - 半透明
     */
    public static final int GRAYWHITE_TRANSLUCENT = 0x80f2f2f2;

    /**
     * 紫色
     */
    public static final int PURPLE = 0xff800080;

    /**
     * 紫色 - 半透明
     */
    public static final int PURPLE_TRANSLUCENT = 0x80800080;

    /**
     * 青色
     */
    public static final int CYAN = 0xff00ffff;

    /**
     * 青色 - 半透明
     */
    public static final int CYAN_TRANSLUCENT = 0x8000ffff;

    /**
     * 青色 - 深的
     */
    public static final int CYAN_DARK = 0xff008b8b;

    /**
     * 青色 - 深的 - 半透明
     */
    public static final int CYAN_DARK_TRANSLUCENT = 0x80008b8b;

    /**
     * 黄色
     */
    public static final int YELLOW = 0xffffff00;

    /**
     * 黄色 - 半透明
     */
    public static final int YELLOW_TRANSLUCENT = 0x80ffff00;

    /**
     * 黄色 - 浅的
     */
    public static final int YELLOW_LIGHT = 0xffffffe0;

    /**
     * 黄色 - 浅的 - 半透明
     */
    public static final int YELLOW_LIGHT_TRANSLUCENT = 0x80ffffe0;

    /**
     * 巧克力色
     */
    public static final int CHOCOLATE = 0xffd2691e;

    /**
     * 巧克力色 - 半透明
     */
    public static final int CHOCOLATE_TRANSLUCENT = 0x80d2691e;

    /**
     * 番茄色
     */
    public static final int TOMATO = 0xffff6347;

    /**
     * 番茄色 - 半透明
     */
    public static final int TOMATO_TRANSLUCENT = 0x80ff6347;

    /**
     * 橙红色
     */
    public static final int ORANGERED = 0xffff4500;

    /**
     * 橙红色 - 半透明
     */
    public static final int ORANGERED_TRANSLUCENT = 0x80ff4500;

    /**
     * 银白色
     */
    public static final int SILVER = 0xffc0c0c0;

    /**
     * 银白色 - 半透明
     */
    public static final int SILVER_TRANSLUCENT = 0x80c0c0c0;

    /**
     * 高光
     */
    public static final int HIGHLIGHT = 0x33ffffff;

    /**
     * 低光
     */
    public static final int LOWLIGHT = 0x33000000;

}
DatabaseExportUtils.java
package com.github.lazylibrary.util; /**
 * Copyright 2014 Zhenguo Jin (jingle1267@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

/**
 * 应用数据库导出工具类
 *
 * @author jingle1267@163.com
 */
public final class DatabaseExportUtils {

    private static final boolean DEBUG = true;
    private static final String TAG = "DatabaseExportUtils";

    /**
     * Don't let anyone instantiate this class.
     */
    private DatabaseExportUtils() {
        throw new Error("Do not need instantiate!");
    }

    /**
     * 开始导出数据 此操作比较耗时,建议在线程中进行
     *
     * @param context      上下文
     * @param targetFile   目标文件
     * @param databaseName 要拷贝的数据库文件名
     * @return 是否倒出成功
     */
    public boolean startExportDatabase(Context context, String targetFile,
                                       String databaseName) {
        if (DEBUG) {
        }
        if (!Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            if (DEBUG) {
            }
            return false;
        }
        String sourceFilePath = Environment.getDataDirectory() + "/data/"
                + context.getPackageName() + "/databases/" + databaseName;
        String destFilePath = Environment.getExternalStorageDirectory()
                + (TextUtils.isEmpty(targetFile) ? (context.getPackageName() + ".db")
                                                 : targetFile);
        boolean isCopySuccess = FileUtils
                .copyFile(sourceFilePath, destFilePath);
        if (DEBUG) {
            if (isCopySuccess) {

            } else {
            }
        }
        return isCopySuccess;
    }
}
DataCleanManager.java
package com.github.lazylibrary.util; /**
 * Copyright 2014 Zhenguo Jin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.math.BigDecimal;

import android.content.Context;
import android.os.Environment;

/**
 * 本应用数据清除管理器
 * 主要功能有清除内/外缓存,清除数据库,清除sharedPreference,清除files和清除自定义目录
 *
 * @author jingle1267@163.com
 */
public class DataCleanManager {

    /**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
     *
     * @param context 上下文
     */
    public static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }

    /**
     * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases)
     *
     * @param context 上下文
     */
    public static void cleanDatabases(Context context) {
        deleteFilesByDirectory(new File(context.getFilesDir().getPath()
                + context.getPackageName() + "/databases"));
    }

    /**
     * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
     *
     * @param context 上下文
     */
    public static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File(context.getFilesDir().getPath()
                + context.getPackageName() + "/shared_prefs"));
    }

    /**
     * 按名字清除本应用数据库
     *
     * @param context 上下文
     * @param dbName 数据库名称
     */
    public static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }

    /**
     * 清除/data/data/com.xxx.xxx/files下的内容
     *
     * @param context 上下文
     */
    public static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
     *
     * @param context 上下文
     */
    public static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }

    /**
     * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除
     *
     * @param filePath 文件路径
     */
    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /**
     * 清除本应用所有的数据
     *
     * @param context 上下文
     * @param filePath 文件路径
     */
    public static void cleanApplicationData(Context context, String... filePath) {
        cleanInternalCache(context);
        cleanExternalCache(context);
        cleanDatabases(context);
        cleanSharedPreference(context);
        cleanFiles(context);
        for (String fp : filePath) {
            cleanCustomCache(fp);
        }
    }

    /**
     * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理
     *
     * @param directory 文件夹File对象
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    // 获取文件
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录,一般放一些长时间保存的数据
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据
    public static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面还有文件
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }

    /**
     *
     *
     * @param size 传入的大小
     * @return  格式化单位返回格式化之后的值
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                          .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                          .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                          .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

}
RegexUtils.java
/*
 * Copyright (C) 2013 Peng fei Pan 
                           
                            
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.lazylibrary.util;

/**
 * 
                            

正则表达式工具类,提供一些常用的正则表达式

*/ public class RegexUtils { /** * 匹配全网IP的正则表达式 */ public static final String IP_REGEX = "^((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))$"; /** * 匹配手机号码的正则表达式 *
支持130——139、150——153、155——159、180、183、185、186、188、189号段 */ public static final String PHONE_NUMBER_REGEX = "^1{1}(3{1}\\d{1}|5{1}[012356789]{1}|8{1}[035689]{1})\\d{8}$"; /** * 匹配邮箱的正则表达式 *
"www."可省略不写 */ public static final String EMAIL_REGEX = "^(www\\.)?\\w+@\\w+(\\.\\w+)+$"; /** * 匹配汉子的正则表达式,个数限制为一个或多个 */ public static final String CHINESE_REGEX = "^[\u4e00-\u9f5a]+$"; /** * 匹配正整数的正则表达式,个数限制为一个或多个 */ public static final String POSITIVE_INTEGER_REGEX = "^\\d+$"; /** * 匹配身份证号的正则表达式 */ public static final String ID_CARD = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"; /** * 匹配邮编的正则表达式 */ public static final String ZIP_CODE = "^\\d{6}$"; /** * 匹配URL的正则表达式 */ public static final String URL = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[wW]{3}\\.[\\w-]+\\.\\w{2,4}(\\/.*)?$"; /** * 匹配给定的字符串是否是一个邮箱账号,"www."可省略不写 * @param string 给定的字符串 * @return true:是 */ public static boolean isEmail(String string){ return string.matches(EMAIL_REGEX); } /** * 匹配给定的字符串是否是一个手机号码,支持130——139、150——153、155——159、180、183、185、186、188、189号段 * @param string 给定的字符串 * @return true:是 */ public static boolean isMobilePhoneNumber(String string){ return string.matches(PHONE_NUMBER_REGEX); } /** * 匹配给定的字符串是否是一个全网IP * @param string 给定的字符串 * @return true:是 */ public static boolean isIp(String string){ return string.matches(IP_REGEX); } /** * 匹配给定的字符串是否全部由汉子组成 * @param string 给定的字符串 * @return true:是 */ public static boolean isChinese(String string){ return string.matches(CHINESE_REGEX); } /** * 验证给定的字符串是否全部由正整数组成 * @param string 给定的字符串 * @return true:是 */ public static boolean isPositiveInteger(String string){ return string.matches(POSITIVE_INTEGER_REGEX); } /** * 验证给定的字符串是否是身份证号 *
*
身份证15位编码规则:dddddd yymmdd xx p *
dddddd:6位地区编码 *
yymmdd:出生年(两位年)月日,如:910215 *
xx:顺序编码,系统产生,无法确定 *
p:性别,奇数为男,偶数为女 *
*
*
身份证18位编码规则:dddddd yyyymmdd xxx y *
dddddd:6位地区编码 *
yyyymmdd:出生年(四位年)月日,如:19910215 *
xxx:顺序编码,系统产生,无法确定,奇数为男,偶数为女 *
y:校验码,该位数值可通过前17位计算获得 *
前17位号码加权因子为 Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ] *
验证位 Y = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ] *
如果验证码恰好是10,为了保证身份证是十八位,那么第十八位将用X来代替 校验位计算公式:Y_P = mod( ∑(Ai×Wi),11 ) *
i为身份证号码1...17 位; Y_P为校验码Y所在校验码数组位置 * @param string * @return */ public static boolean isIdCard(String string){ return string.matches(ID_CARD); } /** * 验证给定的字符串是否是邮编 * @param string * @return */ public static boolean isZipCode(String string){ return string.matches(ZIP_CODE); } /** * 验证给定的字符串是否是URL,仅支持http、https、ftp * @param string * @return */ public static boolean isURL(String string){ return string.matches(URL); } }
SqliteUtils.java
package com.github.lazylibrary.util;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * SqliteUtils
 * 
 * @author Trinea 2013-10-21
 */
public class SqliteUtils {

    private static volatile SqliteUtils instance;

    private DbHelper                    dbHelper;
    private SQLiteDatabase              db;

    private SqliteUtils(Context context) {
        dbHelper = new DbHelper(context);
        db = dbHelper.getWritableDatabase();
    }

    public static SqliteUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (SqliteUtils.class) {
                if (instance == null) {
                    instance = new SqliteUtils(context);
                }
            }
        }
        return instance;
    }

    public SQLiteDatabase getDb() {
        return db;
    }
}
ZipUtil.java
package com.github.lazylibrary.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Java utils 实现的Zip工具
 *
 * @author once
 */
public class ZipUtil{
    private static final int BUFF_SIZE = 1024 * 1024; // 1M Byte
    private static boolean stopZipFlag;

    public static boolean isStopZipFlag() {
		return stopZipFlag;
	}

	public static void setStopZipFlag(boolean stopZipFlag) {
		ZipUtil.stopZipFlag = stopZipFlag;
	}

	/**
     * 批量压缩文件(夹)
     *
     * @param resFileList 要压缩的文件(夹)列表
     * @param zipFile 生成的压缩文件
     * @param zipListener     zipListener
     */
    public static void zipFiles(Collection
                           
                             resFileList, File zipFile,ZipListener zipListener)  {

        ZipOutputStream zipout = null;
        try {
            zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(
                    zipFile), BUFF_SIZE));
            for (File resFile : resFileList) {
                if(stopZipFlag){
                    break;
                }
                zipFile(resFile, zipout, "",zipListener);
            }
            zipout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量压缩文件(夹)
     *
     * @param resFileList 要压缩的文件(夹)列表
     * @param zipFile 生成的压缩文件
     * @param comment 压缩文件的注释
     * @param zipListener    zipListener
     */
    public static void zipFiles(Collection
                            
                              resFileList, File zipFile, String comment,ZipListener zipListener) { ZipOutputStream zipout = null; try { zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE)); for (File resFile : resFileList) { zipFile(resFile, zipout, "",zipListener); } zipout.setComment(comment); zipout.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 解压缩一个文件 * * @param zipFile 压缩文件 * @param folderPath 解压缩的目标目录 */ public static void upZipFile(File zipFile, String folderPath) { File desDir = new File(folderPath); if (!desDir.exists()) { desDir.mkdirs(); } ZipFile zf = null; try { zf = new ZipFile(zipFile); for (Enumeration
                              entries = zf.entries(); entries.hasMoreElements();) { ZipEntry entry = ((ZipEntry)entries.nextElement()); InputStream in = zf.getInputStream(entry); String str = folderPath + File.separator + entry.getName(); str = new String(str.getBytes("8859_1"), "GB2312"); File desFile = new File(str); if (!desFile.exists()) { File fileParentDir = desFile.getParentFile(); if (!fileParentDir.exists()) { fileParentDir.mkdirs(); } desFile.createNewFile(); } OutputStream out = new FileOutputStream(desFile); byte buffer[] = new byte[BUFF_SIZE]; int realLength; while ((realLength = in.read(buff
                            
                           
网友评论