You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

696 lines
22 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.dsideal.Util;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dsideal.Const.OsSystemConst;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.hikaricp.HikariCpPlugin;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommonUtil {
//在独立的main函数中使用下面的方式进行声明logback对象
private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
//获取当前年份
public static String getCurrentYear() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
Date date = new Date();
return sdf.format(date);
}
/**
* 功能:校验密码强度
* 作者:吴缤
* 日期2019-01-19
*
* @param pwd
* @return
*/
public static boolean getPwdLegal(String pwd) {
boolean flag = false;
try {
String regExp = "[a-z0-9A-Z]+";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(pwd);
return m.matches();
} catch (Exception e) {
return false;
}
}
private static String TruncateUrlPage(String strURL) {
String strAllParam = null;
String[] arrSplit = null;
strURL = strURL.trim();
arrSplit = strURL.split("[?]");
if (strURL.length() > 1) {
if (arrSplit.length > 1) {
if (arrSplit[1] != null) {
strAllParam = arrSplit[1];
}
}
}
return strAllParam;
}
private static Map<String, String> URLRequest(String URL) {
Map<String, String> mapRequest = new HashMap<String, String>();
String[] arrSplit = null;
String strUrlParam = TruncateUrlPage(URL);
if (strUrlParam == null) {
return mapRequest;
}
// 每个键值为一组 www.2cto.com
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
// 解析出键值
if (arrSplitEqual.length > 1) {
// 正确解析
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (arrSplitEqual[0] != "") {
// 只有参数没有值,不加入
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
}
public static String handleRedirectUrlParas(String redirect_url) {
String redirectUrl = redirect_url;
String[] paras = redirect_url.split("\\?");
if (paras.length > 1) {
String uri = paras[0];
Map<String, String> parasMap = URLRequest(redirect_url);
for (Map.Entry<String, String> entry : parasMap.entrySet()) {
if (!entry.getKey().equals(PropKit.get("sso.sessionid"))) {
if (uri.indexOf("?") == -1) {
uri += "?"+entry.getKey()+"="+entry.getValue();
}else{
uri += "&"+entry.getKey()+"="+entry.getValue();
}
}
}
redirectUrl = uri;
}
return redirectUrl;
}
/**
* 功能:获取操作系统类型
* 作者:黄海
* 时间2019-04-22
*
* @return
*/
public static int getOsSystemType() {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
return OsSystemConst.WINDOWS;
} else {
return OsSystemConst.CENTOS;
}
}
/**
* 功能:删除指定目录下所有的文件
* 作者:黄海
* 时间2019-01-03
*
* @param tempPath
*/
public static void clearFile(String tempPath) {
File file = new File(tempPath);
File[] tempList = file.listFiles();
if (tempList != null) {
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
tempList[i].delete();
}
}
}
}
/**
* 功能:判断是不是合法的日期格式
* 作者:黄海
* 时间2018-12-20
*
* @param str
* @return
*/
public static boolean isValidDate(String str) {
boolean convertSuccess = true;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
convertSuccess = false;
}
return convertSuccess;
}
/**
* 功能:将用户帐号和原始密码传入,返回是不是修改了密码
* 作者:黄海
* 时间2018-12-12
*
* @return
*/
public static Page<Record> ConvertLoginRs(Page<Record> page) {
List<Record> list = new ArrayList<>();
for (int i = 0; i < page.getList().size(); i++) {
Record record = page.getList().get(i);
String original_pwd = record.get("original_pwd");
String database_pwd = record.get("pwd");
//将明文密码加密
String pwd = CommonUtil.getLdapPassword(original_pwd);
if (!pwd.equals(database_pwd)) {
record.set("original_pwd", "用户已修改");
}
record.remove("pwd");
list.add(record);
}
Page<Record> pageRecords = new Page(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
return pageRecords;
}
/**
* 功能判断一个字符串是不是JSONArray格式
* 作者:黄海
* 时间:2018-12-12
*
* @param content
* @return
*/
public static boolean isJsonArray(String content) {
try {
JSONArray.parseArray(content);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 功能:获取当前时间,按年月日+时分秒格式返回
* 作者:黄海
* 时间2018-11-30
*
* @return
*/
public static String GetCurrentTimeString() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
String nowTime = sdf.format(date);
return nowTime;
}
/**
* 加签
*
* @param map
* @return
*/
public static String Sign(Map<String, Object> map, String signKey) {
if (map == null) {
return null;
}
List<String> keyList = new ArrayList<>(map.keySet());
Collections.sort(keyList);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < keyList.size(); i++) {
String key = keyList.get(i);
Object value = map.get(key);
sb.append(key + "=" + value + "&");
}
String signStr = sb.substring(0, sb.length() - 1) + signKey;
String md5Str = DigestUtils.md5Hex(signStr);
return md5Str;
}
/**
* 按照layUI格式分页获取数据
*/
public static Map<String, Object> renderJsonForLayUI(List<Record> list, int count) {
Map<String, Object> result = new HashMap<>();
result.put("code", 0);
result.put("msg", "");
result.put("count", count);
result.put("data", list);
return result;
}
public static Map<String, Object> renderJsonForLayUI(List<Record> list) {
Map<String, Object> result = new HashMap<>();
result.put("code", 0);
result.put("msg", "");
result.put("count", list.size());
result.put("data", list);
return result;
}
/**
* 按照layUI格式分页获取数据
*
* @param dataPage
* @return
*/
public static Map<String, Object> renderJsonForLayUI(Page<Record> dataPage) {
Map<String, Object> result = new HashMap<>();
result.put("code", 0);
result.put("msg", "");
result.put("count", dataPage.getTotalRow());
result.put("data", dataPage.getList());
return result;
}
/**
* 功能:判断一个字符串是不是整数
* 作者:黄海
* 时间2018-11-19
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
try {
for (int i = str.length(); --i >= 0; ) {
if (str.charAt(0) == '-') {
continue;
} else {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
}
return true;
} catch (Exception err) {
return false;
}
}
/**
* 功能封装一个返回json信息的函数
* 作者:黄海
* 时间2018-11-06
*
* @param result
* @param message
*/
public static Map returnMessageJson(boolean result, String message) {
Map<String,Object> map = new HashMap<>();
map.put("success", result);
map.put("message", message);
return map;
}
public static Map returnMessageJson(boolean result, JSONObject jo) {
Map<String,Object> map = new HashMap<>();
map.put("success", result);
map.put("result", jo);
return map;
}
public static Map returnMessageJson(boolean result, List<Record> list) {
Map<String,Object> map = new HashMap<>();
map.put("success", result);
map.put("result", list);
return map;
}
/**
* 功能简单的md5加密
* 作者:黄海
* 时间2018-11-06
*
* @param target
* @return
*/
public static String md5(String target) {
return DigestUtils.md5Hex(target);
}
//算法:将密码经过 MD5 运算,得到 32 字节的字符串然后每2个字节压缩成一个十六进制字符
// 这样得到16字节的字符串最后经过Base64编码。
public static String getLdapPassword(String password) {
try {
String md5pass = md5(password);
byte[] baKeyword = new byte[md5pass.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(md5pass.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
log.error("======================错误密码:" + md5pass);
e.printStackTrace();
}
}
String newstr = Base64.encodeBase64String(baKeyword);
return newstr;
} catch (Exception err) {
log.error("出错的密码:" + password);
return null;
}
}
/**
* 功能获取6位随机数
* 作者:黄海
* 日期2018-11-27
*
* @return
*/
public static String getSixRandom() {
String sources = "0123456789";
Random rand = new Random();
StringBuffer flag = new StringBuffer();
for (int j = 0; j < 6; j++) {
flag.append(sources.charAt(rand.nextInt(9)) + "");
}
return flag.toString();
}
/**
* 功能执行一个shell指令直到结束
* 作者:黄海
* 时间2019-01-19
*
* @param cmd
*/
public static void ExecShellWaitFinish(String cmd) {
Process process = null;
String ls_1;
try {
process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
while ((ls_1 = bufferedReader1.readLine()) != null)
log.info(ls_1);
bufferedReader1.close();
process.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (process.waitFor() == 0) {
return;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 功能:验证是否为手机号
* 作者:黄海
* 日期2018-11-27
* 13+任意数
* 15+除4的任意数
* 18+除1和4的任意数
* 17+除9的任意数
* 147
*
* @param phoneNum
* @return
*/
public static boolean getIsPhoneLegal(String phoneNum) {
try {
String regExp = "^((13[0-9])|(19[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(phoneNum);
return m.matches();
} catch (Exception e) {
return false;
}
}
/**
* 功能:验证是否为邮箱
* 作者:黄海
* 日期2018-11-27
*
* @param eMail
* @return
*/
public static boolean getIsEmailLegal(String eMail) {
try {
String regExp = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(eMail);
return m.matches();
} catch (Exception e) {
return false;
}
}
/**
* 功能:验证是否为日期格式
* 作者:黄海
* 日期2018-12-07
*
* @param date
* @return
*/
public static boolean getIsDateLegal(String date) {
if (date == null || StrKit.isBlank(date)) return false;
try {
String regExp = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(date);
return m.matches();
} catch (Exception e) {
return false;
}
}
/**
* 功能:判断性别是否在有效范围内
* 作者:黄海
* 日期2018-12-07
*
* @param xb
* @return
*/
public static boolean getXbCorrectRange(String xb) {
String[] stageArr = new String[]{"1", "2"};
for (String s : stageArr) {
if (s.equals(xb)) {
return true;
}
}
return false;
}
/**
* 功能:判断民族是否在有效范围内
* 作者:黄海
* 日期2018-12-07
*
* @param mz
* @return
*/
public static boolean getMzCorrectRange(String mz) {
String[] stageArr = new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "97", "98"};
for (String s : stageArr) {
if (s.equals(mz)) {
return true;
}
}
return false;
}
/**
* 功能:判断是不是合法的政治面貌
* 作者:黄海
* 时间2019-01-05
*
* @param zzmm
* @return
*/
public static boolean getZzmmCorrectRange(String zzmm) {
String[] stageArr = new String[]{"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13"};
for (String s : stageArr) {
if (s.equals(zzmm)) {
return true;
}
}
return false;
}
/**
* 功能获取查询总数量的SQL语句
* 作者:黄海
* 时间2021-11-01
*
* @param findSql
* @return
*/
public static String getTotalSql(String findSql) {
String totalRowSql = "select count(*) from (" + findSql + ") as t100";
return totalRowSql;
}
/**
* 功能接字符串方便IN方式查询
* 作者:黄海
* 时间2021-10-22
*
* @param list
* @param key
* @return
*/
public static String getIds(List<Record> list, String key) {
String s = "";
if (list.size() == 0) return "-1";
for (Record record1 : list) s += "'" + record1.getStr(key) + "',";
s = s.substring(0, s.length() - 1);
return s;
}
/**
* 功能:输出字符串信息
*
* @param str
*/
public static void printf(String str) {
System.out.println(DateTime.now() + " " + str);
}
/***
* delete CRLF; delete empty line ;delete blank lines
*
* @param input
* @return
*/
private static String deleteCRLFOnce(String input) {
return input.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1");
}
/**
* delete CRLF; delete empty line ;delete blank lines
*
* @param input
* @return
*/
public static String deleteCRLF(String input) {
input = deleteCRLFOnce(input);
return deleteCRLFOnce(input);
}
public static void changeEncode(String source, String target) throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream(source), "gbk");
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(target), "utf-8");
int len = 0;
char[] chars = new char[1024];
while ((len = isr.read(chars)) != -1) {
osw.write(chars, 0, len);
}
osw.close();
isr.close();
}
public static boolean checkPass(String pass) {
//注释掉必须要有符号这个要求:&& pass.matches(".*[~!@#$%^&*\\.?]{1,}.*")
// if (pass.matches(".*[a-z]{1,}.*") && pass.matches(".*[A-Z]{1,}.*") && pass.matches(".*\\d{1,}.*") && pass.length()>=7 ) {
// return true;
// }
// return false;
return true;
}
public static boolean isBase64(String str) {
String base64Rule = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
return Pattern.matches(base64Rule, str);
}
/**
* 功能返回当前class的运行路径
*
* @return
*/
public static String getClassPath() throws URISyntaxException {
String path = PathKit.class.getClassLoader().getResource("").toURI().getPath();
if (getOsSystemType() == OsSystemConst.WINDOWS) {
if (path.startsWith("/")) path = path.substring(1);
}
return path;
}
public static void log(String msg) {
System.out.println(DateTime.now() + " " + msg);
}
public static JSONObject getJsonFile(String filePath) {
return JSONObject.parseObject(FileUtil.readUtf8String((filePath)));
}
public static void Print(String msg) {
System.out.println(DateTime.now() + " " + msg);
}
public static boolean isLinux() {
return System.getProperty("os.name").toLowerCase().contains("linux");
}
private static String connectionTestQuery = "select 1";
// 连接池中允许的最大连接数。缺省值10推荐的公式((core_count * 2) + effective_spindle_count)
private static int maxPoolSize = 10;
// 一个连接 idle 状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
private static long idleTimeoutMs = 600000;
private static long maxLifetimeMs = 1800000;
// 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生 SQLException 缺省:30秒
private static long connectionTimeoutMs = 30000;
public static HikariCpPlugin createHikariCpPlugin(String url, String username, String password, String driverClass) {
HikariCpPlugin hp = new HikariCpPlugin(url, username, password, driverClass);
hp.setConnectionTestQuery(connectionTestQuery);
hp.setConnectionTimeout(connectionTimeoutMs);
hp.setIdleTimeout(idleTimeoutMs);
hp.setMaxLifetime(maxLifetimeMs);
hp.setMaximumPoolSize(maxPoolSize);
return hp;
}
public static boolean isIP(String str) {
// IP地址的正则表达式
String ipPattern = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
return Pattern.matches(ipPattern, str);
}
public static boolean isDomain(String str) {
// 域名的正则表达式
String domainPattern = "^(?![0-9]+$)(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\\.[a-zA-Z]{2,})+$";
return Pattern.matches(domainPattern, str);
}
}