package com.txqc.mlk.util;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.web.multipart.MultipartFile;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 工具方法类
*/
public class Kit {
/**
* 15位身份证号
*/
private static final Integer FIFTEEN_ID_CARD = 15;
/**
* 18位身份证号
*/
private static final Integer EIGHTEEN_ID_CARD = 18;
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static boolean isValidCard18(String idcard) {
if (EIGHTEEN_ID_CARD != idcard.length()) {
return false;
}
return true;
}
/**
* 验证15位身份编码是否合法
*
* @param idcard 身份编码
* @return 是否合法
*/
public static boolean isValidCard15(String idcard) {
if (FIFTEEN_ID_CARD != idcard.length()) {
return false;
}
return true;
}
private static <T> void setFieldValue(T rowData, Field field, Object value) throws IllegalAccessException {
if (field.getType() == int.class || field.getType() == Integer.class) {
field.set(rowData, value);
} else if (field.getType() == long.class || field.getType() == Long.class) {
field.set(rowData, value);
} else if (field.getType() == double.class || field.getType() == Double.class) {
field.set(rowData, value);
} else if (field.getType() == String.class) {
field.set(rowData, String.valueOf(value));
} else if (field.getType() == LocalDateTime.class) {
field.set(rowData, LocalDateTime.parse(String.valueOf(value), dateTimeFormatter));
}
}
private static Object getCellValue(Cell cell) {
CellType cellType = cell.getCellType();
Object cellValue = null;
if (cellType == CellType._NONE) {
} else if (cellType == CellType.NUMERIC) {
// 数值型
if (DateUtil.isCellDateFormatted(cell)) {
// 日期类型
Date d = cell.getDateCellValue();
cellValue = dateTimeFormatter.format(LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault()));
} else {
double numericCellValue = cell.getNumericCellValue();
BigDecimal bdVal = new BigDecimal(numericCellValue);
if ((bdVal + ".0").equals(Double.toString(numericCellValue))) {
// 整型
cellValue = bdVal;
} else if (String.valueOf(numericCellValue).contains("E10")) {
// 科学记数法
cellValue = new BigDecimal(numericCellValue).toPlainString();
} else {
// 浮点型
cellValue = numericCellValue;
}
}
} else if (cellType == CellType.STRING) {
// 字符串型
cellValue = cell.getStringCellValue();
} else if (cellType == CellType.FORMULA) {
// 公式型
} else if (cellType == CellType.BLANK) {
// 空值
} else if (cellType == CellType.BOOLEAN) {
// 布尔型
cellValue = cell.getBooleanCellValue();
} else if (cellType == CellType.ERROR) {
// 错误
cellValue = cell.getErrorCellValue();
}
return cellValue;
}
/**
* 根据身份编号获取年龄
*
* @param idCard 身份编号
* @return 年龄
*/
public static int getAgeByIdCard(String idCard) {
int iAge = 0;
Calendar cal = Calendar.getInstance();
String year = idCard.substring(6, 10);
int iCurrYear = cal.get(Calendar.YEAR);
iAge = iCurrYear - Integer.valueOf(year);
return iAge;
}
/**
* 获取出生日期 yyyy年MM月dd日
*
* @param IDCard
* @return
*/
public static String getBirthByIdCard(String IDCard) {
String birthday = "";
String year = "";
String month = "";
String day = "";
if (isNotEmpty(IDCard)) {
//15位身份证号
if (IDCard.length() == FIFTEEN_ID_CARD) {
// 身份证上的年份(15位身份证为1980年前的)
year = "19" + IDCard.substring(6, 8);
//身份证上的月份
month = IDCard.substring(8, 10);
//身份证上的日期
day = IDCard.substring(10, 12);
//18位身份证号
} else if (IDCard.length() == EIGHTEEN_ID_CARD) {
// 身份证上的年份
year = IDCard.substring(6).substring(0, 4);
// 身份证上的月份
month = IDCard.substring(10).substring(0, 2);
//身份证上的日期
day = IDCard.substring(12).substring(0, 2);
}
birthday = year + "-" + month + "-" + day;
}
return birthday;
}
/**
* 根据身份编号获取生日年
*
* @param idCard 身份编号
* @return 生日(yyyy)
*/
public static Short getYearByIdCard(String idCard) {
return Short.valueOf(idCard.substring(6, 10));
}
/**
* 根据身份编号获取生日月
*
* @param idCard 身份编号
* @return 生日(MM)
*/
public static Short getMonthByIdCard(String idCard) {
return Short.valueOf(idCard.substring(10, 12));
}
/**
* 根据身份编号获取生日天
*
* @param idCard 身份编号
* @return 生日(dd)
*/
public static Short getDateByIdCard(String idCard) {
return Short.valueOf(idCard.substring(12, 14));
}
/**
* 根据身份编号获取性别
*
* @param idCard 身份编号
* @return 性别(M - 男 , F - 女 , N - 未知)
*/
public static String getGenderByIdCard(String idCard) {
String sGender = "未知";
String sCardNum = idCard.substring(16, 17);
if (Integer.parseInt(sCardNum) % 2 != 0) {
sGender = "1";//男
} else {
sGender = "2";//女
}
return sGender;
}
/**
* 去掉null
*
* @param source
* @return
*/
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for (java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue != null) {
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
/**
* 判空方法
*
* @param obj
* @return
*/
public static boolean isEmpty(Object obj) {
if (obj != null && !"".equals(obj.toString())) {
if (obj instanceof List) {
if (((List<?>) obj).size() == 0) {
return true;
}
}
return false;
}
return true;
}
/**
* 判不为空方法
*
* @param obj
* @return
*/
public static boolean isNotEmpty(Object obj) {
if (obj != null && !"".equals(obj.toString())) {
if (obj instanceof List) {
if (((List<?>) obj).size() == 0) {
return false;
}
}
return true;
}
return false;
}
/**
* 验证文件后缀是否符合要求
*
* @param fileType 后缀类型数组(如:xlsx/pdf/docx)
* @param file
* @return
*/
public static R verifyFileLegal(String[] fileType, MultipartFile file) {
if (isEmpty(file)) {
return R.fail("未获取到文件");
} else if (isNotEmpty(file)) {
String fileName = file.getResource().getFilename();
if (isNotEmpty(fileName) && isNotEmpty(fileType)) {
String[] fileNames = fileName.split("\\.");
if (isNotEmpty(fileNames) && fileNames.length > 0) {
if (!Arrays.asList(fileType).contains(fileNames[1])) {
return R.fail("文件类型不匹配");
}
}
}
}
return R.ok();
}
/**
* String转换为LocalDateTime
*
* @param timeString
* @return
*/
public static LocalDateTime getStringToLocalDateTime(String timeString) {
if (isNotEmpty(timeString)) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(timeString, df);
}
return null;
}
/**
* String转换为LocalDate
*
* @param timeString
* @return
*/
public static LocalDate getStringToLocalDate(String timeString) {
if (isNotEmpty(timeString)) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDate.parse(timeString, df);
}
return null;
}
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
if (value == null) {
value = "";
}
map.put(fieldName, value);
}
return map;
}
private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy年MM月dd日",
"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyyMMdd",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm", "yyyy.MM.dd HH:mm:ss"};
/**
* 校验输入的字符串是否为日期格式
*
* @param str
* @return
*/
public static boolean verifyDate(String str) {
boolean convertSuccess = true;
try {
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
DateUtils.parseDate(str, parsePatterns);
} catch (ParseException e) {
// e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
convertSuccess = false;
}
return convertSuccess;
}
/**
* 求差集
* 求List1中有的但是List2中没有的元素
*/
public static List<String> subList2(List<String> list1, List<String> list2) {
Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
return list1.parallelStream().filter(str -> {
return !tempMap.containsKey(str);
}).collect(Collectors.toList());
}
public static boolean isBlank(String temp) {
boolean returnValue = true;
if (temp != null) {
returnValue = temp.matches("\\s*");
}
return returnValue;
}
public static String nullToStr(String temp) {
if (temp == null) {
temp = "";
}
return temp;
}
/**
* sql注入
*
* @param str
* @return
*/
public static boolean sqlValidate(String str) {
str = str.toLowerCase();//统一转为小写
String badStr = "'|and|exec|execute|insert|drop|" +
"char|declare|sitename|net user|xp_cmdshell|or|like'|create|" +
"table|from|grant|group_concat|column_name|" +
"information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|" +
"chr|mid|master|truncate|";//过滤掉的sql关键字,可以手动添加
String[] badStrs = badStr.split("\\|");
for (int i = 0; i < badStrs.length; i++) {
if (str.indexOf(badStrs[i]) >= 0) {
return false;
}
}
return true;
}
/**
* Date转LocalDate
*
* @param date
* @return
*/
public static LocalDate date2LocalDate(Date date) {
if (null == date) {
return null;
}
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
/**
* LocalDate转Date
*
* @param localDate
* @return
*/
public static Date localDate2Date(LocalDate localDate) {
if (null == localDate) {
return null;
}
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
}
工具类-身份证验证,获取年龄,去掉对象空属性,判空
猜你喜欢
转载自blog.csdn.net/ZHOU_VIP/article/details/130476022
今日推荐
周排行