Commit 549bd709 authored by ZWT's avatar ZWT

都删了

parent 1c2c1d75
package pps.core.auth;
/**
* 基础认证Auth
*
* @author ZWT
* @date 2023/01/09
*/
public interface Auth {
/**
* 基础认证Auth
*
* @return {@link String}
*/
String getAuth();
}
\ No newline at end of file
package pps.core.auth;
import org.apache.commons.codec.binary.Base64;
import java.nio.charset.StandardCharsets;
/**
* 用户名密码认证
*
* @author ZWT
* @date 2023/01/09
*/
public class BasicAuth implements Auth {
private String username;
private String password;
public BasicAuth(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String getAuth() {
String auth = String.format("%s:%s", this.username, this.password);
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}
}
\ No newline at end of file
package pps.core.auth;
/**
* Bearer Token 认证
*
* @author ZWT
* @date 2023/01/09
*/
public class BearerAuth implements Auth {
private String token;
public BearerAuth(String token) {
this.token = token;
}
@Override
public String getAuth() {
return "Bearer " + this.token;
}
}
\ No newline at end of file
package pps.core.common.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import xstartup.annotation.XText;
import java.util.Date;
/**
* 基础
*
* @author ZWT
* @date 2023/08/25 15:46
*/
@Data
public class BaseModel {
@XText("ID")
@TableId(type = IdType.ASSIGN_UUID)
private String id;
@XText("是否删除(0_是;1_否)")
@TableField
private Integer isDeleted;
@XText("创建人ID")
@TableField
private String createById;
@XText("创建人名称")
@TableField
private String createByName;
@XText("创建时间")
@TableField
private Date createTime;
@XText("修改人ID")
@TableField
private String modifyById;
@XText("修改人名称")
@TableField
private String modifyByName;
@XText("修改时间")
@TableField
private Date modifyTime;
}
package pps.core.common.enums;
import xstartup.error.XError;
/**
* 业务错误
*
* @author ZWT
* @date 2023/09/12
*/
public enum BusinessError implements XError {
FileFormatError(2204, "文件格式有误,请检查上传文件格式!"),
UndiscoveredData(2205, "未发现数据,请检查后重新导入!"),
;
private int code;
private String text;
BusinessError(int code, String text) {
this.code = code;
this.text = text;
}
@Override
public int getCode() {
return code;
}
@Override
public String getText() {
return text;
}
}
package pps.core.common.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
/**
* 作业计划影响状态字典
*/
public enum TaskPlanTaskAffectDic implements DictEnum {
Affect_Upload(11, "", null),
Affect_Upload_False(0, "否", Affect_Upload),
Affect_Upload_True(1, "是", Affect_Upload),
Affect_Ability(12, "", null),
Affect_Ability_False(0, "否", Affect_Ability),
Affect_Ability_True(1, "是(影响联络站转供能力)", Affect_Ability),
Affect_Ability_True2(2, "是(含截断、限压、限流、干线截断阀旁通流程30min以上)", Affect_Ability),
Affect_Venting(13, "", null),
Affect_Venting_False(0, "否", Affect_Venting),
Affect_Venting_True(1, "管道放空", Affect_Venting),
Affect_Venting_True2(2, "全站放空", Affect_Venting),
Affect_Venting_True3(3, "站内局部放空", Affect_Venting),
Affect_SupplyGas(14, "", null),
Affect_SupplyGas_False(0, "否", Affect_SupplyGas),
Affect_SupplyGas_True(1, "影响重要不可中断用户供气(用户暂不同意)", Affect_SupplyGas),
Affect_SupplyGas_True3(2, "影响重要不可中断用户供气(用户已同意)", Affect_SupplyGas),
Affect_SupplyGas_True2(3, "影响可中断用户供气", Affect_SupplyGas),
Affect_Run(15, "", null),
Affect_Run_False(0, "否", Affect_Run),
Affect_Run_True(1, "影响在用机组", Affect_Run),
Affect_Run_True2(2, "影响备用机组", Affect_Run),
Affect_Communication(16, "", null),
Affect_Communication_False(0, "否", Affect_Communication),
Affect_Communication_True(1, "是", Affect_Communication),
Affect_Alarm(17, "", null),
Affect_Alarm_False(0, "否", Affect_Alarm),
Affect_Alarm_True(1, "是", Affect_Alarm),
Affect_Other(99, "未知", null),
;
@EnumValue
private Integer value;
private String desc;
private TaskPlanTaskAffectDic parent;
TaskPlanTaskAffectDic(Integer value, String desc, TaskPlanTaskAffectDic parent) {
this.desc = desc;
this.value = value;
this.parent = parent;
}
public static TaskPlanTaskAffectDic findByValue(Integer value) {
for (TaskPlanTaskAffectDic item : values()) {
if (item.getValue().equals(value)) {
return item;
}
}
return Affect_Other;
}
public static TaskPlanTaskAffectDic findBySubValue(Integer parentValue, Integer value) {
TaskPlanTaskAffectDic parentDic = Affect_Other;
for (TaskPlanTaskAffectDic item : values()) {
if (item.getValue().equals(parentValue)) {
parentDic = item;
}
}
for (TaskPlanTaskAffectDic item : values()) {
if (item.getParent() != null && item.getParent().equals(parentDic) && item.getValue().equals(value)) {
return item;
}
}
return Affect_Other;
}
public static TaskPlanTaskAffectDic findBySubDesc(Integer parentValue, String desc) {
TaskPlanTaskAffectDic parentDic = Affect_Other;
for (TaskPlanTaskAffectDic item : values()) {
if (item.getValue().equals(parentValue)) {
parentDic = item;
}
}
for (TaskPlanTaskAffectDic item : values()) {
if (item.getParent() != null && item.getParent().equals(parentDic) && item.getDesc().equals(desc)) {
return item;
}
}
return Affect_Other;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String getDesc() {
return desc;
}
public TaskPlanTaskAffectDic getParent() {
return parent;
}
}
package pps.core.common.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* @author lixueyan
* @date 2022/1/12 0012 10:46
*/
public class AESUtil {
private static String KEY = "abcdef0123456789"; // 长度必须是 16
private static String IV = "abcdef0123456789"; // 长度必须是 16
public static void main(String args[]) throws Exception {
String content = "dddddddddd";
//加密
String encrypted = encrypt(content, KEY, IV);
//解密
String decrypted = decrypt(encrypted, KEY, IV);
System.out.println("加密前:" + content);
System.out.println("加密后:" + encrypted);
System.out.println("解密后:" + decrypted);
}
public static String encrypt(String content) throws Exception {
return encrypt(content, KEY, IV);
}
/**
* 加密返回的数据转换成 String 类型
*
* @param content 明文
* @param key 秘钥
* @param iv 初始化向量是16位长度的字符串
* @return
* @throws Exception
*/
public static String encrypt(String content, String key, String iv) throws Exception {
// 将返回的加密过的 byte[] 转换成Base64编码字符串 !!!!很关键
return base64ToString(AES_CBC_Encrypt(content.getBytes(), key.getBytes(), iv.getBytes()));
}
public static String decrypt(String content) {
try {
return decrypt(content, KEY, IV);
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
/**
* 将解密返回的数据转换成 String 类型
*
* @param content Base64编码的密文
* @param key 秘钥
* @param iv 初始化向量是16位长度的字符串
* @return
* @throws Exception
*/
public static String decrypt(String content, String key, String iv) throws Exception {
// stringToBase64() 将 Base64编码的字符串转换成 byte[] !!!与base64ToString()配套使用
return new String(AES_CBC_Decrypt(stringToBase64(content), key.getBytes(), iv.getBytes()));
}
private static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
private static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes, byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
/**
* 字符串装换成 Base64
*/
public static byte[] stringToBase64(String key) throws Exception {
return Base64.decodeBase64(key.getBytes());
}
/**
* Base64装换成字符串
*/
public static String base64ToString(byte[] key) throws Exception {
return new Base64().encodeToString(key);
}
}
package pps.core.common.utils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.regex.Pattern;
/**
* Description:
* date: 2020/11/18 16:47
*
* @author zhujiangwei
*/
public class BigDecimalUtil {
/**
* 小数格式化
*
* @param obj 原数据
* @return
*/
public static String parseBigDecimal2Str(Object obj) {
return removeLastZero(String.valueOf(parseBigDecimal(obj, 10)));
}
/**
* 小数格式化
*
* @param obj 原数据
* @return
*/
public static double parseBigDecimal2Double(Object obj) {
return Double.parseDouble(removeLastZero(String.valueOf(parseBigDecimal(obj, 10))));
}
/**
* 小数格式化(保留固定的小数位数)
*
* @param obj 原数据
* @param num 保留小数的位数
* @return
*/
public static String parseBigDecimal2Str(Object obj, int num) {
return String.valueOf(parseBigDecimal(obj, num));
}
public static BigDecimal parseBigDecimal(Object obj, int num) {
if (obj == null) return BigDecimal.ZERO.setScale(num, BigDecimal.ROUND_HALF_UP);
BigDecimal org = null;
if (obj instanceof BigDecimal) {
org = (BigDecimal) obj;
} else {
String pattern = "([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])";
if (!Pattern.matches(pattern, String.valueOf(obj))) { //非数字字符串
org = BigDecimal.ZERO;
} else {
org = parseObj2BigDecimal(obj);
}
}
return org.setScale(num, BigDecimal.ROUND_HALF_UP);
}
/**
* 空值转换
*/
public static BigDecimal parseNull2Zero(BigDecimal org) {
return org == null ? BigDecimal.ZERO : org;
}
/**
* 去掉数字字符串末尾的0
*/
public static String removeLastZero(String org) {
if (org == null || "".equals(org.trim())) return "0";
//String pattern = "(-?([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9]))";
//if(!Pattern.matches(pattern,org)) return "0"; //非数字字符串
DecimalFormat format = new DecimalFormat("###############.##########");
return format.format(new Double(org));
}
public static BigDecimal parseObj2BigDecimal(Object obj) {
if (obj == null) return BigDecimal.ZERO;
String str = String.valueOf(obj).trim();
if (str.length() == 0) return BigDecimal.ZERO;
BigDecimal result = null;
try {
result = new BigDecimal(str);
} catch (Exception e) {
e.printStackTrace();
result = BigDecimal.ZERO;
}
return result;
}
}
package pps.core.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 转换工具类
*
* @author lixueyan
*/
public class ConvertUtils {
private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);
public static <T> T sourceToTarget(Object source, Class<T> target) {
if (source == null) {
return null;
}
T targetObject = null;
try {
targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetObject;
}
public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
if (sourceList == null) {
return null;
}
List targetList = new ArrayList<>(sourceList.size());
try {
for (Object source : sourceList) {
T targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
targetList.add(targetObject);
}
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetList;
}
}
package pps.core.common.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DynamicPwd {
public static String buildDynPwd() {
String str = new SimpleDateFormat("dd:HH:mm").format(new Date());
String[] items = str.split(":");
String pwd = String.format("%02d%02d%02d", Integer.parseInt(items[2]), Integer.parseInt(items[1]) + 1, Integer.parseInt(items[0]));
return pwd;
}
public static void main(String[] args) throws Exception {
String pwd = buildDynPwd();
System.out.println(pwd);
}
}
...@@ -8,28 +8,17 @@ public class ExceptionHelper { ...@@ -8,28 +8,17 @@ public class ExceptionHelper {
public static final String LINE_SEPERTOR = System.getProperty("line.separator"); public static final String LINE_SEPERTOR = System.getProperty("line.separator");
public static String getExceptionLogDetail(Throwable e) { public static String getExceptionLogDetail(Throwable e) {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer); PrintWriter printWriter = new PrintWriter(writer);
try { try {
e.printStackTrace(printWriter);
printWriter.flush(); printWriter.flush();
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("EXCEPTION:").append(e.getClass().getName()).append(LINE_SEPERTOR) stringBuilder.append("EXCEPTION:").append(e.getClass().getName()).append(LINE_SEPERTOR)
.append(" Message:").append(e.getMessage()).append(LINE_SEPERTOR) .append(" Message:").append(e.getMessage()).append(LINE_SEPERTOR)
.append(" Stack:").append(writer.toString()); .append(" Stack:").append(writer);
return stringBuilder.toString(); return stringBuilder.toString();
// return "EXCEPTION:" + e.getClass().getName() + lineSepertor
// + " Message:" + e.getMessage() + lineSepertor
// + " StackTrack:" + writer.toString();
} finally { } finally {
printWriter.close(); printWriter.close();
} }
} }
} }
package pps.core.common.utils;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* Description:模板导出工具类
* date: 2020/8/20 18:56
*
* @author zjw
*/
public class ExportExcelUtils {
public static void outputFileData(HttpServletResponse response, byte[] fileBuff, String fileName) throws Exception {
response.setContentType("application/octet-stream;charset=GBK");
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
OutputStream out = null;
try {
out = response.getOutputStream();
out.write(fileBuff);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
public static void outputFileData(byte[] fileBuff, String filePath) throws Exception {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
try {
out.write(fileBuff);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
/**
* 根据参数生成excel文件的二进制数据
*
* @param tempPath excel模板路径
* @param params 模板中相关参数的Map
* @return 生成文件的byte数组
*/
public static byte[] genSingleExcelFileData(String tempPath, Map<String, Object> params) {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(new File(tempPath));
} catch (FileNotFoundException e) {
System.out.println("-----" + tempPath + "文件未找到,导出空数据");
return null;
}
Context context = new Context();
if (params != null) {
for (String key : params.keySet()) {
context.putVar(key, params.get(key));
}
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(fileInputStream, buff);
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> funcs = new HashMap<String, Object>();
funcs.put("utils", new JxlsUtils()); //添加自定义功能
evaluator.getJexlEngine().setFunctions(funcs);
jxlsHelper.processTemplate(context, transformer);
} catch (IOException e) {
e.printStackTrace();
}
return buff.toByteArray();
}
/**
* 根据参数生成excel文件的二进制数据
*
* @param inputStream excel模板路径
* @param params 模板中相关参数的Map
* @return 生成文件的byte数组
*/
public static byte[] genSingleExcelFileData(InputStream inputStream, Map<String, Object> params) {
Context context = new Context();
if (params != null) {
for (String key : params.keySet()) {
context.putVar(key, params.get(key));
}
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(inputStream, buff);
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> funcs = new HashMap<String, Object>();
funcs.put("utils", new JxlsUtils()); //添加自定义功能
evaluator.getJexlEngine().setFunctions(funcs);
jxlsHelper.processTemplate(context, transformer);
} catch (IOException e) {
e.printStackTrace();
}
return buff.toByteArray();
}
}
package pps.core.common.utils;
/**
* @Description 雪花算法
*/
public class IdWorker {
private final long twepoch = 1288834974657L;
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long sequenceBits = 12L;
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public static void main(String[] args) {
IdWorker idWorker = new IdWorker(0, 0);
for (int i = 0; i < 100; i++) {
long id = idWorker.nextId();
System.out.println(id);
}
}
/**
* 获得下一个ID (该方法是线程安全的)
*
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
//如果毫秒相同,则从0递增生成序列号
sequence = (sequence + 1) & sequenceMask;
//毫秒内序列溢出
if (sequence == 0) {
//阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
//上次生成ID的时间截
lastTimestamp = timestamp;
//移位并通过或运算拼到一起组成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (workerId << workerIdShift) //
| sequence;
}
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
}
\ No newline at end of file
package pps.core.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import java.util.List;
public class ImportExcelUtils {
/**
* 判断Excel当前行是否为空
*
* @param row
* @return
*/
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != CellType.BLANK)
return false;
}
return true;
}
/**
* 数据非空校验
* 规则:titles 中 含有 * 的 会进行非空校验
*
* @param row
* @param titles
* @return
*/
public static String checkData(Row row, List<String> titles) {
DataFormatter formatter = new DataFormatter();
for (int i = 0; i < titles.size(); i++) {
Cell cell = row.getCell(i);
if (titles.get(i).startsWith("*") && StringUtils.isBlank(formatter.formatCellValue(cell))) {
String msg = String.format("第%s行 %s 不能为空", (i + 1), titles.get(i).replace("*", ""));
return msg;
}
}
return null;
}
}
package pps.core.common.utils;
import pps.core.common.enums.TaskPlanTaskAffectDic;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Description:
* date: 2021/3/31 16:15
*
* @author zhujiangwei
*/
public class JxlsUtils {
public static void main(String[] args) {
String as = "ss";
System.out.println(as);
}
public String dateFormat(Date date) {
return this.dateFormat(date, "yyyy-MM-dd");
}
public String dateFormat(Date date, String pattern) {
if (date == null) {
return "";
}
try {
SimpleDateFormat dateFmt = new SimpleDateFormat(pattern);
return dateFmt.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public double bigDecimalFormat(Object data) {
return bigDecimalFormat(data, 2);
}
public double bigDecimalFormat(Object data, int num) {
if (data == null) {
return 0d;
}
try {
if (data instanceof BigDecimal) {
return BigDecimalUtil.parseBigDecimal(data, num).doubleValue();
} else if (data instanceof String) {
return BigDecimalUtil.parseBigDecimal(new BigDecimal((String) data), num).doubleValue();
} else {
return BigDecimalUtil.parseBigDecimal(new BigDecimal(data.toString()), num).doubleValue();
}
} catch (Exception e) {
e.printStackTrace();
}
return 0d;
}
public String enumFormat(Integer subValue, Integer parentValue) {
if (subValue == null) {
return "未知";
}
TaskPlanTaskAffectDic bySubValue = TaskPlanTaskAffectDic.findBySubValue(parentValue, subValue);
return bySubValue.getDesc();
}
}
package pps.core.common.utils;
import java.security.MessageDigest;
/**
* @author lixueyan
* @date 2022/11/11 0011 16:11
*/
public class MD5Util {
private static byte[] md5(String s) {
MessageDigest algorithm;
try {
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes("UTF-8"));
byte[] messageDigest = algorithm.digest();
return messageDigest;
} catch (Exception e) {
System.out.println("MD5 Error..." + e.getMessage());
}
return null;
}
private static final String toHex(byte hash[]) {
if (hash == null) {
return null;
}
StringBuffer buf = new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++) {
if ((hash[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString(hash[i] & 0xff, 16));
}
return buf.toString();
}
public static String hash(String s) {
try {
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
} catch (Exception e) {
System.out.println("not supported charset..." + e.getMessage());
return s;
}
}
/**
* 对密码按照用户名,密码,盐进行加密
*
* @param username 用户名
* @param password 密码
* @param salt 盐
* @return
*/
public static String encryptPassword(String username, String password, String salt) {
return MD5Util.hash(username + password + salt);
}
/**
* 对密码按照密码,盐进行加密
*
* @param password 密码
* @param salt 盐
* @return
*/
public static String encryptPassword(String password, String salt) {
return MD5Util.hash(password + salt);
}
/**
* 对密码按照密码,盐进行加密
*
* @param password 密码
* @return
*/
public static String encryptPassword(String password) {
return MD5Util.hash(password);
}
}
package pps.core.common.utils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import xstartup.base.util.XDateUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author lixueyan
* @date 2022/8/9 0009 15:38
*/
public class MapUtil {
private static Map<Class, List<Method>> classMethodMap = new ConcurrentHashMap<Class, List<Method>>();
private static Map<Class<?>, Map<String, Method>> getMethods = new HashMap<Class<?>, Map<String, Method>>();
public static Map<String, Object> objectToMapObject(Object bean) {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Method> fields = recursiveGetMethodMap(bean);
for (String fieldName : fields.keySet()) {
Method method = fields.get(fieldName);
if (method == null) continue;
JsonIgnore jsonIgnore = method.getAnnotation(JsonIgnore.class);
if (jsonIgnore != null)
continue;
Object value = invokeMethod(bean, method);
Class<?> returnType = method.getReturnType();
if (returnType != null && returnType == Date.class && value != null) {
map.put(fieldName, XDateUtils.getDateTimeString((Date) value));
} else {
map.put(fieldName, value);
}
}
return map;
}
public static Map<String, Object> objectToMapNotContainNull(Object bean) {
Map<String, Object> map = objectToMapObject(bean);
Map<String, Object> mapResult = new HashMap<String, Object>();
for (String key : map.keySet()) {
if (map.get(key) != null) {
mapResult.put(key, map.get(key));
}
}
return mapResult;
}
private static Map<String, Method> recursiveGetMethodMap(Object obj) {
return recursiveGetMethodMap(obj.getClass());
}
private static Object invokeMethod(Object obj, Method method, Object... args) {
if (method == null)
return null;
try {
return method.invoke(obj, args);
} catch (Exception e) {
}
return null;
}
private static Map<String, Method> recursiveGetMethodMap(Class<?> _class) {
Map<String, Method> methodMap = getMethods.get(_class);
if (methodMap == null) {
synchronized (getMethods) {
if ((methodMap = getMethods.get(_class)) == null) {
methodMap = new HashMap<String, Method>();
List<Method> methodList = getDeclaredMethods(_class);
for (Method method : methodList) {
String methodName = method.getName();
int modifiers = method.getModifiers();
if (!Modifier.isPublic(modifiers))
continue;
if (Modifier.isStatic(modifiers))
continue;
if (method.getParameterCount() != 0)
continue;
if (method.getDeclaringClass() == Object.class)
continue;
if (methodName.startsWith("get") && methodName.length() > 3) {
String propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4, methodName.length());
methodMap.put(propertyName, method);
}
}
getMethods.put(_class, methodMap);
}
}
}
return methodMap;
}
private static List<Method> getDeclaredMethods(Class<?> clazz) {
if (classMethodMap.containsKey(clazz))
return classMethodMap.get(clazz);
synchronized (classMethodMap) {
if (classMethodMap.containsKey(clazz))
return classMethodMap.get(clazz);
List<Method> methodList = Arrays.asList(clazz.getMethods());
classMethodMap.put(clazz, methodList);
return methodList;
}
}
public static <T> T mapToObj(Map<String, Object> map, Class<T> clz) throws Exception {
Object obj = clz.newInstance();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, objToValue(map.get(field.getName()), field.getType()));
}
return (T) obj;
}
public static <T> List<T> mapToList(List<Map<String, Object>> mapList, Class<T> clz) throws Exception {
List<T> list = new ArrayList<>();
for (Map<String, Object> map : mapList) {
list.add((T) mapToObj(map, clz));
}
return list;
}
public static Object objToValue(Object o, Class c) {
if (o == null || StringUtils.isBlank(String.valueOf(o))) {
if (c == String.class) {
return o;
} else {
return null;
}
}
if (c == Integer.class) {
if (o instanceof Long) {
return o;
}
return Integer.parseInt(String.valueOf(o));
} else if (c == Float.class) {
return Float.parseFloat(String.valueOf(o));
} else if (c == Double.class) {
return Double.parseDouble(String.valueOf(o));
} else if (c == BigDecimal.class) {
return new BigDecimal(String.valueOf(o));
} else if (c == Boolean.class) {
if (o != null) {
if ((Boolean.parseBoolean(String.valueOf(o))) == true)
return 1;
else
return 0;
} else {
return null;
}
} else if (c == Date.class) {
return XDateUtils.parse(String.valueOf(o));
} else {
return o;
}
}
}
package pps.core.common.utils;
public class NumUtils {
public static void main(String[] args) {
System.out.println(digitUppercase(11120.1));
}
/**
* 数字金额大写转换
*
* @param n 数字
* @return 中文大写数字
*/
public static String digitUppercase(double n) {
//String[] fraction = {"角", "分"};
String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
String[][] unit = {{"", "万", "亿"}, {"", "拾", "佰", "仟"}};
String head = n < 0 ? "负" : "";
n = Math.abs(n);
String s = "";
// for (int i = 0; i < fraction.length; i++) {
// s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
// }
if (s.length() < 1) {
//s = "整";
}
int integerPart = (int) Math.floor(n);
for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
String p = "";
for (int j = 0; j < unit[1].length && n > 0; j++) {
p = digit[integerPart % 10] + unit[1][j] + p;
integerPart = integerPart / 10;
}
s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
}
return head + s.replaceAll("(零.)*零", "").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零整");
}
public static String getCode() {
return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
}
}
package pps.core.common.utils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SqlFilter {
public static final List<String> BAD_KEYWORDS = Arrays.asList(
"select", "update", "delete", "insert", "truncate"
, "and", "or", "char", "into", "substr"
, "ascii", "declare", "exec", "count", "master"
, "drop", "execute", "table", "sitename", "xp_cmdshell"
, "like", "from", "grant", "use", "group_concat"
, "column_name", "information_schema.columns", "table_schema"
, "union", "where", "order", "by", "add"
, "all", "alter", "any", "as", "create"
, "in", "join", "inner", "not", "set"
, "--", "--;", ";--");
public static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s+");
public static final Splitter SPLITTER_WHITESPACE = Splitter.on(PATTERN_WHITESPACE);
public static final Joiner JOINER_WHITESPACE = Joiner.on(" ");
public static final Pattern BAD_FORM_PATTERN_KEYWORDS = Pattern.compile("^(" + String.join("|", BAD_KEYWORDS) + ")$", Pattern.CASE_INSENSITIVE);
public static final String BAD_FORM_PATTERN_STR = "'|\\*|/|\\\\|--.*";//过滤掉的sql关键字,特殊字符前面需要加\\进行转义
public static final Pattern BAD_FORM_PATTERN = Pattern.compile(BAD_FORM_PATTERN_STR, Pattern.CASE_INSENSITIVE);
public static final String filterValue(String original) {
if (Strings.isNullOrEmpty(original)) {
return original;
}
original = original.trim();
if (Strings.isNullOrEmpty(original)) {
return original;
}
if (!PATTERN_WHITESPACE.matcher(original).find()) {
//没有空格
return filterValueNoSpace(original);
}
List<String> keywords = SPLITTER_WHITESPACE.splitToList(original);
List<String> fixedKeywords = new ArrayList<String>(keywords.size());
keywords.forEach(keyword -> {
String fixed = filterValueNoSpace(keyword);
if (!Strings.isNullOrEmpty(fixed)) {
fixedKeywords.add(fixed);
}
});
if (fixedKeywords.isEmpty()) {
return "";
}
return JOINER_WHITESPACE.join(fixedKeywords);
}
private static String filterValueNoSpace(String original) {
//关键字查询
Matcher matcher = BAD_FORM_PATTERN_KEYWORDS.matcher(original);
if (matcher.find()) {
return "";
}
Matcher matcher1 = BAD_FORM_PATTERN.matcher(original);
if (matcher1.find()) {
original = matcher1.replaceAll("");
}
return original;
}
}
package pps.core.common.utils;
import java.math.BigDecimal;
/**
* 到大小数函数
*
* @author ZWT
* @date 2024/06/03
*/
@FunctionalInterface
public interface ToBigDecimalFunction<T> {
/**
* 应用为大小数
*
* @param value 价值
* @return {@link BigDecimal }
*/
BigDecimal applyAsBigDecimal(T value);
}
\ No newline at end of file
package pps.core.common.utils;
import org.apache.poi.ss.usermodel.DateUtil;
import java.util.Calendar;
/**
* @author lixueyan
* @date 2023/2/9 0009 13:41
*/
public class XSSFDateUtil extends DateUtil {
protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment