Commit 1c8b3d6c authored by wangquan  wangquan's avatar wangquan wangquan
Browse files

22

parent 440ddd1b
package com.zxr.demos.common.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestResut {
private Integer resultCode;
private String msg;
}
package com.zxr.demos.common.response;
import com.zxr.demos.common.enums.UdspApiResultCode;
import com.zxr.demos.common.enums.ResultCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Objects;
/**
* @author xiaoyu
* 吉利接口响应结果
* @since 2023/8/16
*/
@Data
@AllArgsConstructor
public class UdspApiCommonResult<T> {
/**
* 200表示请求成功,其他表示失败
*/
private int code;
private String message;
private Boolean success;
private T data; // 使用泛型T来表示data字段的类型
public UdspApiCommonResult() {
}
private static <T> UdspApiCommonResult<T> newInstance(Integer code, String message, T data) {
UdspApiCommonResult<T> result = new UdspApiCommonResult<>();
result.setMessage(message);
result.setCode(code);
result.setData(data);
result.setSuccess(Objects.equals(code, UdspApiResultCode.SUCCESS.getCode()));
return result;
}
public static <T> UdspApiCommonResult<T> fail(ResultCode status) {
return newInstance(status.getCode(), status.getMessage(), null);
}
public static <T> UdspApiCommonResult<T> success(T data) {
return newInstance(UdspApiResultCode.SUCCESS.getCode(), UdspApiResultCode.SUCCESS.getMessage(), data);
}
}
package com.zxr.demos.common.response;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
@Data
public class UdspCarSeriesListResult {
/**
* 车型名称
*/
@JSONField(name = "modelName")
private String modelName;
/**
* 车型代码
*/
@JSONField(name = "code")
private String code;
}
package com.zxr.demos.common.response;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class UdspPartsResult {
/**
* 自增id
*/
@JSONField(name = "id")
private Long id;
/**
* 车系名称
*/
@JSONField(name = "modelName")
private String modelName;
/**
* 零件代码
*/
@JSONField(name = "partsCode")
private String partsCode;
/**
* 零件英文名称
*/
@JSONField(name = "partsEname")
private String partsEname;
/**
* 零件中文名称
*/
@JSONField(name = "partsCname")
private String partsCname;
/**
* 经销商代码
*/
@JSONField(name = "dealerCode")
private String dealerCode;
/**
* 单价
*/
@JSONField(name = "amt")
private BigDecimal amt;
}
package com.zxr.demos.common.response;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class UdspWorkHourResult {
/**
* 自增id
*/
@JSONField(name = "id")
private Long id;
/**
* 车型名称
*/
@JSONField(name = "modelName")
private String modelName;
/**
* 工时代码
*/
@JSONField(name = "taskCode")
private String taskCode;
/**
* 工时名称
*/
@JSONField(name = "taskName")
private String taskName;
/**
* 工时,以小时为单位
*/
@JSONField(name = "taskTime")
private BigDecimal taskTime;
}
package com.zxr.demos.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.codec.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* AES 加密
*
* @author bjliuqiang
*/
public class AesEncryptUtil {
//使用AES-128-CBC加密模式,key需要为16位,key和iv可以相同!
// private static String KEY = "1234567890adbcde";
// private static String IV = "1234567890hjlkew";
private static String KEY = "CE33603303969986";
private static String IV = "CE33603303969986";
/**
* 加密方法
*
* @param data 要加密的数据
* @param key 加密key
* @param iv 加密iv
* @return 加密的结果
* @throws Exception
*/
public static String encrypt(String data, String key, String iv) {
try {
if (data == null) {
return data;
}
//"算法/模式/补码方式"NoPadding PkcsPadding
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return Base64.encodeToString(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 解密方法
*
* @param data 要解密的数据
* @param key 解密key
* @param iv 解密iv
* @return 解密的结果
* @throws Exception
*/
public static String desEncrypt(String data, String key, String iv) {
try {
byte[] encrypted1 = Base64.decode(data);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 使用默认的key和iv加密
*
* @param data
* @return
* @throws Exception
*/
public static String encrypt(String data) {
return encrypt(data, KEY, IV);
}
/**
* 使用默认的key和iv解密
*
* @param data
* @return
* @throws Exception
*/
public static String desEncrypt(String data) {
return desEncrypt(data, KEY, IV);
}
private static final int keyMax = 16;
private static final String charSeq = "nFslTb67oRHXwqGk";
/**
* 使用厂商APPID+venderCode加密
*
* @param data
* @param appId
* @param venderCode
* @return
* @throws Exception
*/
public static String encryptPer(String data, String appId, String venderCode) {
if (StringUtils.isBlank(appId)) {
return data;
}
if (appId.length() < keyMax) {
appId = appId + charSeq.substring(appId.length(), keyMax);
}
String key = appId.substring(0, keyMax);
if (StringUtils.isNotBlank(venderCode) && venderCode.length() < keyMax) {
venderCode = venderCode + charSeq.substring(venderCode.length(), keyMax);
}
String iv = StringUtils.isBlank(venderCode) ? key : venderCode.substring(0, keyMax);
return encrypt(data, key, iv);
}
public static String desEncryptPer(String data, String appId, String venderCode) {
if (StringUtils.isBlank(appId)) {
return data;
}
if (appId.length() < keyMax) {
appId = appId + charSeq.substring(appId.length(), keyMax);
}
String key = appId.substring(0, keyMax);
if (StringUtils.isNotBlank(venderCode) && venderCode.length() < keyMax) {
venderCode = venderCode + charSeq.substring(venderCode.length(), keyMax);
}
String iv = StringUtils.isBlank(venderCode) ? key : venderCode.substring(0, keyMax);
return desEncrypt(data, key, iv);
}
public static void main(String[] args) throws Exception {
String test1 = "北京市通州区马驹桥镇兴贸三街珠江四季悦城1号院1号楼二单元814室";
String test = new String(test1.getBytes(), "UTF-8");
String data = null;
String key = "1234567812345678";
String iv = "abcdabcdabcdabcd";
data = encryptPer(test, key, iv);
System.out.println("数据:" + test);
System.out.println("加密:" + data);
String en = "qV1pst837BvF4gIDmnGFy+2QWXHPCgRWVWT8TSD72dBvNBrJWLF9jLafGnRlsuiyM0sPwUFJz0wY2AZKRvatCm8LD+MD/hGpJjZzqybblXmWaoS95+t5XpS5uOxBMksw";
String jiemi = desEncryptPer(en, key, iv).trim();
System.out.println("解密:" + jiemi);
key = "12345678123456781";
iv = "abcdabcdabcdabcd1";
data = encryptPer(test, key, iv);
System.out.println("数据:" + test);
System.out.println("加密:" + data);
en = "qV1pst837BvF4gIDmnGFy+2QWXHPCgRWVWT8TSD72dBvNBrJWLF9jLafGnRlsuiyM0sPwUFJz0wY2AZKRvatCm8LD+MD/hGpJjZzqybblXmWaoS95+t5XpS5uOxBMksw";
jiemi = desEncryptPer(en, key, iv).trim();
System.out.println("解密:" + jiemi);
key = "1234567812";
iv = "abcdabcdabcda";
data = encryptPer(test, key, iv);
System.out.println("数据:" + test);
System.out.println("加密:" + data);
en = "nJ7tK5PoTAYcpLMv7KxNhnyjbMWY/IWe4SNK5EXdK4StS2w1SVV8deAU5sEJnWR2qU+vvI4lQTUdJWymDo4fYW/J/fVhgGzDJeCvvoxFVG2S3e07hx32neKH/hDYbuCW";
jiemi = desEncryptPer(en, key, iv).trim();
System.out.println("解密:" + jiemi);
key = "1234567812";
iv = "";
data = encryptPer(test, key, iv);
System.out.println("数据:" + test);
System.out.println("加密:" + data);
en = "1L3lzKvpk/7te4bFZlAd0wpkGlp0cX9v7J2ly2I0Kzw4f9NWjG2AQY+cyb3+JEJBBK1UZJ65MbMXvUEYnj60l/EvvyyGi6NxFGbAUVG+61fztXvTUBeFqlM2vfc1Xs8B";
jiemi = desEncryptPer(en, key, iv).trim();
System.out.println("解密:" + jiemi);
key = "3c8a354e13c448eb9820a169acce1128";
iv = "";
en = "pbDs4su3ToCvHOTEjRZi0R0fsXwF/BZLN9S5x041y3f4ojWDvaSK97TIBmEX6kWt";
jiemi = desEncryptPer(en, key, iv).trim();
System.out.println("解密:" + jiemi);
key = "yihubiying2024";
iv = "8851502741";
en = "cuvGrHSLtbTcmlB4a/3SlQ==";
jiemi = desEncryptPer(en, key, iv).trim();
System.out.println("解密:" + jiemi);
}
// /**
// * 测试
// */
// public static void main(String args[]) throws Exception {
//
// String test1 = "qwe123!@#";
// String test = new String(test1.getBytes(), "UTF-8");
// String data = null;
// String key = KEY;
// String iv = IV;
// // /g2wzfqvMOeazgtsUVbq1kmJawROa6mcRAzwG1/GeJ4=
// data = encrypt(test, key, iv);
// System.out.println("数据:" + test);
// System.out.println("加密:" + data);
//
// String en = "6MhDTUIZuer1Bwxxu7BVdg==";
// String jiemi = desEncrypt(en, key, iv).trim();
// System.out.println("解密:" + jiemi);
//
//
// }
}
package com.zxr.demos.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author 花荣
* @date created in 2021/3/24 5:49 下午
* @project shb-paas
* @Modified by
* @Description 日期时间工具类
*/
@Slf4j
public class DateUtils {
public static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT_YMD = "yyyy-MM-dd";
public static final String DATE_YMD = "yyMMdd";
public static final long ND = 1000 * 24 * 60 * 60;
public static final long NH = 1000 * 60 * 60;
public static final long NM = 1000 * 60;
public static String getCurrentTime() {
SimpleDateFormat sFormat = new SimpleDateFormat(DATE_FORMAT_DEFAULT);
Calendar c1 = Calendar.getInstance();
return sFormat.format(c1.getTime());
}
public static String getCurrentDay() {
SimpleDateFormat sFormat = new SimpleDateFormat(DATE_FORMAT_YMD);
Calendar c1 = Calendar.getInstance();
return sFormat.format(c1.getTime());
}
public static Date stringToDate(String dateStr) throws ParseException {
SimpleDateFormat sFormat = new SimpleDateFormat(DATE_FORMAT_YMD);
return sFormat.parse(dateStr);
}
public static Date stringToDateTime(String dateStr) throws ParseException {
SimpleDateFormat sFormat = new SimpleDateFormat(DATE_FORMAT_DEFAULT);
return sFormat.parse(dateStr);
}
public static LocalDateTime stringToLocalDateTime(String dateStr) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(dateStr, df);
}
public static Long stringToDateTimeMillis(String dateStr) throws ParseException {
if (!StringUtils.isEmpty(dateStr)) {
String[] tmpArr = dateStr.split(" ");
List<String> tmpList = Arrays.asList(tmpArr).stream().filter(str -> !StringUtils.isEmpty(str)).map(str -> str.replace("/", "-")).collect(Collectors.toList());
dateStr = tmpList.get(0) + " " + tmpList.get(1);
Date dateTime = stringToDateTime(dateStr);
return dateTime != null ? dateTime.getTime() : null;
} else {
return null;
}
}
public static Date getCurrentDayDate(){
try {
return stringToDate(getCurrentDay());
} catch (ParseException e) {
log.error("ERROR:", e);
return null;
}
}
public static Date getCurrentDayTime(){
try {
return stringToDate(getCurrentTime());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* yyyy-mm-dd
*
* @param appointBeginDate
* @return
*/
public static String dateToString(Date appointBeginDate) {
SimpleDateFormat sFormat = new SimpleDateFormat(DATE_FORMAT_YMD);
return sFormat.format(appointBeginDate);
}
/**
* yyyy-mm-dd
*
* @param appointBeginDate
* @return
*/
public static String dateToString2(Date appointBeginDate) {
SimpleDateFormat sFormat = new SimpleDateFormat(DATE_FORMAT_DEFAULT);
return sFormat.format(appointBeginDate);
}
/**
* yyyy-mm-dd
*
* @param appointBeginDate
* @return
*/
public static String dateToString(Date appointBeginDate, String format) {
SimpleDateFormat sFormat = new SimpleDateFormat(format);
return sFormat.format(appointBeginDate);
}
/**
* 获取两个时间的时间差
* @param start
* @param end
* @param index
* @return
*/
public static Integer getTimeDifference(Date start,Date end,String index){
if(start == null || end == null || StringUtils.isEmpty(index)){
return null;
}
Integer result = 0;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(start);
c2.setTime(end);
if("year".equals(index)){
result = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
}else if("month".equals(index)){
result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
}else if("day".equals(index)){
Calendar sCalendar = Calendar.getInstance();
Calendar eCalendar = Calendar.getInstance();
sCalendar.setTime(start);
eCalendar.setTime(end);
int days = 0;
while (sCalendar.before(eCalendar)) {
days++;
sCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
//int days = (int) ((end.getTime() - start.getTime()) / (1000*3600*24));
result = days;
} else if ("hour".equals(index)) {
long diff = end.getTime() - start.getTime();
result = (int) (diff / (60 * 60 * 1000));
//result = c2.get(Calendar.HOUR) - c1.get(Calendar.HOUR);
} else if ("minute".equals(index)) {
//result = c2.get(Calendar.MINUTE) - c1.get(Calendar.MINUTE);
long diff = end.getTime() - start.getTime();
result = (int) ((diff / (60 * 1000)));
} else if ("second".equals(index)) {
result = c2.get(Calendar.SECOND) - c1.get(Calendar.SECOND);
} else {
return null;
}
return result;
}
/**
* 给一个时间加上几天、几月、几年、几小时、几分钟
* date 时间 num 要增加的时间(负数为减) index 标识
* @param date
* @param num
* @param index
* @return
*/
public static Date timeToAdd(Date date,Integer num,String index){
if(date == null || num == null || index == null || index == ""){
return date;
}
Calendar cd = Calendar.getInstance();
cd.setTime(date);
if("second".equals(index)){
cd.add(Calendar.SECOND,num);
}else if("minute".equals(index)){
cd.add(Calendar.MINUTE,num);
}else if("hour".equals(index)){
cd.add(Calendar.HOUR,num);
}else if("day".equals(index)){
cd.add(Calendar.DATE,num);
}else if("month".equals(index)){
cd.add(Calendar.MONTH,num);
}else if("year".equals(index)){
cd.add(Calendar.YEAR,num);
}else{
return null;
}
return cd.getTime();
}
/**
* 时间戳转日期
* @param s
* @return
*/
public static String stampToDate(String s,String format){
if(StringUtils.isEmpty(format)){
format = "yyyy-MM-dd HH:mm:ss";
}
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
long lt = new Long(s);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
/**
* 时间字符串转Time对象
* @param timeStr
* @return
* @throws ParseException
*/
public static Time stringToTime(String timeStr) throws ParseException{
Date tmpDateTime = stringToDateTime(dateToString(new Date(),DATE_FORMAT_YMD) + " " + timeStr);
Time time = new Time(tmpDateTime.getTime());
return time;
}
public static Boolean compareDate(Date dt1, Date dt2) {
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// Date dt1 = df.parse(DATE1);
// Date dt2 = df.parse(DATE2);
//dt1 在dt2前
// TimeLog.info("dt1 在dt2前");
return dt1.getTime() > dt2.getTime();
}
/**
* 获取今天开始时间和结束时间
* @return
*/
public static Map<String, String> getTodayTime() {
Map<String, String> map = new LinkedHashMap<>();
SimpleDateFormat sdfTs = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdfTe = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Date today = Calendar.getInstance().getTime();
String timeStart = "";
String timeEnd = "";
timeStart = sdfTs.format(today);
timeEnd = sdfTe.format(today);
map.put("timeStart", timeStart);
map.put("timeEnd", timeEnd);
return map;
}
/**
* 获取传入时间当天的开始时间和结束时间
* @param
* @author 逆风
* @date 2020/9/16 5:30 下午
* @exception
* @return java.util.Map<java.lang.String,java.lang.String>
*/
public static Map<String, String> getDateStartAndEndTime(Date today) {
Map<String, String> map = new LinkedHashMap<>();
SimpleDateFormat sdfTs = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdfTe = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String timeStart = "";
String timeEnd = "";
timeStart = sdfTs.format(today);
timeEnd = sdfTe.format(today);
map.put("timeStart", timeStart);
map.put("timeEnd", timeEnd);
return map;
}
/**
* 获取昨天开始时间和结束时间
* @return
*/
public static Map<String, String> getYesterdayTime() {
Map<String, String> map = new LinkedHashMap<String, String>();
SimpleDateFormat sdfTs = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdfTe = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = cal.getTime();
String timeStart = "";
String timeEnd = "";
timeStart = sdfTs.format(yesterday);
timeEnd = sdfTe.format(yesterday);
map.put("timeStart", timeStart);
map.put("timeEnd", timeEnd);
return map;
}
//获取最近30天开始时间结束时间
public static Map<String, String> getLast30DaysTime() {
Map<String, String> map = new LinkedHashMap<>();
SimpleDateFormat sdfTs = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdfTe = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -29);
Date thirtyDaysAgo = cal.getTime();
String timeStart = "";
timeStart = sdfTs.format(thirtyDaysAgo);
Date today = Calendar.getInstance().getTime();
String timeEnd = "";
timeEnd = sdfTe.format(today);
map.put("timeStart", timeStart);
map.put("timeEnd", timeEnd);
return map;
}
/**
* 获取指定日期开始的时间戳
* @param date 指定日期
* @return
*/
public static Long getTimestampBegin(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
//将分钟至0
c.set(Calendar.MINUTE, 0);
//将秒至0
c.set(Calendar.SECOND,0);
//将毫秒至0
c.set(Calendar.MILLISECOND, 0);
// 获取本月第一天的时间戳
return c.getTimeInMillis();
}
/**
* 获取指定日期结束的时间戳
* @param date 指定日期
* @return
*/
public static Long getTimestampEnd(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 23);
//将分钟至59
c.set(Calendar.MINUTE, 59);
//将秒至59
c.set(Calendar.SECOND,59);
//将毫秒至999
c.set(Calendar.MILLISECOND, 999);
// 获取本月最后一天的时间戳
return c.getTimeInMillis();
}
public static Long getCurrentStartTime() {
LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点
ZonedDateTime dt = ZonedDateTime.now(ZoneId.systemDefault());//获取当前时间
long start = dt.toLocalDate().atStartOfDay(ZoneId.systemDefault()).toEpochSecond() * 1000;//获取当天的起始时间戳
return start;
}
public static Long getCurrentEndTime() {
LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点
ZonedDateTime dt = ZonedDateTime.now(ZoneId.systemDefault());//获取当前时间
long start = dt.toLocalDate().atStartOfDay(ZoneId.systemDefault()).toEpochSecond() * 1000;//获取当天的起始时间戳
return start;
}
// 获取近30天不包含当天的时间戳
public static Long getThirtyDayTime() {
Date date = timeToAdd(new Date(), -31, "day");
return getTimestampBegin(date);
}
/**
* 将日期字符串转化为日期。失败返回null。
*
* @param date 日期字符串
* @param dateStyle 日期风格
* @return 日期
*/
public static Date stringToDate(String date, DateStyle dateStyle) {
Date myDate = null;
if (dateStyle == null) {
List<Long> timestamps = new ArrayList<Long>();
for (DateStyle style : DateStyle.values()) {
Date dateTmp = stringToDate(date, style.getValue());
if (dateTmp != null) {
timestamps.add(dateTmp.getTime());
}
}
myDate = getAccurateDate(timestamps);
} else {
myDate = stringToDate(date, dateStyle.getValue());
}
return myDate;
}
/**
* 获取精确的日期
*
* @param timestamps 时间long集合
* @return 日期
*/
private static Date getAccurateDate(List<Long> timestamps) {
Date date = null;
long timestamp = 0;
Map<Long, long[]> map = new HashMap<Long, long[]>();
List<Long> absoluteValues = new ArrayList<Long>();
if (timestamps != null && timestamps.size() > 0) {
if (timestamps.size() > 1) {
for (int i = 0; i < timestamps.size(); i++) {
for (int j = i + 1; j < timestamps.size(); j++) {
long absoluteValue = Math.abs(timestamps.get(i) - timestamps.get(j));
absoluteValues.add(absoluteValue);
long[] timestampTmp = {timestamps.get(i), timestamps.get(j)};
map.put(absoluteValue, timestampTmp);
}
}
// 有可能有相等的情况。如2012-11和2012-11-01。时间戳是相等的
long minAbsoluteValue = -1;
if (!absoluteValues.isEmpty()) {
// 如果timestamps的size为2,这是差值只有一个,因此要给默认值
minAbsoluteValue = absoluteValues.get(0);
}
for (int i = 0; i < absoluteValues.size(); i++) {
if (minAbsoluteValue > absoluteValues.get(i)) {
minAbsoluteValue = absoluteValues.get(i);
}
}
if (minAbsoluteValue != -1) {
long[] timestampsLastTmp = map.get(minAbsoluteValue);
if (absoluteValues.size() > 1) {
timestamp = Math.max(timestampsLastTmp[0], timestampsLastTmp[1]);
} else if (absoluteValues.size() == 1) {
// 当timestamps的size为2,需要与当前时间作为参照
long dateOne = timestampsLastTmp[0];
long dateTwo = timestampsLastTmp[1];
if ((Math.abs(dateOne - dateTwo)) < 100000000000L) {
timestamp = Math.max(timestampsLastTmp[0], timestampsLastTmp[1]);
} else {
long now = System.currentTimeMillis();
if (Math.abs(dateOne - now) <= Math.abs(dateTwo - now)) {
timestamp = dateOne;
} else {
timestamp = dateTwo;
}
}
}
}
} else {
timestamp = timestamps.get(0);
}
}
if (timestamp != 0) {
date = new Date(timestamp);
}
return date;
}
/**
* 将日期字符串转化为日期。失败返回null。
*
* @param date 日期字符串
* @param parttern 日期格式
* @return 日期
*/
public static Date stringToDate(String date, String parttern) {
Date myDate = null;
if (date != null) {
try {
myDate = getDateFormat(parttern).parse(date);
} catch (Exception e) {
}
}
return myDate;
}
/**
* 获取SimpleDateFormat
*
* @param parttern 日期格式
* @return SimpleDateFormat对象
* @throws RuntimeException 异常:非法日期格式
*/
private static SimpleDateFormat getDateFormat(String parttern) throws RuntimeException {
return new SimpleDateFormat(parttern);
}
/**
* 将日期字符串转化为日期。失败返回null。
*
* @param date 日期字符串
* @return 日期
*/
public static Date stringToDate2(String date) {
DateStyle dateStyle = null;
return stringToDate3(date, dateStyle);
}
/**
* 将日期字符串转化为日期。失败返回null。
*
* @param date 日期字符串
* @param dateStyle 日期风格
* @return 日期
*/
public static Date stringToDate3(String date, DateStyle dateStyle) {
Date myDate = null;
if (dateStyle == null) {
List<Long> timestamps = new ArrayList<Long>();
for (DateStyle style : DateStyle.values()) {
Date dateTmp = stringToDate4(date, style.getValue());
if (dateTmp != null) {
timestamps.add(dateTmp.getTime());
}
}
myDate = getAccurateDate(timestamps);
} else {
myDate = stringToDate4(date, dateStyle.getValue());
}
return myDate;
}
/**
* 将日期字符串转化为日期。失败返回null。
*
* @param date 日期字符串
* @param parttern 日期格式
* @return 日期
*/
public static Date stringToDate4(String date, String parttern) {
Date myDate = null;
if (date != null) {
try {
myDate = getDateFormat(parttern).parse(date);
} catch (Exception e) {
}
}
return myDate;
}
public enum DateStyle {
/**
* yyyy-MM-dd HH:mm:ss
*/
YYYY_MM_DD_HH_MM_SS("yyyy-MM-dd HH:mm:ss"),
/**
* yyyy-MM-dd
*/
YYYY_MM_DD("yyyy-MM-dd"),
/**
* yyyy-MM-dd HH:mm
*/
YYYY_MM_DD_HH_MM("yyyy-MM-dd HH:mm"),
/**
* MM-dd
*/
MM_DD("MM-dd"),
/**
* yyyy-MM
*/
YYYY_MM("yyyy-MM"),
/**
* MM-dd HH:mm
*/
MM_DD_HH_MM("MM-dd HH:mm"),
/**
* MM-dd HH:mm:ss
*/
MM_DD_HH_MM_SS("MM-dd HH:mm:ss"),
/**
* MM/dd
*/
MM_DD_EN("MM/dd"),
/**
* yyyy/MM
*/
YYYY_MM_EN("yyyy/MM"),
/**
* yyyy/MM/dd
*/
YYYY_MM_DD_EN("yyyy/MM/dd"),
/**
* MM/dd HH:mm
*/
MM_DD_HH_MM_EN("MM/dd HH:mm"),
/**
* MM/dd HH:mm:ss
*/
MM_DD_HH_MM_SS_EN("MM/dd HH:mm:ss"),
/**
* yyyy/MM/dd HH:mm
*/
YYYY_MM_DD_HH_MM_EN("yyyy/MM/dd HH:mm"),
/**
* yyyy/MM/dd HH:mm:ss
*/
YYYY_MM_DD_HH_MM_SS_EN("yyyy/MM/dd HH:mm:ss"),
/**
* MM月dd日
*/
MM_DD_CN("MM月dd日"),
/**
* yyyy年MM月
*/
YYYY_MM_CN("yyyy年MM月"),
/**
* yyyy年MM月dd日
*/
YYYY_MM_DD_CN("yyyy年MM月dd日"),
/**
* MM月dd日 HH:mm
*/
MM_DD_HH_MM_CN("MM月dd日 HH:mm"),
/**
* MM月dd日 HH:mm:ss
*/
MM_DD_HH_MM_SS_CN("MM月dd日 HH:mm:ss"),
/**
* yyyy年MM月dd日 HH:mm
*/
YYYY_MM_DD_HH_MM_CN("yyyy年MM月dd日 HH:mm"),
/**
* yyyy年MM月dd日 HH:mm:ss
*/
YYYY_MM_DD_HH_MM_SS_CN("yyyy年MM月dd日 HH:mm:ss"),
/**
* HH:mm
*/
HH_MM("HH:mm"),
/**
* HH:mm:ss
*/
HH_MM_SS("HH:mm:ss");
private final String value;
DateStyle(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
/**
* @description 某年、某月、某周、某日的23:59:59 失效时间
* @param resetTime
* @param zoneId
* @return long
* @throws
* @author 逆风
* @time 2023/3/1 09:50
*/
public static long getlapseTime(String resetTime, ZoneId zoneId) {
ZonedDateTime now = ZonedDateTime.of(LocalDateTime.now(), zoneId);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd 23:59:59").withZone(zoneId);
String lapseTime = null;
switch (resetTime) {
case "today":
//获取一天的结束时间
lapseTime = now.format(dateTimeFormatter);
break;
case "week":
//获取一周的结束时间
lapseTime = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).format(dateTimeFormatter);
break;
case "month":
//获取一月的结束时间
lapseTime = now.with(TemporalAdjusters.lastDayOfMonth()).format(dateTimeFormatter);
break;
case "year":
//获取一年的结束时间
lapseTime = now.with(TemporalAdjusters.lastDayOfYear()).format(dateTimeFormatter);
break;
default:
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone(zoneId));
try {
Date date = sdf.parse(lapseTime);
return date.getTime() - now.toInstant().toEpochMilli();
} catch (ParseException e) {
e.printStackTrace();
}
return 24 * 60 * 60;
}
}
package com.zxr.demos.common.utils;
import com.zxr.demos.common.enums.SpecialSymbolEnum;
import io.swagger.annotations.ApiModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 字符转换器
* @author 曹浩-非离
* 2019-07-26
*/
@ApiModel("对象DO、PO、VO之间的转换器")
@Slf4j
public class EsSpecialConvert {
/**
* 字符转化生僻字
*
* @param content 字符
* @return java.lang.String 生僻字
*/
public static String transSymbol(String content) {
if(StringUtils.isEmpty(content)){
return "";
}
for (SpecialSymbolEnum symbolEnum : SpecialSymbolEnum.values()) {
content = content.replace(symbolEnum.getKey(), symbolEnum.getWord());
}
return content;
}
/**
* 字符转化生僻字
*
* @param list 字符
* @return java.lang.String 生僻字
*/
public static List<String> transSymbolList(List<String> list) {
List<String> results = new ArrayList<>();
if (CollectionUtils.isNotEmpty(list)) {
for (String item : list) {
String symbol = transSymbol(item);
results.add(symbol);
}
}
return results;
}
/**
* 生僻字转化字符
*
* @param content 生僻字
* @return java.lang.String 字符
*/
public static String transWord(String content) {
if(StringUtils.isEmpty(content)){
return "";
}
for (SpecialSymbolEnum symbolEnum : SpecialSymbolEnum.values()) {
content = content.replace(symbolEnum.getWord(), symbolEnum.getKey());
}
return content;
}
}
package com.zxr.demos.common.utils;
import java.io.Serializable;
@FunctionalInterface
public interface Fn<T, R> extends Serializable {
R apply(T source);
public static <T, R> String getName(Fn<T, R> fn) {
return Reflections.fnToFieldName((tk.mybatis.mapper.weekend.Fn) fn);
}
}
package com.zxr.demos.common.utils;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@Slf4j
public class JdSignUtil {/**
* 生成京东 API 请求签名
* @param params 请求参数(不包括 sign)
* @param appSecret 京东应用密钥
* @return 生成的签名
*/
public static String generateSign(Map<String, String> params, String appSecret) {
// 1. 参数按键名升序排序
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
// 2. 按顺序拼接参数名和参数值
StringBuilder signSrc = new StringBuilder();
for (String key : keys) {
signSrc.append(key).append(params.get(key));
}
System.out.println(signSrc);
// 3. 头尾加上 appSecret
String signString = appSecret + signSrc + appSecret;
// 4. 使用 MD5 加密并转为大写
return md5Encrypt(signString).toUpperCase();
}
/**
* MD5 加密
* @param input 待加密字符串
* @return MD5 加密后的字符串
*/
private static String md5Encrypt(String input) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bytes = md5.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException("MD5加密失败", e);
}
}
}
\ No newline at end of file
package com.zxr.demos.common.utils;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import java.util.List;
/**
* @author xiaoyu
* 分页工具类
* @since 2023/9/15
*/
public class PageUtil {
/**
* 构建分页对象
* @author xiaoyu
* @since 2023/9/15
* @param pageNum 参数
* @param pageSize 参数
* @return com.github.pagehelper.PageInfo
*/
public static PageInfo build(Integer pageNum, Integer pageSize){
PageInfo pageInfo = new PageInfo<>();
pageInfo.setPageNum(pageNum);
pageInfo.setPageSize(pageSize);
return pageInfo;
}
/**
* 分页
* @author xiaoyu
* @since 2023/9/15
* @param pageInfo 参数
* @param reportDataList 参数
* @return com.github.pagehelper.PageInfo
*/
public static PageInfo paging(PageInfo pageInfo, List reportDataList){
pageInfo.setTotal(reportDataList.size());
if (pageInfo.getPageSize() == 0) {
pageInfo.setList(reportDataList);
pageInfo.setPages(1);
return pageInfo;
}
int from = (pageInfo.getPageNum() > 0 ? (pageInfo.getPageNum() - 1) : 0) * pageInfo.getPageSize();
int to = pageInfo.getPageNum() * pageInfo.getPageSize();
if (from >= reportDataList.size()) {
pageInfo.setList(Lists.newArrayList());
} else if (to >= reportDataList.size()) {
pageInfo.setList(reportDataList.subList(from, reportDataList.size()));
} else {
pageInfo.setList(reportDataList.subList(from, to));
}
pageInfo.setPages(reportDataList.size() % pageInfo.getPageSize() == 0 ? (reportDataList.size() / pageInfo.getPageSize()) : (reportDataList.size() / pageInfo.getPageSize()) + 1);
return pageInfo;
}
}
package com.zxr.demos.common.utils;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.weekend.Fn;
import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.util.regex.Pattern;
import java.lang.reflect.Method;
@Slf4j
public class Reflections {
private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
private Reflections() {
}
public static String fnToFieldName(Fn fn) {
Method method = null;
try {
method = fn.getClass().getDeclaredMethod("writeReplace");
method.setAccessible(Boolean.TRUE);
SerializedLambda serializedLambda = (SerializedLambda) method.invoke(fn);
String getter = serializedLambda.getImplMethodName();
if (GET_PATTERN.matcher(getter).matches()) {
getter = getter.substring(3);
} else if (IS_PATTERN.matcher(getter).matches()) {
getter = getter.substring(2);
}
return Introspector.decapitalize(getter);
} catch (NoSuchMethodException e) {
log.error("ERROR:", e);
} catch (IllegalAccessException e) {
log.error("ERROR:", e);
} catch (InvocationTargetException e) {
log.error("ERROR:", e);
}
return null;
}
}
package com.zxr.demos.common.vo;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
@Data
public class CarSeriesListVO {
/**
* 车型名称
*/
@JSONField(name = "modelName")
private String modelName;
/**
* 车型代码
*/
@JSONField(name = "code")
private String code;
}
package com.zxr.demos.common.vo;
import com.zxr.demos.common.entity.User;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class KunKunVO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("部门id")
private Integer id;
@ApiModelProperty("父级部门id")
private Integer parentId;
@ApiModelProperty("机构/部门名称")
private String departNameNew;
@ApiModelProperty("子级部门的集合")
private List<KunKunVO> children;
private User userNew;
}
package com.zxr.demos.common.vo;
public class ShbLoginUserVO {
}
Supports Markdown
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