Commit b2eded42 authored by kang.nie@inzymeits.com's avatar kang.nie@inzymeits.com
Browse files

初始化代码

parent 12156d65
Pipeline #3109 failed with stages
in 0 seconds
package com.cusc.nirvana.user.rnr.mg.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cache.CacheFactory;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.rnr.mg.service.NoticeConfigService;
import com.cusc.nirvana.user.rnr.mg.service.TimingSendService;
import com.cusc.nirvana.user.rnr.mg.util.RnrMgRestTemplateUtils;
import com.cusc.nirvana.user.rnr.notice.dto.RnrNoticeConfigDTO;
import com.cusc.nirvana.user.rnr.notice.dto.RnrNoticeContentDTO;
import com.cusc.nirvana.user.rnr.notice.service.IRnrNoticeContentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.*;
/**
* @className: TimingSendServiceImpl
* @author: jk
* @date: 2022/7/29 17:20
* @version: 1.0
**/
@Service
@Slf4j
public class TimingSendServiceImpl implements TimingSendService {
@Resource
private CacheFactory cacheFactory;
@Autowired
@Qualifier("thirdPartyRnr")
private RestTemplate thirdPartyRnr;
@Autowired
@Qualifier("restTemplate")
private RestTemplate restTemplate;
@Resource
private NoticeConfigService noticeConfigService;
@Resource
private IRnrNoticeContentService iRnrNoticeContentService;
@Override
public void sendKafka(List<RnrNoticeContentDTO> list) {
//定义参数格式为json
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
for (RnrNoticeContentDTO rnrNoticeContentDTO : list) {
if (rnrNoticeContentDTO.getCount() <= 10) {
try {
RnrNoticeConfigDTO rnrNoticeConfigDTO1 = noticeConfigService.queryNoticeConfig(rnrNoticeContentDTO.getNoticeConfigId());
if (null != rnrNoticeConfigDTO1) {
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(JSON.parseObject(rnrNoticeContentDTO.getNoticeContent()), headers);
Response ret = null;
//1为域名调用 2为服务名调用
log.info("RnrNoticeConsumer start , url = {},request = {}", rnrNoticeConfigDTO1.getUrl(), rnrNoticeContentDTO.getNoticeContent());
if (1 == rnrNoticeConfigDTO1.getUrlType()) {
ret = RnrMgRestTemplateUtils.postForObject(restTemplate, rnrNoticeConfigDTO1.getUrl(), httpEntity, Response.class);
} else {
ret = RnrMgRestTemplateUtils.postForObject(thirdPartyRnr, rnrNoticeConfigDTO1.getUrl(), httpEntity, Response.class);
}
log.info("RnrNoticeConsumer end , url = {},request = {},response = {}", rnrNoticeConfigDTO1.getUrl(), rnrNoticeContentDTO.getNoticeContent(), JSONObject.toJSONString(ret));
RnrNoticeContentDTO rnrNotice = new RnrNoticeContentDTO();
rnrNotice.setUuid(rnrNoticeContentDTO.getUuid());
if (null == ret || !ret.getSuccess()) {
rnrNotice.setCount(rnrNoticeContentDTO.getCount() + 1);
}else {
rnrNotice.setNoticeStatus(0);
}
iRnrNoticeContentService.update(rnrNotice);
}
} catch (Exception e) {
RnrNoticeContentDTO rnrNotice = new RnrNoticeContentDTO();
rnrNotice.setUuid(rnrNoticeContentDTO.getUuid());
rnrNotice.setCount(rnrNoticeContentDTO.getCount() + 1);
iRnrNoticeContentService.update(rnrNotice);
}
}
}
}
public static void main(String[] args) {
String a = "{iccid=89860900000000000005, orderId=5ea7328ca34442798fe60ade4db6b6a3, oldIccid=null, tenantNo=1, resultCode=3, vin=CUSC0000001000004, manufacturerOrgId=aab1ae4c00d049e99d144d52b945ec5d, orgId=null, rnrBizzType=1}";
Map<String, Object> b = mapStringToMap(a);
System.out.println(JSONObject.toJSONString(b));
Map<String, Object> maps = JSON.parseObject(JSONObject.toJSONString(b),Map.class);
System.out.println(maps);
}
private static Map<String, Object> mapStringToMap(String str) {
str = str.substring(1, str.length() - 1);
String[] strs = str.split(",");
Map<String, Object> map = new HashMap<>();
for (String string : strs) {
String key = string.split("=")[0].trim();
String value = string.split("=")[1];
map.put(key, value);
}
return map;
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
public class Base64ConvertUitl {
private static final Logger logger = LoggerFactory.getLogger(Base64ConvertUitl.class);
private static final String FILE_EXT = "jpg";
private static final String VEDIO_EXT = "mp4";
/**
* 将文件转成base64 字符串
*
* @return
* @throws Exception
*/
public static String encodeBase64File(String path) throws Exception {
File file = new File(path);
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
byte[] encode = new Base64().encode(buffer);
return encode.toString();
}
/**
* 将base64字符解码保存文件
*
* @param base64
*/
public static MultipartFile decoderBase64File(String base64, String tmpDir) {
String sourceFile = tmpDir + UUID.randomUUID() + "." + FILE_EXT;
byte[] content = Base64.decodeBase64(base64);
writeBytesToFile(content, sourceFile);
File file = new File(sourceFile);
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
if (file != null) {
try {
file.delete();//删除本地保存的文件
} catch (Exception e) {
e.printStackTrace();
}
}
return multipartFile;
}
/**
* 将base64字符解码保存文件
* @param base64
* @param tmpDir
* @return
*/
public static MultipartFile decoderBase64File2Video(String base64, String tmpDir) {
String sourceFile = tmpDir + UUID.randomUUID() + "." + VEDIO_EXT;
byte[] content = Base64.decodeBase64(base64);
writeBytesToFile(content, sourceFile);
File file = new File(sourceFile);
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
if (file != null) {
try {
file.delete();//删除本地保存的文件
} catch (Exception e) {
e.printStackTrace();
}
}
return multipartFile;
}
public static FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";
FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true,
file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
public static boolean writeBytesToFile(byte[] content, String sourceFile) {
try (ByteArrayInputStream bis = new ByteArrayInputStream(content);
OutputStream out = new FileOutputStream(sourceFile)) {
byte[] data = new byte[1024];
int size = 0;
while ((size = bis.read(data)) != -1) {
out.write(data, 0, size);
}
out.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 将base64转成视频文件(mp4格式)
*
* @param base64
* @param videoFilePath
*/
public static void decoderBase64ToVideo(String base64, String videoFilePath) {
String[] split = base64.split(",");
if (split.length > 1) {
base64 = String.valueOf(split[1]);
}
//base解密
byte[] videoByte = new byte[0];
FileOutputStream fos = null;
try {
videoByte = new BASE64Decoder().decodeBuffer(base64);
File videoFile = new File(videoFilePath);
//输入视频文件
fos = new FileOutputStream(videoFile);
fos.write(videoByte, 0, videoByte.length);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param base64Str
* @return
*/
public static BufferedImage base64Str2BufferedImage(String base64Str) {
BufferedImage image = null;
try {
InputStream inputStream = baseToInputStream(base64Str);
image = ImageIO.read(inputStream);
} catch (IOException e) {
logger.error("base642BufferedImage error={}", e);
}
return image;
}
/**
* @param base64Str
* @return
*/
private static InputStream baseToInputStream(String base64Str) {
ByteArrayInputStream stream = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64Str);
stream = new ByteArrayInputStream(bytes1);
} catch (Exception e) {
logger.error("baseToInputStream error={}", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stream;
}
/**
* @param bufferedImage
* @return
*/
public static String imageToBase64(BufferedImage bufferedImage) {
Base64 encoder = new Base64();
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, FILE_EXT, baos);
String base64 = new String(encoder.encode((baos.toByteArray())));
return base64;
} catch (IOException e) {
logger.error("imageToBase64 error={}", e);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* @param base64Img
* @param reSize (例如32K 只需要传32 即可)
* @return
*/
public static String resizeImage(String base64Img, int reSize) {
int reSizeK = reSize * 1024;
try {
BufferedImage src = base64Str2BufferedImage(base64Img);
BufferedImage output = Thumbnails.of(src).size(src.getWidth() / 3, src.getHeight() / 3).asBufferedImage();
String base64 = imageToBase64(output);
if (base64.length() > reSizeK) {
output = Thumbnails.of(output).scale(1 / (base64.length() / reSizeK)).asBufferedImage();
base64 = imageToBase64(output);
}
return base64;
} catch (Exception e) {
return base64Img;
}
}
/**
* 转换成大小为32K一下大照片base64
*
* @param base64Img
* @return
*/
public static String resizeImageTo32K(String base64Img) {
boolean resizeFlag = base64Img.length() > 32 * 1024;
try {
while (resizeFlag) {
BufferedImage src = base64Str2BufferedImage(base64Img);
BufferedImage output = Thumbnails.of(src).size(src.getWidth() * 4 / 5, src.getHeight() * 4 / 5).asBufferedImage();
base64Img = imageToBase64(output);
resizeFlag = base64Img.length() > 32 * 1024;
}
return base64Img;
} catch (Exception e) {
return base64Img;
}
}
public static String fileToBase64(File file) {
if (file == null) {
return null;
}
String base64 = null;
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
byte[] buff = new byte[fin.available()];
fin.read(buff);
base64 = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(buff);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fin != null) {
fin.close();
}
if (file != null && file.exists()) {
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return base64;
}
public static void main(String[] args) throws Exception {
String base64 = fileToBase64(new File("E:\\1.jpg"));
System.out.println("原始大小=" + (base64.length() / 1024));
String resizeBase64 = resizeImageTo32K(base64);
System.out.println("压缩大小=" + (resizeBase64.length() / 1024));
System.out.println(resizeBase64);
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import org.apache.commons.lang3.StringUtils;
/**
* Description: 智网sql工具类
* <br />
* CreateDate 2022-07-08 20:31:36
*
* @author yuyi
**/
public class CuscSqlUtils {
private final static String[] keywords =
{"'", "\"", ";", "\\", "*", "-", "+", "%", "master", "truncate", "insert", "select", "delete", "update",
"declare",
"alert", "drop", "and", "exec", "execute", "count", "xp_cmdshell", "declare", "sitename", "mid", "union", "from"};
/**
* Description: 转换sql注入
* <br />
* CreateDate 2022-07-08 20:32:05
*
* @author yuyi
**/
public static String transactSQLInjection(String str) {
if (StringUtils.isEmpty(str)) {
return null;
}
//判断是否包含非法字符
for (String keyword : keywords) {
if (str.indexOf(keyword) != -1) {
str = StringUtils.replace(str, keyword, "");
}
}
return str;
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import com.cusc.nirvana.user.util.CuscStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* Description: 时间工具类
* <br />
* CreateDate 2021-12-08 16:42
*
* @author yuy336
**/
@Slf4j
public class DateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(DateUtil.class);
/**
* 比较两个日期的大小
*
* @param date1 起始日期
* @param date2 结束日期
* @return date1小于date2返回-1,date1大于date2返回1,相等返回0
*/
public static int compareDate(Date date1, Date date2) {
return date1.compareTo(date2);
}
/**
* 计算两个日期之间相差的天数
*
* @param beginDate 起始日期
* @param endDate 结束日期
* @return 相差天数
*/
public static int daysBetween(Date beginDate, Date endDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
beginDate = sdf.parse(sdf.format(beginDate));
endDate = sdf.parse(sdf.format(endDate));
long time1 = beginDate.getTime();
long time2 = endDate.getTime();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
} catch (ParseException e) {
LOGGER.error("DateUtil.daysBetween error ! ", e);
return -1;
}
}
/**
* 计算两个日期之间相差的天数
*
* @param dateStr 日期天厨
* @return 日期类型
*/
public static Date parseDate(String dateStr, String format) {
if (CuscStringUtils.isEmpty(format)) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
try {
return formatter.parse(dateStr);
} catch (ParseException e) {
LOGGER.error("DateUtil.parseDate error ! ", e);
return null;
}
}
//日期格式
public static String yyyyMM = "yyyyMM";
public static String yyyyMMdd = "yyyyMMdd";
public static String yyyyMMddHHmm = "yyyyMMddHHmm";
public static String yyyyMMddHHmmss = "yyyyMMddHHmmss";
public static String yyyyMMddHHmmssS = "yyyyMMddHHmmssS";
public static String yyyyMMddHHmmssSSS = "yyyyMMddHHmmssSSS";
public static String dayChiness = "yyyy年MM月dd日";
public static String dayChinessTwo = "yyyy年MM月dd日HH:mm";
//中划线日期格式
public static String yyyy_MM_dd = "yyyy-MM-dd";
public static String yyyy_MM_dd_HH_mm = "yyyy-MM-dd HH:mm";
public static String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
public static String yyyy_MM_dd_HH_mm_ss_S = "yyyy-MM-dd HH:mm:ss.S";
//反斜杠日期格式
public static String YYYYsMMsDD = "yyyy/MM/dd";
public static String MMsDDsYYYY = "MM/dd/yyyy";
public static String DDsMMsYYYY = "dd/MM/yyyy";
//时间按
public static String MM_dd = "MM-dd";
public static String HH_mm = "HH:mm"; //24小时制
public static String hh_mm = "hh:mm"; //12小时制
public static String HHmm = "HHmm";
public static String hhmm = "hhmm";
//英文日期
public static String ddMMM = "ddMMM"; //09Oct
public static String ddMMMyy = "ddMMMyy"; //01Jan09
public static String ddMMMyyyy = "ddMMMyyyy"; //01Jan2009
public static Calendar getCalendar(Date date) {
try {
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(date);
return calendar;
} catch (Exception e) {
return null;
}
}
public static Calendar getCalendarByDateStr(String dateString, String formater) throws Exception {
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat(formater).parse(dateString));
return calendar;
} catch (Exception e) {
return null;
}
}
/////////////////////////////////////////////////////////////////////////////////////
//----------------------- 取得相隔指定天数的日期 ---------------------------------//
/////////////////////////////////////////////////////////////////////////////////////
public static String BEFORE = "-"; //减少天数
public static String AFTER = "+"; //增加天数
/**
* 取得相隔数量的日期的日期
*
* @param date 指定日期
* @param type BEFORE:往前,AFTER:往后
* @param interval 相隔的日期
*/
public static Date getIntervalDate(Date date, String type, int interval) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.DATE, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.DATE, +interval);
}
return cal.getTime();
}
/**
* 取得相隔数量的日期的日期字符串
*/
public static String getIntervalDateStr(Date date, String formater, String type, int interval) {
Date lastDate = getIntervalDate(date, type, interval);
return DateUtil.toString(lastDate, formater);
}
/**
* 取得相隔数量的月份的日期字符串
*/
public static String getIntervalMonthStr(Date date, String formater, String type, int interval) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.MONTH, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.MONTH, +interval);
}
Date lastDate = cal.getTime();
return DateUtil.toString(lastDate, formater);
}
/**
* 取得两个时间的间隔,于得到的时间为格林尼治时间,相应间去8小时,得到北京时间
*
* @param depTime 出发日期
* @param arrTime 到达日期
*/
public static Date getSpanTime(Date depTime, Date arrTime) {
Date spanTime = new Date();
spanTime.setTime(arrTime.getTime() - depTime.getTime() - 28800000);
return spanTime;
}
public static Date getSpanTime(String depTimeStr, String arrTimeStr) {
Date depTime = DateUtil.toDate(depTimeStr, DateUtil.HH_mm);
Date arrTime = DateUtil.toDate(arrTimeStr, DateUtil.HH_mm);
Date spanTime = new Date();
spanTime.setTime(arrTime.getTime() - depTime.getTime() - 28800000);
return spanTime;
}
public static long getSpanSeconds(Date startTime, Date endTime) {
return endTime.getTime() - startTime.getTime();
}
/**
* 取得当前年、月、日、小时、分、秒等数值
**/
public static int getCurrentYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
public static int getCurrentMonth() {
return Calendar.getInstance().get(Calendar.MONTH);
}
public static int getCurrentDay() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
public static int getCurrentHour12() {
return Calendar.getInstance().get(Calendar.HOUR);
}
public static int getCurrentHour24() {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
public static int getCurrentMinute() {
return Calendar.getInstance().get(Calendar.MINUTE);
}
public static int getCurrentSecond() {
return Calendar.getInstance().get(Calendar.SECOND);
}
/////////////////////////////////////////////////////////////////////////////////////
//---------------------------- 日期类型之间的转换 ---------------------------------//
/////////////////////////////////////////////////////////////////////////////////////
/**
* 把字符串日期类型按照格式转换成Date日期,缺省的日期格式为yyyy-MM-dd
*
* @param dateStr 字符串类型日期
* @param formater 日期格式,缺省为yyyy-MM-dd
*/
public static Date toDate(String dateStr, String formater) {
if (!StringUtils.hasText(dateStr)) {
return null;
}
try {
if (StringUtils.hasText(formater)) {
return new SimpleDateFormat(formater).parse(dateStr);
} else {
return new SimpleDateFormat(yyyy_MM_dd).parse(dateStr);
}
} catch (Exception pe) {
return null;
}
}
/**
* Date类型:不同格式之间的转换
*
* @param oldDate 老的日期
* @param oldFormater 老的日期格式
* @param newFormater 新的日期格式
*/
public static Date toDate(Date oldDate, String oldFormater, String newFormater) {
if (oldDate == null) {return null;}
try {
String oldDateString = DateUtil.toString(oldDate, oldFormater);
return DateUtil.toDate(oldDateString, newFormater);
} catch (Exception pe) {
return null;
}
}
/**
* 把字符串日期类型按照格式转换成Date日期,缺省的日期格式为yyyy-MM-dd
*
* @param dateStr 字符串类型日期
* @param oriFormater 日期格式,缺省为yyyy-MM-dd
* @param oriLocale 语言变量,为NULL使用缺省的Locale
*/
public static Date toDate(String dateStr, String oriFormater, Locale oriLocale) {
//如果语言环境为空,则直接返回toDate(dateStr,formater);
if (oriLocale == null) {
return toDate(dateStr, oriFormater);
}
if (!StringUtils.hasText(dateStr)) {
return null;
}
try {
if (StringUtils.hasText(oriFormater)) {
return new SimpleDateFormat(oriFormater, oriLocale).parse(dateStr);
} else {
return new SimpleDateFormat(yyyy_MM_dd, oriLocale).parse(dateStr);
}
} catch (Exception pe) {
return null;
}
}
/**
* 把日期类型按照格式转换成字符串,缺省的日期格式为yyyy-MM-dd
*
* @param date Date类型日期
* @param dstFormater 日期格式,缺省为yyyy-MM-dd
*/
public static String toString(Date date, String dstFormater) {
try {
//缺省的日期格式为
if (!StringUtils.hasText(dstFormater)) {
return new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
return new SimpleDateFormat(dstFormater).format(date);
}
} catch (Exception e) {
return null;
}
}
/**
* 把日期类型按照格式转换成字符串
*
* @param date Date类型日期
* @param dstFormater 日期格式,缺省为yyyy-MM-dd
*/
public static String toString(Date date, String dstFormater, Locale dstLocale) {
try {
if (!StringUtils.hasText(dstFormater)) {
dstFormater = DateUtil.ddMMMyy;
}
if (dstLocale == null) {
return new SimpleDateFormat(dstFormater).format(date).toUpperCase();
} else {
return new SimpleDateFormat(dstFormater, dstLocale).format(date).toUpperCase();
}
} catch (Exception e) {
return null;
}
}
/**
* 把日期字符串按照格式相互转换
*
* @param oriDateStr 原始日期字符串
* @param oriFormater 日期日期的格式
* @param dstFormater 转换后的日期格式
*/
public static String toString(String oriDateStr, String oriFormater, String dstFormater) {
try {
if (!StringUtils.hasText(oriDateStr)) {
return "";
}
if (!StringUtils.hasText(oriFormater)) {
oriFormater = DateUtil.yyyy_MM_dd;
}
Date date = DateUtil.toDate(oriDateStr, oriFormater);
if (!StringUtils.hasText(dstFormater)) {
dstFormater = DateUtil.yyyy_MM_dd;
}
return new SimpleDateFormat(dstFormater).format(date);
} catch (Exception e) {
return null;
}
}
/**
* 把日期字符串按照格式相互转换(原始日期和目标日期都有LOCALE要求)
*
* @param oriDateStr 原始日期字符串
* @param oriFormater 日期日期的格式
* @param oriLocale 原始日期的LOCALE
* @param dstFormater 目标日期的格式
* @param dstLocale 目标日期的LOCALE
*/
public static String toString(String oriDateStr, String oriFormater, Locale oriLocale, String dstFormater, Locale dstLocale) {
try {
if (!StringUtils.hasText(oriDateStr)) {
return "";
}
if (!StringUtils.hasText(oriFormater)) {
oriFormater = DateUtil.yyyy_MM_dd;
}
Date date = DateUtil.toDate(oriDateStr, oriFormater, oriLocale);
if (!StringUtils.hasText(dstFormater)) {
dstFormater = DateUtil.ddMMMyy;
}
if (dstLocale == null) {
return new SimpleDateFormat(dstFormater).format(date).toUpperCase();
} else {
return new SimpleDateFormat(dstFormater, dstLocale).format(date).toUpperCase();
}
} catch (Exception e) {
return null;
}
}
public static String formatDate(String value, String oldStyle, String newStyle) {
if (!StringUtils.hasText(value)) {
return "";
}
SimpleDateFormat df = new SimpleDateFormat(oldStyle);
SimpleDateFormat df1 = new SimpleDateFormat(newStyle);
try {
return df1.format(df.parse(value));
} catch (ParseException e) {
return "";
}
}
////////////////////////////////////////////////////////////////////////////////////
// 中文日期 ///
////////////////////////////////////////////////////////////////////////////////////
/**
* 取得中文格式的日期 --> 2010年3月5日
*/
public static String getChineseDate(Date d) {
if (d == null) {
return null;
}
String dtrDate = new SimpleDateFormat(yyyyMMdd).format(d);
return dtrDate.substring(0, 4) + "\u5E74" + Integer.parseInt(dtrDate.substring(4, 6)) + "\u6708" + Integer.parseInt(dtrDate.substring(6, 8)) + "\u65E5";
}
/**
* 取得中文格式的日期 --> 2010年03月15日
*/
public static String getChineseYyyyMmDd(Date d) {
if (d == null) {return null;}
String dtrDate = new SimpleDateFormat(yyyyMMdd).format(d);
return dtrDate.substring(0, 4) + "\u5E74" + dtrDate.substring(4, 6) + "\u6708" + dtrDate.substring(6, 8) + "\u65E5";
}
/**
* 取得中文格式的日期 --> 03月15日 16:15
*/
public static String getChineseDateMMddHHss(Date d) {
if (d == null) {
return null;
}
String dtrDate = DateUtil.toString(d, DateUtil.yyyy_MM_dd_HH_mm);
return dtrDate.substring(5, 7) + "\u6708" + dtrDate.substring(8, 10) + "\u65E5" + dtrDate.substring(11);
}
/**
* 取得中文的星期名称
*/
public static String getCnDayNameOfWeek(Date date) {
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar calendar = DateUtil.getCalendar(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
return weeks[day - 1];
}
/**
* 取得中文的星期名称
*/
public static String getCnDayNameOfWeek(String strDate) {
Date date = DateUtil.toDate(strDate, null);
return getCnDayNameOfWeek(date);
}
/**
* 取得月份的序号
*/
public static String getNumberByEnMonth(String enMonthString) {
String[] months = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
for (int i = 0; i < months.length; i++) {
if (months[i].equalsIgnoreCase(enMonthString)) {
if (i < 9) {
return "0" + (i + 1);
}
return Integer.toString(i + 1);
}
}
return null;
}
/**
* 取得相隔数量的【日或者月】的日期
*
* @param date 指定日期
* @param type BEFORE:往前,AFTER:往后
* @param intervalString 相隔的日或者月,格式为 14D/12M【相隔14日/相隔12月】
*/
public static Date getIntervalDate(Date date, String type, String intervalString) {
try {
//14D --> interval=14,dayOrMonth=D
int interval = Integer.valueOf(intervalString.substring(0, intervalString.length() - 1));
String dayOrMonth = intervalString.substring(intervalString.length() - 1);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if ("S".equals(dayOrMonth.toUpperCase())) {
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.SECOND, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.SECOND, +interval);
}
} else if ("I".equals(dayOrMonth.toUpperCase())) {
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.MINUTE, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.MINUTE, +interval);
}
} else if ("H".equals(dayOrMonth.toUpperCase())) {
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.HOUR, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.HOUR, +interval);
}
} else if ("D".equals(dayOrMonth.toUpperCase())) {
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.DATE, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.DATE, +interval);
}
} else if ("M".equals(dayOrMonth.toUpperCase())) {
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.MONTH, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.MONTH, +interval);
}
} else if ("Y".equals(dayOrMonth.toUpperCase())) {
if (DateUtil.BEFORE.equals(type)) {
cal.add(Calendar.YEAR, -interval);
}
if (DateUtil.AFTER.equals(type)) {
cal.add(Calendar.YEAR, +interval);
}
}
return cal.getTime();
} catch (Exception e) {
return null;
}
}
public static Date getIntervalDate(String dateStr, String type, String intervalString) {
Date date = DateUtil.toDate(dateStr, DateUtil.yyyy_MM_dd);
return getIntervalDate(date, type, intervalString);
}
////////////////////////////////////////////////////////////////////////////////////
// 国际化日期 //
////////////////////////////////////////////////////////////////////////////////////
/**
* 根据语言类型获取星期名称
*
* @param date
* @param locale
* @return
*/
public static String getDayofTheWeek(Date date, Locale locale) {
if (locale != null && locale.toString().startsWith(Locale.UK.toString())) {
String[] weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
Calendar calendar = DateUtil.getCalendar(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
return weeks[day - 1];
}
return DateUtil.getCnDayNameOfWeek(date);
}
/**
* 根据语言类型获取日期格式
*
* @param date
* @param locale
* @return
*/
public static String getDate(Date date, Locale locale) {
if (locale != null && locale.toString().startsWith(Locale.UK.toString())) {
return DateUtil.toString(date, DateUtil.MM_dd);
}
return DateUtil.getChineseDate(date).substring(5);
}
/**
* 根据语言类型获取日期格式
*
* @param date
* @param locale
* @return
*/
public static String getFormatDateForUpdateTime(Date date, Locale locale) {
if (locale != null && locale.toString().startsWith(Locale.UK.toString())) {
return DateUtil.toString(date, DateUtil.yyyy_MM_dd_HH_mm);
}
return DateUtil.getChineseDateMMddHHss(date);
}
public static XMLGregorianCalendar date2XMLGregorianCalendar(Date date) {
if (date == null) {
return null;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar xmlCa = null;
try {
xmlCa = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
} catch (Exception e) {
log.error("xml date error", e);
}
return xmlCa;
}
/**
* 对字符串日期信息 进行验证是否合法
*/
public static boolean isValidDate(String strDate) {
SimpleDateFormat parser = new SimpleDateFormat(yyyyMMdd);
parser.setLenient(false);
try {
parser.parse(strDate);
return true;
} catch (Exception e) {
return false;
}
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
* Description: MD5计算工具类
* <br />
* CreateDate 2022-03-11 15:58
*
* @author yuy336
**/
public class Md5CaculateUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(Md5CaculateUtil.class);
/**
* 获取一个文件的md5值(可处理大文件)
*
* @return md5 value
*/
public static String getFileMD5(File file) {
FileInputStream fileInputStream = null;
try {
MessageDigest MD5 = MessageDigest.getInstance("MD5");
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
MD5.update(buffer, 0, length);
}
return new String(Hex.encodeHex(MD5.digest()));
} catch (Exception e) {
LOGGER.error("getFileMD5 error : ", e);
return null;
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
LOGGER.error("getFileMD5 FileInputStream close error : ", e);
}
}
}
/**
* 获取上传文件的md5
*
* @param file
* @return
* @throws IOException
*/
public static String getMd5(MultipartFile file) {
try {
//获取文件的byte信息
byte[] uploadBytes = file.getBytes();
// 拿到一个MD5转换器
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(uploadBytes);
//转换为16进制
return new BigInteger(1, digest).toString(16);
} catch (Exception e) {
LOGGER.error("getMd5 error :", e);
}
return null;
}
/**
* 求一个字符串的md5值
*
* @param target 字符串
* @return md5 value
*/
public static String MD5(String target) {
return DigestUtils.md5Hex(target);
}
public static void main(String[] args) {
System.out.println(MD5("appid=63ba3b58-060e-4c1&timestamp=2022-03-30 17:19:27"
+ ".95&nonce=02252db9af6f44eebc376a8c018699e3&appkey=a56feb3e-b55a-4f2"));
}
}
/*
package com.cusc.nirvana.user.rnr.mg.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.mg.dto.OssDownloadRs;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
@Data
public class OSSUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String bucketName;
private static String prefix;
private static OSS ossClient;
public OSSUtil(String endpoint, String bucketName, String accessKey, String secretKey, String prefix) {
OSSUtil.endpoint = endpoint;
OSSUtil.bucketName = bucketName;
OSSUtil.accessKeyId = accessKey;
OSSUtil.accessKeySecret = secretKey;
OSSUtil.prefix = prefix;
getOSSClient();
}
*/
/**
* 获取oss客户端实例
* @return
*//*
public static OSS getOSSClient(){
// if(null == ossClient){
// // 创建OSSClient实例。
// ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// }
// return ossClient;
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
*/
/**
* 本地文件上传
*
* @param sourceFilePathName 本地文件路径
* @param aimFilePathName 在阿里OSS中保存的可以包含路径的文件名
* @return 返回上传后文件的访问路径
* @throws FileNotFoundException
*//*
public static String upload(String bucketName, String sourceFilePathName, String aimFilePathName) throws FileNotFoundException {
FileInputStream is = new FileInputStream(sourceFilePathName);
if (aimFilePathName.startsWith("/")) {
aimFilePathName = aimFilePathName.substring(1);
}
// 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// int indexOfLastDot = aimFilePathName.lastIndexOf(".");
// String suffix = aimFilePathName.substring(indexOfLastDot);
// metadata.setContentType(getContentType(suffix));
//避免文件覆盖
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, aimFilePathName, is);
//避免访问时将图片下载下来
//putObjectRequest.setMetadata(metadata);
OSS ossClient = getOSSClient();
ossClient.putObject(putObjectRequest);
// 设置URL过期时间为100年
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, aimFilePathName, expiration);
ossClient.shutdown();
return url.toString();
}
*/
/**
* 流上传文件
*
* @param is 文件流
* @param aimFilePathName 在阿里OSS中保存的可以包含路径的文件名
* @return 返回上传后文件的访问路径
* @throws FileNotFoundException
*//*
public static String upload(String bucketName, InputStream is, String aimFilePathName) throws FileNotFoundException {
if (aimFilePathName.startsWith("/")) {
aimFilePathName = aimFilePathName.substring(1);
}
//避免文件覆盖
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, aimFilePathName, is);
//避免访问时将图片下载下来
//putObjectRequest.setMetadata(metadata);
OSS ossClient = getOSSClient();
ossClient.putObject(putObjectRequest);
// 设置URL过期时间为100年
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, aimFilePathName, expiration);
ossClient.shutdown();
return url.toString();
}
*/
/**
* 获取文件大小
*
* @param aimFilePathName 在阿里OSS中保存的可以包含路径的文件名
* @return 返回上传后文件的访问路径
* @throws FileNotFoundException
*//*
public static Double getFileSize(String bucketName, String aimFilePathName) throws FileNotFoundException {
OSS ossClient = getOSSClient();
boolean existFlag = ossClient.doesObjectExist(bucketName, aimFilePathName);
if(!existFlag){
throw new CuscUserException("500","文件不存在");
}
Double fileSize = 0D;
ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, aimFilePathName);
fileSize = Double.valueOf(objectMetadata.getContentLength());
ossClient.shutdown();
return fileSize;
}
*/
/**
* multipartFile实现上传
*
* @param multipartFile
* @return
*//*
public static String upload(String bucketName, MultipartFile multipartFile) throws IOException {
// 获取上传的文件的输入流
InputStream inputStream = multipartFile.getInputStream();
// 获取文件名称
String fileName = multipartFile.getOriginalFilename();
// 拼接fileName
fileName = prefix + fileName;
// 如果需要上传时设置存储类型与访问权限
//ObjectMetadata metadata = new ObjectMetadata();
//metadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
// 上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
//putObjectRequest.setMetadata(metadata);
OSS ossClient = getOSSClient();
ossClient.putObject(putObjectRequest);
//文件访问路径
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
// 关闭ossClient
ossClient.shutdown();
// 把上传到oss的路径返回
return url.toString();
}
*/
/**
* 判断文件是否存在,文件名需要完整路径,
* 如rnr_test/1.jpg
*
* @param objectName
* @return
*//*
public static boolean isFileExist(String bucketName, String objectName) {
OSS ossClient = getOSSClient();
boolean res = ossClient.doesObjectExist(bucketName, objectName);
return res;
}
*/
/**
* 根据文件名获取文件路径
*
* @param bucketName 要下载的文件名
* @param fileName 文件完整名称
* *//*
public static String getFileUrl(String bucketName, String fileName) {
OSS ossClient = getOSSClient();
//文件访问路径
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
// 关闭ossClient
ossClient.shutdown();
return url.toString();
}
*/
/**
* 通过文件名下载文件到本地
*
* @param objectName 要下载的文件名
* @param localFileName 本地要创建的文件名
*//*
public static void downloadFile(String bucketName, String objectName, String localFileName) {
OSS ossClient = getOSSClient();
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName));
// 关闭OSSClient。
ossClient.shutdown();
}
*/
/**
* 通过文件名获取下载流
*
* @param objectName 要下载的文件名
*//*
public static OssDownloadRs downloadFile(String bucketName, String objectName) {
OSS ossClient = getOSSClient();
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
OSSObject object = ossClient.getObject(new GetObjectRequest(bucketName, objectName));
InputStream inputStream = object.getObjectContent();
OssDownloadRs ossDownloadRs = new OssDownloadRs();
ossDownloadRs.setOss(ossClient);
ossDownloadRs.setInputStream(inputStream);
// 关闭OSSClient。
// ossClient.shutdown();
return ossDownloadRs;
}
*/
/**
* 删除文件
*
* @param objectName
*//*
public static void deleteFile(String bucketName, String objectName) {
OSS ossClient = getOSSClient();
ossClient.deleteObject(bucketName, objectName);
ossClient.shutdown();
}
*/
/**
* 批量删除文件或目录
*
* @param keys
*//*
public static void deleteFiles(String bucketName, List<String> keys) {
OSS ossClient = getOSSClient();
// 删除文件。
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
ossClient.shutdown();
}
*/
/**
* 创建文件夹
*
* @param folder
* @return
*//*
public static String createFolder(String bucketName, String folder) {
// 文件夹名
String fileName = folder;
OSS ossClient = getOSSClient();
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, fileName)) {
// 创建文件夹
ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(new byte[0]));
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, fileName);
return object.getKey();
}
ossClient.shutdown();
return fileName;
}
*/
/**
* @return String
* @MethodName: contentType
* @Description: 获取文件类型
*//*
private static String contentType(String fileType) {
fileType = fileType.toLowerCase();
String contentType = "";
if (fileType.equals("bmp")) {
contentType = "image/bmp";
} else if (fileType.equals("gif")) {
contentType = "image/gif";
} else if (fileType.equals("png") || fileType.equals("jpeg") || fileType.equals("jpg")) {
contentType = "image/jpeg";
} else if (fileType.equals("html")) {
contentType = "text/html";
} else if (fileType.equals("txt")) {
contentType = "text/plain";
} else if (fileType.equals("vsd")) {
contentType = "application/vnd.visio";
} else if (fileType.equals("ppt") || fileType.equals("pptx")) {
contentType = "application/vnd.ms-powerpoint";
} else if (fileType.equals("doc") || fileType.equals("docx")) {
contentType = "application/msword";
} else if (fileType.equals("xml")) {
contentType = "text/xml";
} else if (fileType.equals("mp4")) {
contentType = "video/mp4";
} else {
contentType = "application/octet-stream";
}
return contentType;
}
}*/
package com.cusc.nirvana.user.rnr.mg.util;
import com.cusc.nirvana.user.rnr.common.constants.ResponseCode;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.util.CuscStringUtils;
/**
* Description: 参数校验工具类
* <br />
* CreateDate 2021-11-09 17:42
*
* @author yuyi
**/
public class ParameterCheckUtil {
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(String parameter) {
if (CuscStringUtils.isEmpty(parameter)) {
throw new CuscUserException(ResponseCode.PARAMETER_NOT_NULL.getCode() + "",
ResponseCode.PARAMETER_NOT_NULL.getMsg());
}
}
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(String parameter, ResponseCode code) {
if (CuscStringUtils.isEmpty(parameter)) {
throw new CuscUserException(code.getCode() + "", code.getMsg());
}
}
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Integer parameter, ResponseCode code) {
if (parameter == null) {
throw new CuscUserException(code.getCode() + "", code.getMsg());
}
}
/**
* Description: 检查非空
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Integer parameter) {
if (parameter == null) {
throw new CuscUserException(ResponseCode.PARAMETER_NOT_NULL.getCode() + "",
ResponseCode.PARAMETER_NOT_NULL.getMsg());
}
}
/**
* Description: 检查非空-长整型
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Long parameter, ResponseCode code) {
if (parameter == null) {
throw new CuscUserException(code.getCode() + "", code.getMsg());
}
}
/**
* Description: 检查非空-长整型
* <br />
* CreateDate 2021-11-09 17:45:25
*
* @author yuyi
**/
public static void checkNotNull(Long parameter) {
if (parameter == null) {
throw new CuscUserException(ResponseCode.PARAMETER_NOT_NULL.getCode() + "",
ResponseCode.PARAMETER_NOT_NULL.getMsg());
}
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import java.util.ArrayList;
import java.util.List;
/**
* Description: 实名mq工具类
* <br />
* CreateDate 2021-12-08 16:42
*
* @author yuy336
**/
public class RnrMqUtil {
/**
* mq的超时时间
*/
public final static int MQ_TIME_OUT = 3000;
private static List<Integer> defaultLevel;
/**
* 默认层级值
*/
private static int middleDefaultLevelValue = 300;
/**
* 默认层级数,由于延迟一般不超过5分钟,所以折中判断
*/
private static int middleDefaultLevel = 9;
static {
defaultLevel = new ArrayList<>();
defaultLevel.add(1);
defaultLevel.add(5);
defaultLevel.add(10);
defaultLevel.add(30);
defaultLevel.add(60);
defaultLevel.add(120);
defaultLevel.add(180);
defaultLevel.add(240);
defaultLevel.add(300);
defaultLevel.add(360);
defaultLevel.add(420);
defaultLevel.add(480);
defaultLevel.add(540);
defaultLevel.add(600);
defaultLevel.add(1200);
defaultLevel.add(1800);
defaultLevel.add(3600);
defaultLevel.add(7200);
}
/**
* Description: 通过索引获取数值
* <br />
* CreateDate 2022-03-08 14:34:46
*
* @author yuyi
**/
public static int getValue(Integer index) {
return defaultLevel.get(index);
}
/**
* Description: 通过描述获取级别
* <br />
* CreateDate 2022-03-08 14:37:43
*
* @author yuyi
**/
public static int getLevel(int second) {
Integer level = null;
if(second <= middleDefaultLevelValue){
for (int i = middleDefaultLevel - 1; i >= 0; i--) {
int diff = second - defaultLevel.get(i);
if (diff >= 0) {
level = i;
break;
}
}
}else{
for (int i = defaultLevel.size() - 1; i >= middleDefaultLevel; i--) {
int diff = second - defaultLevel.get(i);
if (diff >= 0) {
level = i;
break;
}
}
}
return level + 1;
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.mg.constants.RnrBizzTypeEnum;
import com.cusc.nirvana.user.rnr.mg.constants.RnrOrderType;
import com.cusc.nirvana.user.rnr.mg.constants.RnrStatus;
import com.cusc.nirvana.user.rnr.mg.dto.MgRnrInfoDTO;
import com.cusc.nirvana.user.rnr.mg.dto.RnrOrderDTO;
/**
* @author yubo
* @since 2022-04-26 10:58
*/
public class RnrOrderUtil {
//是否需要创建用户
public static boolean needCreateUser(MgRnrInfoDTO rnrInfoDTO, RnrOrderDTO rnrOrderDTO) {
return rnrInfoDTO.getIsTrust() == 0 &&
(RnrOrderType.SEC_VEHICLE.getCode().equals(rnrOrderDTO.getOrderType())
|| RnrOrderType.NEW_VEHICLE.getCode().equals(rnrOrderDTO.getOrderType()));
}
//订单类型转通知类型
public static RnrBizzTypeEnum orderTypeToNoticeType(int orderType) {
RnrOrderType rnrOrderType = RnrOrderType.getTypeByCode(orderType);
if (rnrOrderType == null) {
throw new CuscUserException("", "不支持发送此类型的工单消息");
}
switch (rnrOrderType) {
case NEW_VEHICLE:
case SEC_VEHICLE:
case COMPANY_NEW_VEHICLE:
case CARMAKER_NEW_VEHICLE:
case ONE_CAR_MORE_CARD_BIND:
return RnrBizzTypeEnum.Bind;
case UNBIND:
case SEC_UNBIND:
case COMPANY_CORPORATION_UNBIND:
case ENTERPRISEUNBIND:
return RnrBizzTypeEnum.Unbound;
case COMPANY_CORPORATION_CHANGE:
return RnrBizzTypeEnum.INFO_CHANGE;
case TBOX_CHANGE:
return RnrBizzTypeEnum.ChangeBinding;
default:
throw new CuscUserException("", "不支持发送此类型的工单消息");
}
}
//审核通过订单类型转成实名状态
public static RnrStatus orderTypeToRnrStatus(int orderType) {
RnrOrderType rnrOrderType = RnrOrderType.getTypeByCode(orderType);
if (rnrOrderType == null) {
throw new CuscUserException("", "不支持此类型的工单消息");
}
switch (rnrOrderType) {
case NEW_VEHICLE:
case SEC_VEHICLE:
case COMPANY_NEW_VEHICLE:
case CARMAKER_NEW_VEHICLE:
case ONE_CAR_MORE_CARD_BIND:
case REBINDING:
return RnrStatus.RNR;
case UNBIND:
case SEC_UNBIND:
case COMPANY_CORPORATION_UNBIND:
return RnrStatus.UNBOUND;
default:
return RnrStatus.INIT;
}
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.user.rnr.mg.util.crypt.Sm4Demo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/SM4")
public class SM4Test {
private static final String key = "89c0Cusc268f5A51";
@PostMapping("")
public String SM4(@RequestBody Sm4Demo demo) {
String text = "0 加密 1 解密";
Integer type = demo.getType();
String value = demo.getValue();
SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes());
if(0==type){
text = sm4.encryptBase64(value);
log.info("{},加密,{}",value, text );
}else if (1 == type){
text = sm4.decryptStr(value);
log.info("{},解密,{}",value, text );
}else{
return text;
}
return text;
}
@PostMapping("/two")
public String SM4Two(@RequestBody Sm4Demo demo) {
String text = "0 加密 1 解密";
List<Sm4Demo.Sm4DemoDeatail> selectList = demo.getDetailList();
SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes());
for (Sm4Demo.Sm4DemoDeatail detailBean : selectList) {
if (!StringUtils.isEmpty(detailBean.getDecryptStr())) {
text = sm4.encryptBase64(detailBean.getDecryptStr());
detailBean.setEncryptStr(text);
log.info("{},加密,{}", detailBean.getDecryptStr(), detailBean.getEncryptStr());
} else if (!StringUtils.isEmpty(detailBean.getEncryptStr())) {
text = sm4.decryptStr(detailBean.getEncryptStr());
detailBean.setDecryptStr(text);
log.info("{},解密,{}", detailBean.getEncryptStr(), detailBean.getDecryptStr());
}
}
return JSON.toJSONString(demo);
}
public static void main(String[] args) {
Sm4Demo sm4Demo = new Sm4Demo();
sm4Demo.setType(1);
List<Sm4Demo.Sm4DemoDeatail> selectList = new ArrayList<>();
Sm4Demo.Sm4DemoDeatail sm4DemoDeatail = new Sm4Demo.Sm4DemoDeatail();
sm4DemoDeatail.setEncryptStr("UkGq7K7w449fvfJO8d0RUrh6pr6Bw0tDzYgpcxQGAcY=");
selectList.add(sm4DemoDeatail);
sm4DemoDeatail = new Sm4Demo.Sm4DemoDeatail();
sm4DemoDeatail.setEncryptStr("I4sDTLoGF4qMV49gFYCHTOHxn7BzKYkeGIFVDLsUhwU=");
selectList.add(sm4DemoDeatail);
sm4DemoDeatail = new Sm4Demo.Sm4DemoDeatail();
sm4DemoDeatail.setDecryptStr("HYQ3D4D17JZ012225");
selectList.add(sm4DemoDeatail);
sm4DemoDeatail = new Sm4Demo.Sm4DemoDeatail();
sm4DemoDeatail.setDecryptStr("HYQ3D4D17JZ012219");
selectList.add(sm4DemoDeatail);
sm4Demo.setDetailList(selectList);
System.out.println(JSON.toJSONString(sm4Demo));
SymmetricCrypto sm4 = SmUtil.sm4(key.getBytes());
String text ="";
for (Sm4Demo.Sm4DemoDeatail detailBean : selectList) {
if(!StringUtils.isEmpty(detailBean.getDecryptStr())){
text = sm4.encryptBase64(detailBean.getDecryptStr());
detailBean.setEncryptStr(text);
log.info("{},加密,{}", detailBean.getDecryptStr(), detailBean.getEncryptStr());
}else if(!StringUtils.isEmpty(detailBean.getEncryptStr())){
text = sm4.decryptStr(detailBean.getEncryptStr());
detailBean.setDecryptStr(text);
log.info("{},解密,{}", detailBean.getEncryptStr(), detailBean.getDecryptStr());
}
}
System.out.println(JSON.toJSONString(sm4Demo));
}
}
package com.cusc.nirvana.user.rnr.mg.util;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Set;
/**
* @author yubo
* @since 2022-04-15 16:07
*/
public class SpringValidationUtil {
/**
* 分组验证参数
* @param <T>
* @param validateData 参数
* @param validateGroup 分组
* @return
*/
public static <T> Set<ConstraintViolation<T>> groupVerificationParameters(T validateData, Class<?>... validateGroup) {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
return validatorFactory.getValidator().validate(validateData, validateGroup);
}
}
package com.cusc.nirvana.user.rnr.mg.util.crypt;
import org.apache.commons.lang3.StringUtils;
/**
* 脱敏工具类
*
* @author yubo
* @since 2022-05-03 10:26
*/
public class DesensitizationUtil {
/**
* 手机号脱敏
*
* @param phone
* @return
*/
public static String desensitizePhone(String phone) {
if (StringUtils.isNotBlank(phone)) {
return phone.replaceAll("(\\w{3})\\w{4}(\\w{4})", "$1****$2");
}
return phone;
}
/**
* 姓名脱敏
*
* @param name
* @return
*/
public static String desensitizeName(String name) {
if (StringUtils.isNotBlank(name)) {
String left = StringUtils.left(name, 1);
return StringUtils.rightPad(left, name.length(), "*");
}
return name;
}
}
package com.cusc.nirvana.user.rnr.mg.util.crypt;
import java.math.BigInteger;
public class HexUtil
{
/**
* 整形转换成网络传输的字节流(字节数组)型数据
*
* @param num 一个整型数据
* @return 4个字节的自己数组
*/
public static byte[] intToBytes(int num)
{
byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & (num >> 0));
bytes[1] = (byte) (0xff & (num >> 8));
bytes[2] = (byte) (0xff & (num >> 16));
bytes[3] = (byte) (0xff & (num >> 24));
return bytes;
}
/**
* 四个字节的字节数据转换成一个整形数据
*
* @param bytes 4个字节的字节数组
* @return 一个整型数据
*/
public static int byteToInt(byte[] bytes)
{
int num = 0;
int temp;
temp = (0x000000ff & (bytes[0])) << 0;
num = num | temp;
temp = (0x000000ff & (bytes[1])) << 8;
num = num | temp;
temp = (0x000000ff & (bytes[2])) << 16;
num = num | temp;
temp = (0x000000ff & (bytes[3])) << 24;
num = num | temp;
return num;
}
/**
* 长整形转换成网络传输的字节流(字节数组)型数据
*
* @param num 一个长整型数据
* @return 4个字节的自己数组
*/
public static byte[] longToBytes(long num)
{
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
bytes[i] = (byte) (0xff & (num >> (i * 8)));
}
return bytes;
}
/**
* 大数字转换字节流(字节数组)型数据
*
* @param n
* @return
*/
public static byte[] byteConvert32Bytes(BigInteger n)
{
byte tmpd[] = (byte[])null;
if(n == null)
{
return null;
}
if(n.toByteArray().length == 33)
{
tmpd = new byte[32];
System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
}
else if(n.toByteArray().length == 32)
{
tmpd = n.toByteArray();
}
else
{
tmpd = new byte[32];
for(int i = 0; i < 32 - n.toByteArray().length; i++)
{
tmpd[i] = 0;
}
System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);
}
return tmpd;
}
/**
* 换字节流(字节数组)型数据转大数字
*
* @param b
* @return
*/
public static BigInteger byteConvertInteger(byte[] b)
{
if (b[0] < 0)
{
byte[] temp = new byte[b.length + 1];
temp[0] = 0;
System.arraycopy(b, 0, temp, 1, b.length);
return new BigInteger(temp);
}
return new BigInteger(b);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @return
*/
public static String getHexString(byte[] bytes)
{
return getHexString(bytes, true);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @param upperCase
* @return
*/
public static String getHexString(byte[] bytes, boolean upperCase)
{
String ret = "";
for (int i = 0; i < bytes.length; i++)
{
ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
}
return upperCase ? ret.toUpperCase() : ret;
}
/**
* 打印十六进制字符串
*
* @param bytes
*/
public static void printHexString(byte[] bytes)
{
for (int i = 0; i < bytes.length; i++)
{
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1)
{
hex = '0' + hex;
}
System.out.print("0x" + hex.toUpperCase() + ",");
}
System.out.println("");
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString)
{
if (hexString == null || hexString.equals(""))
{
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
public static byte charToByte(char c)
{
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 用于建立十六进制字符的输出的小写字符数组
*/
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 用于建立十六进制字符的输出的大写字符数组
*/
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制char[]
*/
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @return 十六进制String
*/
public static String encodeHexString(byte[] data) {
return encodeHexString(data, true);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
* @return 十六进制String
*/
public static String encodeHexString(byte[] data, boolean toLowerCase) {
return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制String
*/
protected static String encodeHexString(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
/**
* 将十六进制字符数组转换为字节数组
*
* @param data 十六进制char[]
* @return byte[]
* @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
*/
public static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("Odd number of characters.");
}
byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常
*/
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch
+ " at index " + index);
}
return digit;
}
/**
* 数字字符串转ASCII码字符串
*
* @param String
* 字符串
* @return ASCII字符串
*/
public static String StringToAsciiString(String content) {
String result = "";
int max = content.length();
for (int i = 0; i < max; i++) {
char c = content.charAt(i);
String b = Integer.toHexString(c);
result = result + b;
}
return result;
}
/**
* 十六进制转字符串
*
* @param hexString
* 十六进制字符串
* @param encodeType
* 编码类型4:Unicode,2:普通编码
* @return 字符串
*/
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char) hexStringToAlgorism(hexString
.substring(i * encodeType, (i + 1) * encodeType));
result += c;
}
return result;
}
/**
* 十六进制字符串装十进制
*
* @param hex
* 十六进制字符串
* @return 十进制数值
*/
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
if (c >= '0' && c <= '9') {
algorism = c - '0';
} else {
algorism = c - 55;
}
result += Math.pow(16, max - i) * algorism;
}
return result;
}
/**
* 十六转二进制
*
* @param hex
* 十六进制字符串
* @return 二进制字符串
*/
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
char c = hex.charAt(i);
switch (c) {
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'A':
result += "1010";
break;
case 'B':
result += "1011";
break;
case 'C':
result += "1100";
break;
case 'D':
result += "1101";
break;
case 'E':
result += "1110";
break;
case 'F':
result += "1111";
break;
}
}
return result;
}
/**
* ASCII码字符串转数字字符串
*
* @param String
* ASCII字符串
* @return 字符串
*/
public static String AsciiStringToString(String content) {
String result = "";
int length = content.length() / 2;
for (int i = 0; i < length; i++) {
String c = content.substring(i * 2, i * 2 + 2);
int a = hexStringToAlgorism(c);
char b = (char) a;
String d = String.valueOf(b);
result += d;
}
return result;
}
/**
* 将十进制转换为指定长度的十六进制字符串
*
* @param algorism
* int 十进制数字
* @param maxLength
* int 转换后的十六进制字符串长度
* @return String 转换后的十六进制字符串
*/
public static String algorismToHexString(int algorism, int maxLength) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
return patchHexString(result.toUpperCase(), maxLength);
}
/**
* 字节数组转为普通字符串(ASCII对应的字符)
*
* @param bytearray
* byte[]
* @return String
*/
public static String byteToString(byte[] bytearray) {
String result = "";
char temp;
int length = bytearray.length;
for (int i = 0; i < length; i++) {
temp = (char) bytearray[i];
result += temp;
}
return result;
}
/**
* 二进制字符串转十进制
*
* @param binary
* 二进制字符串
* @return 十进制数值
*/
public static int binaryToAlgorism(String binary) {
int max = binary.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = binary.charAt(i - 1);
int algorism = c - '0';
result += Math.pow(2, max - i) * algorism;
}
return result;
}
/**
* 十进制转换为十六进制字符串
*
* @param algorism
* int 十进制的数字
* @return String 对应的十六进制字符串
*/
public static String algorismToHEXString(int algorism) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
result = result.toUpperCase();
return result;
}
/**
* HEX字符串前补0,主要用于长度位数不足。
*
* @param str
* String 需要补充长度的十六进制字符串
* @param maxLength
* int 补充后十六进制字符串的长度
* @return 补充结果
*/
static public String patchHexString(String str, int maxLength) {
String temp = "";
for (int i = 0; i < maxLength - str.length(); i++) {
temp = "0" + temp;
}
str = (temp + str).substring(0, maxLength);
return str;
}
/**
* 将一个字符串转换为int
*
* @param s
* String 要转换的字符串
* @param defaultInt
* int 如果出现异常,默认返回的数字
* @param radix
* int 要转换的字符串是什么进制的,如16 8 10.
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt, int radix) {
int i = 0;
try {
i = Integer.parseInt(s, radix);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 将一个十进制形式的数字字符串转换为int
*
* @param s
* String 要转换的字符串
* @param defaultInt
* int 如果出现异常,默认返回的数字
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt) {
int i = 0;
try {
i = Integer.parseInt(s);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 十六进制串转化为byte数组
*
* @return the array of byte
*/
public static byte[] hexToByte(String hex)
throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException();
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
}
return b;
}
/**
* 字节数组转换为十六进制字符串
*
* @param b
* byte[] 需要转换的字节数组
* @return String 十六进制字符串
*/
public static String byteToHex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException(
"Argument b ( byte array ) is null! ");
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xff);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public static byte[] subByte(byte[] input, int startIndex, int length) {
byte[] bt = new byte[length];
for (int i = 0; i < length; i++) {
bt[i] = input[i + startIndex];
}
return bt;
}
}
package com.cusc.nirvana.user.rnr.mg.util.crypt;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class Sm4Demo {
public Sm4Demo() {
this.detailList = new ArrayList<>();
}
private Integer type;
private String value;
private List<Sm4DemoDeatail> detailList =new ArrayList<>();
@Data
public static class Sm4DemoDeatail{
/**
* 加密串
*/
private String encryptStr;
/**
* 解密串
*/
private String decryptStr;
}
}
package com.cusc.nirvana.user.rnr.mg.util.crypt;
import com.cusc.nirvana.user.util.CuscStringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Base64;
/**
* Description: 国密SM4
* <br />
* BC库从1.59版本开始已经基本实现了国密算法(SM2、SM3、SM4)
* CreateDate 2021-11-17 14:37
*
* @author yuyi
**/
public class Sm4Util {
private static final Logger LOGGER = LoggerFactory.getLogger(Sm4Util.class);
//算法名称
public static final String ALGORITHM_NAME = "SM4";
//ECB P5填充
public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
//CBC P5填充
public static final String ALGORITHM_NAME_CBC_PADDING = "SM4/CBC/PKCS5Padding";
//密钥长度
public static final int DEFAULT_KEY_SIZE = 128;
static {
Security.addProvider(new BouncyCastleProvider());
}
private Sm4Util() {
}
/**
* 获取密钥
*
* @return byte
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static byte[] generateKey() throws NoSuchAlgorithmException, NoSuchProviderException {
return generateKey(DEFAULT_KEY_SIZE);
}
/**
* 获取指定长度密钥
*
* @param keySize 密钥的长度
* @return byte
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
*/
public static byte[] generateKey(int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
kg.init(keySize, new SecureRandom());
return kg.generateKey().getEncoded();
}
/**
* ECB P5填充加密
*
* @param key 密钥
* @param data 明文数据
* @return byte
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static byte[] encryptEcbPaddingByte(byte[] key, byte[] data)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException,
NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
/**
* Description: ecb加密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptEcbPadding(String key, String data) {
return encryptEcbPaddingHex(key, data, false, null);
}
/**
* Description: ecb加密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptEcbPaddingHex(String key, String data, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
} else {
keyBytes = key.getBytes();
}
byte[] dataBytes;
if (CuscStringUtils.isNotEmpty(charset)) {
dataBytes = data.getBytes(charset);
} else {
dataBytes = data.getBytes(StandardCharsets.UTF_8);
}
byte[] encrypted = encryptEcbPaddingByte(keyBytes, dataBytes);
return base64Encoder(encrypted);
} catch (Exception e) {
LOGGER.error("Sm4Util.encryptEcbPaddingHex error ! ", e);
return null;
}
}
/**
* ECB P5填充解密
*
* @param key 密钥
* @param cipherText 加密后的数据
* @return byte
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
*/
public static byte[] decryptEcbPaddingByte(byte[] key, byte[] cipherText)
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException {
Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
return cipher.doFinal(cipherText);
}
/**
* Description: ecb解密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptEcbPadding(String key, String data) {
return decryptEcbPaddingHex(key, data, false, null);
}
/**
* Description: ecb解密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptEcbPaddingHex(String key, String data, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
} else {
keyBytes = key.getBytes();
}
byte[] decrypted = decryptEcbPaddingByte(keyBytes, base64Decoder(data));
if (CuscStringUtils.isNotEmpty(charset)) {
return new String(decrypted, charset);
}
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception e) {
LOGGER.error("Sm4Util.decryptEcbPaddingHex error ! ", e);
return null;
}
}
/**
* CBC P5填充加密
*
* @param key 密钥
* @param iv 偏移量
* @param data 明文数据
* @return byte
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidAlgorithmParameterException
*/
public static byte[] encryptCbcPaddingByte(byte[] key, byte[] iv, byte[] data)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
/**
* Description: cbc加密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptCbcPadding(String key, String data, String iv) {
return encryptCbcPaddingHex(key, data, iv, false, null);
}
/**
* Description: cbc加密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String encryptCbcPaddingHex(String key, String data, String iv, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
byte[] ivBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
ivBytes = HexUtil.hexStringToBytes(iv);
} else {
keyBytes = key.getBytes();
ivBytes = iv.getBytes();
}
byte[] dataBytes;
if (CuscStringUtils.isNotEmpty(charset)) {
dataBytes = data.getBytes(charset);
} else {
dataBytes = data.getBytes(StandardCharsets.UTF_8);
}
byte[] encrypted = encryptCbcPaddingByte(keyBytes, ivBytes, dataBytes);
return base64Encoder(encrypted);
} catch (Exception e) {
LOGGER.error("Sm4Util.encryptCbcPaddingHex error ! ", e);
return null;
}
}
/**
* CBC P5填充解密
*
* @param key 密钥
* @param iv 偏移量
* @param cipherText 加密数据
* @return byte
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws InvalidAlgorithmParameterException
*/
public static byte[] decryptCbcPaddingByte(byte[] key, byte[] iv, byte[] cipherText)
throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException {
Cipher cipher = generateCbcCipher(ALGORITHM_NAME_CBC_PADDING, Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
/**
* Description: cbc解密
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptCbcPadding(String key, String data, String iv) {
return decryptCbcPaddingHex(key, data, iv, false, null);
}
/**
* Description: cbc解密,可以指定混淆
* <br />
* CreateDate 2021-11-17 15:53:34
*
* @author yuyi
**/
public static String decryptCbcPaddingHex(String key, String data, String iv, boolean hexString, String charset) {
if (CuscStringUtils.isEmpty(data)) {
return null;
}
try {
byte[] keyBytes;
byte[] ivBytes;
if (hexString) {
keyBytes = HexUtil.hexStringToBytes(key);
ivBytes = HexUtil.hexStringToBytes(iv);
} else {
keyBytes = key.getBytes();
ivBytes = iv.getBytes();
}
byte[] decrypted = decryptCbcPaddingByte(keyBytes, ivBytes, base64Decoder(data));
if (CuscStringUtils.isNotEmpty(charset)) {
return new String(decrypted, charset);
}
return new String(decrypted, StandardCharsets.UTF_8);
} catch (Exception e) {
LOGGER.error("Sm4Util.decryptCbcPaddingHex error ! ", e);
return null;
}
}
/**
* ECB P5填充加解密Cipher初始化
*
* @param algorithmName 算法名称
* @param mode 1 加密 2解密
* @param key 密钥
* @return Cipher
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
*/
private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key)
throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException {
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
cipher.init(mode, sm4Key);
return cipher;
}
/**
* CBC P5填充加解密Cipher初始化
*
* @param algorithmName 算法名称
* @param mode 1 加密 2解密
* @param key 密钥
* @param iv 偏移量
* @return Cipher
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws NoSuchPaddingException
*/
private static Cipher generateCbcCipher(String algorithmName, int mode, byte[] key, byte[] iv)
throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException {
Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(mode, sm4Key, ivParameterSpec);
return cipher;
}
/**
* Description: base64编码
* <br />
* CreateDate 2021-11-17 15:54:52
*
* @author yuyi
**/
private static String base64Encoder(byte[] encrypted) {
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* Description: base64解码
* <br />
* CreateDate 2021-11-17 17:44:13
*
* @author yuyi
**/
private static byte[] base64Decoder(String encrypted) throws IOException {
return Base64.getDecoder().decode(encrypted);
}
}
package com.cusc.nirvana.user.rnr.notice.constants;
/**
* Description: 通知url类型
* <br />
* CreateDate 2021-10-28 12:49:12
*
* @author yuyi
**/
public enum NoticeUrlTypeEnum {
SERVER_NAME(1, "服务名调用"),
IP(2, "ip调用");
private int code;
private String name;
NoticeUrlTypeEnum(int code, String name) {
this.code = code;
this.name = name;
}
public static NoticeUrlTypeEnum getEnumByCode(int code) {
for (NoticeUrlTypeEnum sys : NoticeUrlTypeEnum.values()) {
if (sys.getCode() == code) {
return sys;
}
}
return null;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
package com.cusc.nirvana.user.rnr.notice.converter;
import com.cusc.nirvana.user.rnr.notice.dao.entity.RnrNoticeConfigPO;
import com.cusc.nirvana.user.rnr.notice.dto.RnrNoticeConfigDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 实名通知配置(同一个主体和状态支持多个通知方)(RnrNoticeConfig)表服务接口
*
* @author yuy336
* @since 2022-03-31 15:04:52
*/
@Mapper
public interface RnrNoticeConfigConverter {
RnrNoticeConfigConverter INSTANCE = Mappers.getMapper(RnrNoticeConfigConverter.class);
/**
* Description: do 转 dto
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
RnrNoticeConfigDTO poToDto(RnrNoticeConfigPO bean);
/**
* Description: dto 转 do
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
RnrNoticeConfigPO dtoToPo(RnrNoticeConfigDTO bean);
/**
* Description: do list 转 dto list
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
List<RnrNoticeConfigDTO> poListToDtoList(List<RnrNoticeConfigPO> list);
}
package com.cusc.nirvana.user.rnr.notice.converter;
import com.cusc.nirvana.user.rnr.notice.dao.entity.RnrNoticeContentPO;
import com.cusc.nirvana.user.rnr.notice.dto.RnrNoticeContentDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 实名通知内容(RnrNoticeContent)表服务接口
*
* @author yuy336
* @since 2022-03-31 15:05:11
*/
@Mapper
public interface RnrNoticeContentConverter {
RnrNoticeContentConverter INSTANCE = Mappers.getMapper(RnrNoticeContentConverter.class);
/**
* Description: do 转 dto
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
RnrNoticeContentDTO poToDto(RnrNoticeContentPO bean);
/**
* Description: dto 转 do
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
RnrNoticeContentPO dtoToPo(RnrNoticeContentDTO bean);
/**
* Description: do list 转 dto list
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
List<RnrNoticeContentDTO> poListToDtoList(List<RnrNoticeContentPO> list);
}
package com.cusc.nirvana.user.rnr.notice.converter;
import com.cusc.nirvana.user.rnr.notice.dao.entity.RnrNoticeContentLogPO;
import com.cusc.nirvana.user.rnr.notice.dto.RnrNoticeContentLogDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
/**
* 实名通知内容日志(RnrNoticeContentLog)表服务接口
*
* @author yuy336
* @since 2022-03-31 15:05:28
*/
@Mapper
public interface RnrNoticeContentLogConverter {
RnrNoticeContentLogConverter INSTANCE = Mappers.getMapper(RnrNoticeContentLogConverter.class);
/**
* Description: do 转 dto
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
RnrNoticeContentLogDTO poToDto(RnrNoticeContentLogPO bean);
/**
* Description: dto 转 do
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
RnrNoticeContentLogPO dtoToPo(RnrNoticeContentLogDTO bean);
/**
* Description: do list 转 dto list
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
List<RnrNoticeContentLogDTO> poListToDtoList(List<RnrNoticeContentLogPO> list);
}
package com.cusc.nirvana.user.rnr.notice.converter;
import com.cusc.nirvana.user.rnr.notice.dto.RnrNoticeReqDTO;
import com.cusc.nirvana.user.rnr.notice.dto.ThirdPartyNoticeReqDTO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
/**
* 实名通知Converter
*
* @author yuy336
* @since 2022-03-31 15:04:52
*/
@Mapper
public interface ThirdPartyNoticeConverter {
ThirdPartyNoticeConverter INSTANCE = Mappers.getMapper(ThirdPartyNoticeConverter.class);
/**
* Description: 实名内部请求dto 转 三方通知dto
* <br />
* CreateDate 2021-11-18 15:21:27
*
* @author yuyi
**/
ThirdPartyNoticeReqDTO noticeReqToThirdPartyDto(RnrNoticeReqDTO bean);
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment