WebUtils.java 8.0 KB
package com.framework.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.shiro.SecurityUtils;

import com.alibaba.fastjson.JSONObject;
import com.eport.rest.entity.EptUserInfoEntity;

public class WebUtils {
	private static DecimalFormat df = new DecimalFormat("#0.00");
	private static DecimalFormat df4 = new DecimalFormat("#0.0000");
	private static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");

	public static Boolean checkPassword(String password) {
		Pattern pattern = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z\\!@#%^&\\*()~/|]+$)[0-9A-Za-z\\!@#%^&\\*()~/|]{6,16}$");
		Matcher matcher = pattern.matcher(password);
		return matcher.matches();
	}

	public static Boolean isEmail(String email) {
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();
	}

	public static String saltMd5(String s) {
		s = tranlateString(s);
		return md5(s);
	}

	public static void main(String[] args) {
		System.out.println(saltMd5("123456"));
	}

	public static String tranlateString(String s) {
		if (s.length() > 1) {
			int halfLen = s.length() / 2;
			String result = "";
			for (int i = 0; i < halfLen; i++) {
				result += s.charAt(halfLen + i);
				result += s.charAt(i);
			}
			if (s.length() % 2 == 1) {
				result += s.charAt(s.length() - 1);
			}
			return result;
		}
		return s;
	}

	public static String md5(String s) {
		char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char[] str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String fileMD5(String inputFile) throws IOException {
		// 缓冲区大小(这个可以抽出一个参数)
		int bufferSize = 256 * 1024;
		FileInputStream fileInputStream = null;
		DigestInputStream digestInputStream = null;
		try {
			// 拿到一个MD5转换器(同样,这里可以换成SHA1)
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 使用DigestInputStream
			fileInputStream = new FileInputStream(inputFile);
			digestInputStream = new DigestInputStream(fileInputStream, messageDigest);
			// read的过程中进行MD5处理,直到读完文件
			// 获取最终的MessageDigest
			messageDigest = digestInputStream.getMessageDigest();
			// 拿到结果,也是字节数组,包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 同样,把字节数组转换成字符串
			return byteArrayToHex(resultByteArray);
		} catch (NoSuchAlgorithmException e) {
			return null;
		} finally {
			try {
				digestInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				fileInputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static String byteArrayToHex(byte[] byteArray) {
		// 首先初始化一个字符数组,用来存放每个16进制字符
		char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
		char[] resultCharArray = new char[byteArray.length * 2];
		// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		// 字符数组组合成字符串返回
		return new String(resultCharArray);
	}

	public static String[] getUrlPars(String url) {
		if (url.indexOf("{") > -1 && url.indexOf("}") > -1) {
			return new String[] {url.substring(url.indexOf("{") + 1, url.indexOf("}")) };
		}
		return null;
	}

	public static Object copyProperties(Object des, Object src) {
		return JSONObject.parseObject(JSONObject.toJSONString(src), des.getClass());
	}

	public static String formatMoney(String money) {
		try {
			df.setRoundingMode(RoundingMode.HALF_UP);
			return df.format(new BigDecimal(money.toString()));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("money格式化错误:[" + money + "]");
			return money;
		}
	}

	public static String formatMoneySp(String money) {
		try {
			if (money.startsWith("0.00") || money.startsWith("-0.00")) {
				df.setRoundingMode(RoundingMode.DOWN);
			} else {
				df.setRoundingMode(RoundingMode.HALF_UP);
			}
			return df.format(new BigDecimal(money.toString()));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("money格式化错误:[" + money + "]");
			return money;
		}
	}

	public static String formatMoneyWith4(String money) {
		try {
			df4.setRoundingMode(RoundingMode.HALF_UP);
			return df4.format(new BigDecimal(money.toString()));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("money格式化错误:[" + money + "]");
			return money;
		}
	}

	public static Float coutStringExp(String exp) {
		try {
			if (exp.indexOf("--") > -1) {
				exp = exp.replaceAll("--", "+");
			}
			return Float.parseFloat(jse.eval(exp).toString());
		} catch (Exception e) {
			e.printStackTrace();
			return 0f;
		}
	}

	public static String coutStringExp4String(String exp) {
		try {
			if (exp.indexOf("--") > -1) {
				exp = exp.replaceAll("--", "+");
			}
			return jse.eval(exp).toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "0";
		}
	}

	public static String coutStringWithFormatSp(String exp) {
		return formatMoneySp(coutStringExp4String(exp));
	}

	public static String coutStringWithFormat(String exp) {
		return formatMoney(coutStringExp4String(exp));
	}

	public static String coutStringWithFormat4(String exp) {
		return formatMoneyWith4(coutStringExp4String(exp));
	}

	public static Boolean checkIntIds(String ids) {
		String[] idArray = ids.split(",");
		try {
			for (String id : idArray) {
				Integer.parseInt(id.trim());
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static int getMonthLastDay(int year, int month) {
		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month - 1);
		a.set(Calendar.DATE, 1); // 把日期设置为当月第一天
		a.roll(Calendar.DATE, -1); // 日期回滚一天,也就是最后一天
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	/**
	 * 获取当前登入人员
	 * 
	 * @return
	 */
	public static EptUserInfoEntity getCurrentUser() {
		try {
			return (EptUserInfoEntity) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static ScriptEngine getJse() {
		return jse;
	}

	public static void setJse(ScriptEngine jse) {
		WebUtils.jse = jse;
	}

}