平时收集别人的一些代码工具类 代码工具 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 PanBadgeUtil.java* * 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) { Stacksa = 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); } }
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应用的图标 */ /*Base64.java*/ 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); } }
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.ByteUtils.java
* 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
/* * Copyright (C) 2013 Peng fei PanClassUtils.java* * 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; } }
/* * 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