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.utils;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 网络工具类:从TaobaoSDK中提取.
*
* @author wangkai
* @date 2020/7/1 11:07 上午
*/
@Slf4j
public class WebUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String METHOD_POST = "POST";
private static final String METHOD_GET = "GET";
private static final int DEFAULT_TIME_OUT = 30000;
private static class DefaultTrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
private WebUtils() {
}
/**
* get请求
**/
public static String getForObject(String url) {
HttpHeaders headers = new HttpHeaders();
HttpEntity httpEntity = new HttpEntity<>(headers);
ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, httpEntity, String.class);
return response.getBody();
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param params 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPostByJson(String url, Map<String, Object> params,Map<String, String> headerMap) throws IOException {
String ctype = "application/json";
String query = JSON.toJSONString(params, SerializerFeature.DisableCircularReferenceDetect);
return _doPost(url, ctype, query.getBytes(), DEFAULT_TIME_OUT, DEFAULT_TIME_OUT, headerMap);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param list 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPostByJsonAndArray(String url, List<? extends Object> list, Map<String, String> headerMap) throws IOException {
String ctype = "application/json";
String query = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect);
return _doPost(url, ctype, query.getBytes(), DEFAULT_TIME_OUT, DEFAULT_TIME_OUT, headerMap);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param params 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPostByJsonNew(String url, Map<String, Object> params,Map<String, String> headerMap) throws IOException {
String ctype = "application/json";
String query = JSONUtil.toJsonStr(params);
return _doPost(url, ctype, query.getBytes(), DEFAULT_TIME_OUT, DEFAULT_TIME_OUT, headerMap);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param params 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPost(String url, Map<Object, Object> params) throws IOException {
return doPost(url, params, DEFAULT_CHARSET, DEFAULT_TIME_OUT, DEFAULT_TIME_OUT);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param params 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPost(String url, Map<Object, Object> params, int connectTimeout, int readTimeout)
throws IOException {
return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param params 请求参数
* @param charset 字符集,如UTF-8, GBK, GB2312
* @return 响应字符串
* @throws IOException
*/
public static String doPost(String url, Map<Object, Object> params, String charset, int connectTimeout,
int readTimeout) throws IOException {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
byte[] content = {};
if (query != null) {
content = query.getBytes(charset);
}
return _doPost(url, ctype, content, connectTimeout, readTimeout);
}
public static String doPostJson(String url, Map<Object, Object> params, String charset, int connectTimeout,
int readTimeout) throws IOException {
String ctype = "application/json";
String query = JSON.toJSONString(params);
byte[] content = {};
if (query != null) {
content = query.getBytes(charset);
}
return _doPost(url, ctype, content, connectTimeout, readTimeout);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param params 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPost(String url, Map<String, Object> params, int connectTimeout,
int readTimeout, Map<String, String> headParam) throws IOException {
String ctype = "application/json";
String query = JSON.toJSONString(params);
return _doPost(url, ctype, query.getBytes(), connectTimeout, readTimeout, headParam);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param ctype 请求类型
* @param content 请求字节数组
* @return 响应字符串
* @throws IOException
*/
private static String _doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
throws IOException {
return _doPost(url, ctype, content, connectTimeout, readTimeout, null);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param ctype 请求类型
* @param content 请求字节数组
* @param headerMap 请求头参数
* @return 响应字符串
* @throws IOException
*/
private static String _doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout, Map<String, String> headerMap)
throws IOException {
HttpURLConnection conn = null;
OutputStream out = null;
try {
conn = getConnection(new URL(url), METHOD_POST, ctype, headerMap);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
out = conn.getOutputStream();
out.write(content);
return getResponseAsString(conn);
} catch (IOException e) {
throw e;
} finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
}
/**
* @param url 请求地址
* @return 响应字符串
* @throws IOException
*/
public static String doGet(String url) throws IOException {
return doGet(url, null, DEFAULT_CHARSET);
}
/**
* @param url 请求地址
* @param params 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doGet(String url, Map<Object, Object> params) throws IOException {
return doGet(url, params, DEFAULT_CHARSET);
}
/**
* 执行HTTP GET请求。
*
* @param url 请求地址
* @param params 请求参数
* @param charset 字符集,如UTF-8, GBK, GB2312
* @return 响应字符串
* @throws IOException
*/
public static String doGet(String url, Map<Object, Object> params, String charset) throws IOException {
return doGet(url, params, charset, null);
}
/**
* 执行HTTP GET请求。
*
* @param url 请求地址
* @param params 请求参数
* @param header header参数
* @return 响应字符串
* @throws IOException
*/
public static String doGet(String url, Map<Object, Object> params, Map<String, String> header) throws IOException {
return doGet(url, params, DEFAULT_CHARSET, header);
}
/**
* 执行HTTP GET请求。
*
* @param url 请求地址
* @param params 请求参数
* @param charset 字符集,如UTF-8, GBK, GB2312
* @return 响应字符串
* @throws IOException
*/
public static String doGet(String url, Map<Object, Object> params, String charset, Map<String, String> header) throws IOException {
HttpURLConnection conn = null;
String rsp = null;
try {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
try {
conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype, header);
conn.setConnectTimeout(DEFAULT_TIME_OUT);
conn.setReadTimeout(DEFAULT_TIME_OUT);
} catch (IOException e) {
throw e;
}
try {
rsp = getResponseAsString(conn);
} catch (IOException e) {
throw e;
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
public static Pair<Boolean, String> doPatchForm(String url, Map<String, Object> params, Map<String, String> headParam) throws IOException {
String cType = "application/x-www-form-urlencoded;charset=utf-8";
String query = buildQuery(params);
byte[] content = {};
if (query != null) {
content = query.getBytes(DEFAULT_CHARSET);
}
return _doPatch(url, cType, null, DEFAULT_TIME_OUT, headParam, params);
}
public static Pair<Boolean, String> doPatchByObject(String url, Object param, Map<String, String> head) throws IOException {
String cType = "application/json;charset=utf-8";
String query = JSONUtil.toJsonStr(param);
return _doPatch(url, cType, query, DEFAULT_TIME_OUT, head, null);
}
private static HttpURLConnection getConnection(URL url, String method, String ctype, Map<String, String> headerMap)
throws IOException {
HttpURLConnection conn = null;
if ("https".equals(url.getProtocol())) {
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
} catch (Exception e) {
throw new IOException(e);
}
HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;// 默认都认证通过
}
});
conn = connHttps;
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json,text/xml,text/javascript,text/html,application/xml");
conn.setRequestProperty("User-Agent", "top-sdk-java");
conn.setRequestProperty("Content-Type", ctype);
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return conn;
}
private static URL buildGetUrl(String strUrl, String query) throws IOException {
URL url = new URL(strUrl);
if (StringUtils.isEmpty(query)) {
return url;
}
if (StringUtils.isEmpty(url.getQuery())) {
if (strUrl.endsWith("?")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "?" + query;
}
} else {
if (strUrl.endsWith("&")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "&" + query;
}
}
return new URL(strUrl);
}
public static String buildQuery(Map<Object, Object> params, String charset) throws IOException {
if (params == null || params.isEmpty()) {
return null;
}
StringBuilder query = new StringBuilder();
Set<Map.Entry<Object, Object>> entries = params.entrySet();
boolean hasParam = false;
for (Map.Entry<Object, Object> entry : entries) {
String name = entry.getKey().toString();
String value = entry.getValue().toString();
// 忽略参数名或参数值为空的参数
if (areNotEmpty(name, value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, charset));
}
}
return query.toString();
}
public static String buildQuery(Map<String, Object> params) throws IOException {
if (params == null || params.isEmpty()) {
return null;
}
StringBuilder query = new StringBuilder();
Set<Map.Entry<String, Object>> entries = params.entrySet();
boolean hasParam = false;
for (Map.Entry<String, Object> entry : entries) {
String name = entry.getKey();
String value = entry.getValue().toString();
// 忽略参数名或参数值为空的参数
if (areNotEmpty(name, value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, DEFAULT_CHARSET));
}
}
return query.toString();
}
/**
* 检查指定的字符串列表是否不为空。
*/
public static boolean areNotEmpty(String... values) {
boolean result = true;
if (values == null || values.length == 0) {
result = false;
} else {
for (String value : values) {
result &= !isEmpty(value);
}
}
return result;
}
/**
* 检查指定的字符串是否为空。
* <ul>
*
* <li>SysUtils.isEmpty(null) = true</li>
* <li>SysUtils.isEmpty("") = true</li>
* <li>SysUtils.isEmpty(" ") = true</li>
* <li>SysUtils.isEmpty("abc") = false</li>
* </ul>
*
* @param value 待检查的字符串
* @return true/false
*/
public static boolean isEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((!Character.isWhitespace(value.charAt(i)))) {
return false;
}
}
return true;
}
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
Reader reader = new InputStreamReader(stream, charset);
StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
}
return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
if (StringUtils.isEmpty(ctype)) {
return DEFAULT_CHARSET;
}
String charset = DEFAULT_CHARSET;
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (!param.startsWith("charset")) {
continue;
}
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (!StringUtils.isEmpty(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
return charset;
}
/**
* 使用默认的UTF-8字符集反编码请求参数值。
*
* @param value 参数值
* @return 反编码后的参数值
*/
public static String decode(String value) {
return decode(value, DEFAULT_CHARSET);
}
/**
* 使用默认的UTF-8字符集编码请求参数值。
*
* @param value 参数值
* @return 编码后的参数值
*/
public static String encode(String value) {
return encode(value, DEFAULT_CHARSET);
}
/**
* 使用指定的字符集反编码请求参数值。
*
* @param value 参数值
* @param charset 字符集
* @return 反编码后的参数值
*/
public static String decode(String value, String charset) {
String result = null;
if (!StringUtils.isEmpty(value)) {
try {
result = URLDecoder.decode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* 使用指定的字符集编码请求参数值。
*
* @param value 参数值
* @param charset 字符集
* @return 编码后的参数值
*/
public static String encode(String value, String charset) {
String result = null;
if (!StringUtils.isEmpty(value)) {
try {
result = URLEncoder.encode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* 从URL中提取所有的参数。
*
* @param query URL地址
* @return 参数映射
*/
public static Map<String, String> splitUrlQuery(String query) {
Map<String, String> result = new HashMap<String, String>();
String[] pairs = query.split("&");
if (pairs != null && pairs.length > 0) {
for (String pair : pairs) {
String[] param = pair.split("=", 2);
if (param != null && param.length == 2) {
result.put(param[0], param[1]);
}
}
}
return result;
}
private static Pair<Boolean, String> _doPatch(String url, String cType, String content, int connectTimeout, Map<String, String> headerMap, Map<String, Object> params) throws IOException {
int statusCode = 0;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch(url);
HttpResponse httpResponse = null;
String result = "";
try {
if(MapUtils.isNotEmpty(headerMap)){
for(Map.Entry<String, String> entry : headerMap.entrySet()){
httpPatch.addHeader(entry.getKey(), entry.getValue());
}
}
httpPatch.setHeader("Content-Type", cType);
// body 提交
if(org.apache.commons.lang3.StringUtils.isNotBlank(content)){
StringEntity entity = new StringEntity(content, StandardCharsets.UTF_8);
httpPatch.setEntity(entity);
}
// 表单提交
if(MapUtils.isNotEmpty(params)){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
for (String key : params.keySet()) {
builder.addPart(key,
new StringBody(params.get(key).toString(), ContentType.create("text/plain", Consts.UTF_8)));
}
}
org.apache.http.HttpEntity reqEntity = builder.build();
httpPatch.setEntity(reqEntity);
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(connectTimeout).setConnectTimeout(connectTimeout).build();
httpPatch.setConfig(requestConfig);
httpResponse = httpClient.execute(httpPatch);
// 处理返回结果 20 开头的都是成功
if(!org.apache.commons.lang3.StringUtils.startsWith(String.valueOf(httpResponse.getStatusLine().getStatusCode()), "20")){
log.info("HttpPost: {}", 0);
//System.out.println("response code is :"+response.getStatusLine().getStatusCode());
return Pair.of(false, null);
}
log.info("HttpPost: {}", 1);
org.apache.http.HttpEntity entity = httpResponse.getEntity();
if(entity != null){
log.info("HttpPost: {}", 2);
String resultStr = EntityUtils.toString(entity,"utf-8");
return Pair.of(true, resultStr);
}else{
log.info("HttpPost: {}", 3);
//System.out.println("response.getEntity is null");
return Pair.of(true, null);
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
}
public static String httpPost(String url,String jsonContent){
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_TIME_OUT).setConnectTimeout(DEFAULT_TIME_OUT).build();
httpPost.setConfig(requestConfig);
httpPost.addHeader("Content-Type", "application/json");
StringEntity requestEntity = new StringEntity(jsonContent,"utf-8");
httpPost.setEntity(requestEntity);
try{
response = httpClient.execute(httpPost,new BasicHttpContext());
log.info("HttpPost___________________________________{}", response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
log.info("HttpPost: {}", 0);
//System.out.println("response code is :"+response.getStatusLine().getStatusCode());
return null;
}
log.info("HttpPost: {}", 1);
org.apache.http.HttpEntity entity = response.getEntity();
if(entity != null){
log.info("HttpPost: {}", 2);
String resultStr = EntityUtils.toString(entity,"utf-8");
return resultStr;
}else{
log.info("HttpPost: {}", 3);
//System.out.println("response.getEntity is null");
return null;
}
}catch (Exception e){
log.info("HttpPost: {}", 4);
e.printStackTrace();
return null;
}finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
//System.out.println("close http connection failed");
e.printStackTrace();
}
}
}
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param param 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPostByObject(String url, Object param, Map<String, String> headerMap) throws IOException {
String ctype = "application/json";
String query = JSON.toJSONString(param);
return _doPost(url, ctype, query.getBytes(), DEFAULT_TIME_OUT, DEFAULT_TIME_OUT, headerMap);
}
/**
* 执行HTTP POST请求。
*
* @param url 请求地址
* @param param 请求参数
* @return 响应字符串
* @throws IOException
*/
public static String doPostByObjectNew(String url, Object param, Map<String, String> headerMap) throws IOException {
String ctype = "application/json";
String query = JSONUtil.toJsonStr(param);
return _doPost(url, ctype, query.getBytes(), DEFAULT_TIME_OUT, DEFAULT_TIME_OUT, headerMap);
}
public static String doPatch(String url, Map<String, Object> paramMap, Map<String, String> headerMap) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch(url);
//请求头
if (MapUtils.isNotEmpty(headerMap)) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPatch.addHeader(entry.getKey(), entry.getValue());
}
}
httpPatch.setHeader("Content-type", "application/json");
try {
if (paramMap != null) {
StringEntity entity = new StringEntity(JSON.toJSONString(paramMap), StandardCharsets.UTF_8);
log.info("通过http调用Patch请求,paramMap: {}", paramMap.toString());
httpPatch.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPatch);
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
log.info("通过http调用Patch请求,HttpPatch paramMap: {}",JSON.toJSONString(paramMap));
return EntityUtils.toString(entity, "utf-8");
} else {
log.info("通过http调用Patch请求,HttpPatch: {}", 3);
//System.out.println("response.getEntity is null");
return null;
}
} catch (IOException e) {
log.error("通过http调用Patch请求出错,HttpPatch error is: {}", e.getMessage());
} finally {
try {
httpClient.close();
} catch (IOException e) {
log.error("===========通过http调用Patch请求出错,HttpPatch error is: {}", e.getMessage());
}
}
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;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
@Data
public class MacroServiceSettleStandardVo {
private Integer id;
private String standardNo;
private String state;
private String standardName;
// 服务类型:下拉菜单,选项=取【1-1-3 服务类型设置】页面“启用”状态的值,单选,必填
private String serviceTypeId;
// 服务类型:下拉菜单,选项=取【1-1-3 服务类型设置】页面“启用”状态的值,单选,必填
private String serviceType;
// 保修类型:下拉菜单,选项=保内,默认选中保内,必填
private String warrantyType;
private Long productCategoryId;
// 产品大类:下拉菜单,选项=取【3-2 产品分类】列表内“产品大类”的分类名称,单选,必填
private String productCategory;
// 生效日期:日期控件,仅可选择明天及之后的时间,格式年月日时分秒,时分秒默认为00:00:00,且不可修改,必填
private Long effectiveDate;
// 失效日期:日期控件,需日期需晚于或等于生效日期,格式年月日时分秒,时分秒默认为23:59:59,且不可修改,必填
private Long expirationDate;
private Long createTime;
private Long updateTime;
private ShbLoginUserVO createUser;
private ShbLoginUserVO updateUser;
// 一二级市场:数值,可输入范围0<=X<=99999,最多保留2位小数,必填
private BigDecimal primaryToSecondMarket;
// 三四级市场:数值,可输入范围0<=X<=99999,最多保留2位小数,必填
private BigDecimal thirdToFourthMarket;
// 五六级市场:数值,可输入范围0<=X<=99999,最多保留2位小数,必填
private BigDecimal fifthToSixthMarket;
// 其他市场:数值,可输入范围0<=X<=99999,最多保留2位小数,非必填
private BigDecimal otherMarket;
// 产品小类:下拉菜单,显示已选择产品大类下的小类,选项来源=【3-2 产品分类】列表内“产品小类”,多选,非必填
private List<productSubCategory> productSubCategories;
// 指定产品:选择弹窗,数据来源【3-3 产品型号】列表内“已启用”的产品类型名称,支持多选,非必填
private List<specifiedProduct> specifiedProducts;
// 指定网点:下拉菜单,选项=服务网点列表内为撤点的数据,显示网点名称+网点编号,支持多选,非必填
private List<Provider> serviceProviders;
// 指定地区:级联控件,可选择省-市,支持多选,非必填
private List<Region> regions;
// 备注:文本,非必填
private String remark;
@Data
public static class Provider {
/**
* 服务商id
*/
private String id;
private String name;
private String no;
}
@Data
public static class Region {
private String city;
private String province;
}
@Data
public static class specifiedProduct{
private Long value;
private String label;
}
@Data
public static class productSubCategory {
private Long value;
private String label;
}
}
package com.zxr.demos.common.vo;
public class ShbLoginUserVO {
}
package com.zxr.demos.controller;
import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.zxr.demos.common.entity.CarSeriesList;
import com.zxr.demos.common.entity.PartsData;
import com.zxr.demos.common.entity.WorkHourData;
import com.zxr.demos.common.param.UdspQueryCarSeriesListParam;
import com.zxr.demos.common.param.UdspQueryPartsParam;
import com.zxr.demos.common.param.UdspQueryWorkHourParam;
import com.zxr.demos.common.response.UdspApiCommonResult;
import com.zxr.demos.common.response.UdspCarSeriesListResult;
import com.zxr.demos.common.response.UdspPartsResult;
import com.zxr.demos.common.response.UdspWorkHourResult;
import com.zxr.demos.mapper.UdspCarSeriesListApiMapper;
import com.zxr.demos.mapper.UdspPartsDataMapper;
import com.zxr.demos.mapper.UdspWorkHourApiMapper;
import com.zxr.demos.service.UdspCarSeriesListService;
import com.zxr.demos.service.UdspPartsService;
import com.zxr.demos.service.UdspWorkHourDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author zxr
* @since 2024-09-04
*/
@Slf4j
@RestController
@RequestMapping("/work-hour-data")
public class CommonTestController {
@Autowired
private UdspWorkHourDataService workHourDataService;
@Autowired
private UdspCarSeriesListService carSeriesListService;
@Autowired
private UdspPartsService partsService;
@Autowired
private UdspPartsDataMapper partsDataMapper;
@Autowired
private UdspWorkHourApiMapper workHourApiMapper;
@Autowired
private UdspCarSeriesListApiMapper carSeriesListApiMapper;
/*
* @Description: 车系清单查询接口
* @Author: 张先冉
* @date: 2024/9/5 18:03
*/
@PostMapping("/getModelList")
public UdspApiCommonResult queryPagCarSeriesList(@RequestBody UdspQueryCarSeriesListParam param){
PageInfo<UdspCarSeriesListResult> info = carSeriesListService.queryPagCarSeriesList(param);
return UdspApiCommonResult.success(info.getList());
}
/*
* @Description: 工时信息查询接口
* @Author: 张先冉
* @date: 2024/9/5 15:43
*/
@PostMapping("/getTaskList")
public UdspApiCommonResult queryPageWorkHour(@RequestBody UdspQueryWorkHourParam param){
PageInfo<UdspWorkHourResult> info = workHourDataService.queryPageWorkHour(param);
return UdspApiCommonResult.success(info.getList());
}
/*
* @Description: 零件信息查询接口
* @Author: 张先冉
* @date: 2024/9/5 22:11
*/
@PostMapping("/getPartList")
public UdspApiCommonResult queryPageParts(@RequestBody UdspQueryPartsParam param){
PageInfo<UdspPartsResult> info = partsService.queryPageParts(param);
return UdspApiCommonResult.success(info.getList());
}
/*
* @Description: 车系批量插入
* @Author: 张先冉
* @date: 2024/9/6 11:25
*/
@GetMapping("/testCarSerInsert")
public void testCarSerInsert() {
UdspCarSeriesListResult result1 = new UdspCarSeriesListResult();
result1.setCode("123");
result1.setModelName("zxr");
UdspCarSeriesListResult result2 = new UdspCarSeriesListResult();
result2.setCode("123");
result2.setModelName("zxr");
List<UdspCarSeriesListResult> resultList =new ArrayList<>();
resultList.add(result2);
resultList.add(result1);
//模拟接收数据
List<CarSeriesList> carSeriesLists = new ArrayList<>();
for (int i = 0; i < resultList.size(); i++) {
CarSeriesList carSeriesList = new CarSeriesList();
carSeriesList.setModelCode(resultList.get(i).getCode());
carSeriesList.setModelName(resultList.get(i).getModelName());
carSeriesList.setId((long)i+1);
carSeriesLists.add(carSeriesList);
}
carSeriesListApiMapper.insertBatch(carSeriesLists);
}
/*
* @Description: 工时批量插入
* @Author: 张先冉
* @date: 2024/9/6 11:25
*/
@GetMapping("/testWorkHourInsert")
public void testWorkHourInsert() {
UdspWorkHourResult result = new UdspWorkHourResult();
result.setId(22L);
result.setTaskCode("123");
result.setModelName("zxr");
result.setTaskName("zzzz");
result.setTaskTime(new BigDecimal("2.2"));
WorkHourData workHourData = BeanUtil.copyProperties(result, WorkHourData.class);
log.info("workHourData{}",workHourData);
List<WorkHourData> workHourDataList =new ArrayList<>();
workHourDataList.add(workHourData);
workHourApiMapper.insertBatch(workHourDataList);
}
/*
* @Description: 零件批量插入接口
* @Author: 张先冉
* @date: 2024/9/5 22:11
*/
@GetMapping("/insertPartList")
public void insertparts(){
List<UdspPartsResult> partsResultList = new ArrayList<>();
UdspPartsResult partsResult = new UdspPartsResult();
partsResult.setId(3000L);
partsResult.setModelName("CX11");
partsResult.setPartsCode("8888843536");
partsResult.setPartsEname("OIL FILTER INSERT");
partsResult.setPartsCname("机油滤清器");
partsResult.setDealerCode("UAT20000");
partsResult.setAmt(new BigDecimal("68.0000000000"));
partsResultList.add(partsResult);
log.info("partsResultList:{}",partsResultList);
List<PartsData> partsDataList = BeanUtil.copyToList(partsResultList, PartsData.class);
partsDataMapper.insertBatch(partsDataList);
}
/*
* @Description: 删除
* @Author: 张先冉
* @date: 2024/9/12 11:21
*/
@GetMapping("/deleteparts")
public void deleteparts(){
partsDataMapper.deleteparts();
}
@Transactional
@GetMapping("/deleteAndInsert")
public void testDeleteAndInsert(){
deleteAndInsert();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void deleteAndInsert() {
try{
//delete
carSeriesListApiMapper.deleteCarSerTable();
//insert
List<CarSeriesList> carSeriesLists = makeInsertData();
carSeriesListApiMapper.insertBatch(carSeriesLists);
}catch(Exception e){
e.printStackTrace();
log.error("删除和插入失败,任务回滚");
throw new RuntimeException("删除和插入失败,任务回滚");
}
}
private static List<CarSeriesList> makeInsertData() {
UdspCarSeriesListResult result1 = new UdspCarSeriesListResult();
result1.setCode("123");
result1.setModelName("zxc");
UdspCarSeriesListResult result2 = new UdspCarSeriesListResult();
result2.setCode("123");
result2.setModelName("zxr");
List<UdspCarSeriesListResult> resultList = new ArrayList<>();
resultList.add(result2);
resultList.add(result1);
//模拟接收数据
List<CarSeriesList> carSeriesLists = new ArrayList<>();
for (int i = 100; i < resultList.size(); i++) {
CarSeriesList carSeriesList = new CarSeriesList();
carSeriesList.setModelCode(resultList.get(i).getCode());
carSeriesList.setModelName(resultList.get(i).getModelName());
carSeriesList.setId((long) i + 1);
carSeriesLists.add(carSeriesList);
}
return carSeriesLists;
}
}
package com.zxr.demos.controller;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.zxr.demos.common.entity.CarSeriesList;
import com.zxr.demos.common.param.BarCodeParam;
import com.zxr.demos.common.param.BaseProductCatalogSearchModel;
import com.zxr.demos.common.param.TestParam;
import com.zxr.demos.common.response.BarCodeResponseData;
import com.zxr.demos.common.response.Result;
import com.zxr.demos.common.response.UdspCarSeriesListResult;
import com.zxr.demos.mapper.UdspCarSeriesListApiMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
@RequestMapping
public class TestController01 {
@Autowired
private com.zxr.demos.service.myService myService;
@Autowired
private UdspCarSeriesListApiMapper carSeriesListApiMapper;
private static final ObjectMapper objectMapper = new ObjectMapper();
/*
* @Description: 测试返回值
* @Author: zhangxianran
* @date: 2024/10/9 09:23
* @return
*/
@GetMapping("/testResult")
public Result<Boolean> testResult(@RequestParam("type") String type) {
log.info("type :{}",type);
Boolean b = false;
return Result.success(b);
}
@PostMapping("/testBody")
public Result<Boolean> test02(@RequestBody BarCodeParam barCodeParam) throws JsonProcessingException {
log.info("barCodeParam :{}", barCodeParam);
String url = "https://esb-bcd.chinamacro.com/v1/bcd/getHeadquartersStorageBarCode/query";
String result = HttpUtil.post(url, JSONObject.toJSONString(barCodeParam));
result = "{ \"esbInfo\": { \"instId\": null, \"returnStatus\": \"S\", \"returnCode\": \"A0001\", \"returnMsg\": \"获取条码信息成功\", \"requestTime\": \"2021-08-17 16:35:38.332\", \"responseTime\": \"2021-08-17 16:35:38.336\", \"attr1\": null, \"attr2\": null, \"attr3\": null }, \"queryInfo\": { \"totalRecord\": 1, \"totalPage\": 1, \"pageSize\": 2000, \"currentPage\": 1 }, \"resultInfo\": [{ \"org_name\": \"福建区域\", \"warehouse_name\": \"产品外置仓库\", \"cust_code\": \"R113-803\", \"barcode\": \"01069048813196541119121210792367\", \"org_code\": \"130100000002\", \"engineering_proj_name\": \"泉州市晋江市池店工厂宿舍电热采购\", \"bill_type\": 1, \"id\": 369590, \"cust_name\": \"泉州润禾贸易有限公司\", \"item_code\": \"DR305002072193\", \"in_warehouse_name\": \"-\", \"item_name\": \"D50-DT1*50L/2100W储水式电热水器*DH50DT1B\", \"guarantee\": \"-\", \"warehouse_code\": \"106\", \"engineering_proj_sn\": \"200310320\", \"bill_no\": \"XFHA20031600055\", \"channel\": \"工程\", \"bill_date\": \"2020-03-18 14:27:19\", \"in_warehouse_code\": \"-\", \"is_install\": \"-\" }]}";
BarCodeResponseData barCodeResponseData = JSONObject.parseObject(result, BarCodeResponseData.class);
log.info("barCodeResponseData :{}", barCodeResponseData);
log.info("result :{}", result);
Map<String, Object> paramMap;
String s = objectMapper.writeValueAsString(barCodeParam);
paramMap = objectMapper.readValue(s, new TypeReference<Map<String, Object>>() {
});
log.info("paramMap :{}", paramMap);
Boolean b = false;
return Result.success(b);
}
/*
*@Description: 测试事务问题
* @Author: zhangxianran
* @Date: 2024/11/21 13:24
*/
@Transactional(rollbackFor = Exception.class)
@GetMapping("/test/tran")
public void testTran() {
// myService.myInsert();
deleteAndInsertTestUnion();
}
public void deleteAndInsertTestUnion() {
try{
//delete
carSeriesListApiMapper.deleteCarSerTable();
// 模拟除以零异常
int result = 1 / 0; // 这里会触发 ArithmeticException
//insert
List<CarSeriesList> carSeriesLists = makeInsertData();
carSeriesListApiMapper.insertBatch(carSeriesLists);
}catch(Exception e){
e.printStackTrace();
log.error("删除和插入失败,任务回滚");
throw new RuntimeException("删除和插入失败,任务回滚");
}
}
private static List<CarSeriesList> makeInsertData() {
UdspCarSeriesListResult result1 = new UdspCarSeriesListResult();
result1.setCode("123");
result1.setModelName("zxr");
UdspCarSeriesListResult result2 = new UdspCarSeriesListResult();
result2.setCode("123");
result2.setModelName("zxr");
List<UdspCarSeriesListResult> resultList = new ArrayList<>();
resultList.add(result2);
resultList.add(result1);
//模拟接收数据
List<CarSeriesList> carSeriesLists = new ArrayList<>();
for (int i = 0; i < resultList.size(); i++) {
CarSeriesList carSeriesList = new CarSeriesList();
carSeriesList.setModelCode(resultList.get(i).getCode());
carSeriesList.setModelName(resultList.get(i).getModelName());
carSeriesList.setId((long) i + 1);
carSeriesLists.add(carSeriesList);
}
return carSeriesLists;
}
@PostMapping("/testLongParam")
public String testLongParam(@RequestBody TestParam param){
log.info("param :{}",param);
return "";
}
@RequestMapping(value = "/assessmentItem/export", method = RequestMethod.POST)
@ResponseBody
private void testExcelExport(@RequestParam(value = "exportSearchModel") String pcStr , @RequestParam(required = false,value = "selectedFields") String selectedFields){
String pc = pcStr.replaceAll("&quot;", "\"");
Map paramMap = new LinkedHashMap();
paramMap.put("pcStr", pcStr);
paramMap.put("selectedFields", selectedFields);
String fieldString = Optional.ofNullable((String) paramMap.get("selectedFields")).orElse("");
ArrayList<String> fieldList = Lists.newArrayList(fieldString.split(","));
for (String s : fieldList) {
System.out.println(s);
}
BaseProductCatalogSearchModel query = JSON.parseObject(pc, BaseProductCatalogSearchModel.class);
System.out.println(query);
}
@GetMapping("/testTime01")
public void testTime01(){
System.out.println("开始");
time01();
System.out.println("嘻嘻");
}
public void time01() {
// 假设 planTime 是一个未来的时间,例如 40 分钟后
Date planTime = new Date(System.currentTimeMillis() + 40 * 60 * 1000); // 当前时间加 40 分钟
// 当前时间
Date now = new Date();
// 计算计划时间和当前时间之间的差值(毫秒)
long differenceInMillis = planTime.getTime() - now.getTime();
// 判断计划时间是否大于当前时间 30 分钟
if (differenceInMillis > 30 * 60 * 1000) { // 大于 30 分钟
// 提前 30 分钟提醒
Date reminderTime = new Date(planTime.getTime() - 30 * 60 * 1000); // 提前 30 分钟
long delayInMillis = reminderTime.getTime() - now.getTime(); // 计算提醒时间距离当前的延迟时间(毫秒)
System.out.println("Reminder: 你将在 " + reminderTime + " 前30分钟得到提醒。");
// 调度定时任务,在 reminderTime 触发自定义方法
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(() -> triggerReminder(), delayInMillis, TimeUnit.MILLISECONDS);
// 确保任务完成后关闭线程池
scheduler.shutdown();
} else {
System.out.println("计划时间不满足条件,无需提醒。");
}
}
public void triggerReminder() {
System.out.println("哈哈哈");
}
}
package com.zxr.demos.controller;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zxr.demos.common.entity.BaseServiceType;
import com.zxr.demos.common.entity.CarSeriesList;
import com.zxr.demos.common.entity.RbDeliveryFailRetry;
import com.zxr.demos.common.param.CommonPageParam;
import com.zxr.demos.common.response.Result;
import com.zxr.demos.common.utils.PageUtil;
import com.zxr.demos.common.vo.CarSeriesListVO;
import com.zxr.demos.mapper.BaseServiceTypeMapper;
import com.zxr.demos.mapper.RbDeliveryFailRetryMapper;
import com.zxr.demos.mapper.UdspCarSeriesListApiMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@RestController
@RequestMapping
public class TestControllerMySql {
@Autowired
private com.zxr.demos.service.myService myService;
@Autowired
private UdspCarSeriesListApiMapper carSeriesListApiMapper;
@Autowired
private BaseServiceTypeMapper serviceTypeMapper;
/**
* @Description: 分页失败
* @Author: zhangxianran
* @Date: 2024/11/27 11:23
*/
@PostMapping("/testPage01")
public Result<PageInfo<CarSeriesListVO>> testPage01(@RequestBody CommonPageParam param) {
PageHelper.startPage(param.getPageNum(), param.getPageSize());
List<CarSeriesList> list = carSeriesListApiMapper.queryPage();
log.info("list :{}", list);
List<CarSeriesListVO> vos = BeanUtil.copyToList(list, CarSeriesListVO.class);
PageInfo<CarSeriesListVO> info = new PageInfo<>();
info.setList(vos);
return Result.success(info);
}
/**
* @Description: 分页成功,并且显示总条数和当前页面大小
* @Author: zhangxianran
* @Date: 2024/11/27 11:22
*/
@PostMapping("/testPage02")
public Result<PageInfo<CarSeriesListVO>> testPage02(@RequestBody CommonPageParam param) {
PageInfo pageInfo = PageUtil.build(param.getPageNum(), param.getPageSize());
List<CarSeriesList> list = carSeriesListApiMapper.queryPage();
log.info("list :{}", list);
List<CarSeriesListVO> vos = BeanUtil.copyToList(list, CarSeriesListVO.class);
PageInfo paging = PageUtil.paging(pageInfo, vos);
return Result.success(paging);
}
/**
* @Description: 分页失败
* @Author: zhangxianran
* @Date: 2024/11/27 11:23
*/
// @PostMapping("/testPage03")
// public Result<PageInfo<CarSeriesListVO>> testPage03 (@RequestBody CommonPageParam param) {
// PageHelper.startPage(param.getPageNum(),param.getPageSize());
// List<CarSeriesList> list = carSeriesListApiMapper.queryPage();
// PageInfo<CarSeriesList> info = new PageInfo<>(list);
// info.setList(vos);
// return Result.success(info);
// }
/**
* tkmapper的weekends
*/
@GetMapping("/testWeekend")
public Result testWeekend(@RequestParam(required = false) String serviceType) {
Weekend<BaseServiceType> weekend = new Weekend<>(BaseServiceType.class);
WeekendCriteria<BaseServiceType, Object> weekendCriteria = weekend.weekendCriteria()
.andEqualTo(BaseServiceType::getDeleted, 0)
.andEqualTo(BaseServiceType::getServiceType, serviceType);
if (true){
weekendCriteria.andEqualTo(BaseServiceType::getState, 1);
}
List<BaseServiceType> baseServiceTypes = serviceTypeMapper.selectByExample(weekend);
log.info("baseServiceTypes :{}", baseServiceTypes);
return Result.success(baseServiceTypes);
}
/**
* [
* {
* "pageNum": 2,
* "pageSize": 20,
* "orderBy": "someField asc",
* "commonSearch": "searchTerm1"
* },
* {
* "pageNum": 3,
* "pageSize": 15,
* "orderBy": "anotherField desc",
* "commonSearch": "searchTerm2"
* }
* ]
* @param commonPageParamList
* @return
*/
@PostMapping("/testListParam")
public Result testListParam(@RequestBody List<CommonPageParam> commonPageParamList){
log.info("commonPageParamList :{}",commonPageParamList);
return Result.success();
}
@Autowired
private RbDeliveryFailRetryMapper rbDeliveryFailRetryMapper;
@GetMapping("/T1")
public void testMethod() {
LambdaQueryWrapper<RbDeliveryFailRetry> queryWrapper = new LambdaQueryWrapper<RbDeliveryFailRetry>()
// 最近两天的数据
.ge(RbDeliveryFailRetry::getCreatedTime, LocalDateTime.now().minusDays(2))
// 重试次数小于3 或 为null 或 等于0
.and(wrapper -> wrapper
.lt(RbDeliveryFailRetry::getRetryCount, 3)
.or()
.eq(RbDeliveryFailRetry::getRetryCount, 0)
.or()
.isNull(RbDeliveryFailRetry::getRetryCount)
)
// 按创建时间升序
.orderByAsc(RbDeliveryFailRetry::getCreatedTime)
// 只查询50条
.last("LIMIT 50");
List<RbDeliveryFailRetry> rbDeliveryFailRetrieList = rbDeliveryFailRetryMapper.selectList(queryWrapper);
log.info("T1.t1 rbDeliveryFailRetrieList :{}",rbDeliveryFailRetrieList);
}
}
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