mcy 1 year ago
parent 47c9bc7f92
commit 7f26cbab55

@ -0,0 +1,26 @@
package com.ssm;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(scanBasePackages="com.ssm")
@EnableSwagger2
@MapperScan("com.ssm.manage.mapper")
@EnableScheduling
@EnableAspectJAutoProxy
//@ComponentScan(basePackages = {"com.ssm.filter"})
//@ComponentScan(basePackages = {"com.ssm"})
public class DmWebApp {
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(DmWebApp.class, args);
}
}

@ -0,0 +1,111 @@
//package com.ssm.Listener;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.rabbitmq.client.Channel;
//import com.ssm.manage.response.GenericResponse;
//import com.ssm.manage.utils.SessionHelp;
//import com.ssm.core.utils.ChuangLanSmsUtil;
//import com.ssm.manage.entity.AccountTradeRecord;
//import com.ssm.manage.entity.BaseStore;
//import com.ssm.manage.entity.CashSignatureFile;
//import com.ssm.manage.entity.SmsException;
//import com.ssm.manage.query.CashListRequest;
//import com.ssm.manage.service.SsmCashService;
//import com.ssm.manage.utils.Constant;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.amqp.core.Message;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.messaging.handler.annotation.Headers;
//import org.springframework.messaging.handler.annotation.Payload;
//import org.springframework.stereotype.Component;
//
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@Component
//@Configuration
//@Slf4j
//public class SsmCashListener {
// private static final String CASH_TOPIC_CHANGEGE = "cash_exchange";
// private static final String CASH_QUEUE = "cash_queue";
// @Autowired
// private SsmCashService ssmCashService;
//
// /**
// * 监听主队列~
// *
// * @param message
// * @param map
// * @param channel
// * @throws InterruptedException
// * @throws IOException
// */
// @RabbitListener(queues = CASH_QUEUE)
// public void sendMiss(Message message, @Headers Map<String, Object> map, Channel channel) throws InterruptedException, IOException {
// Map map1 = JSON.parseObject(message.getBody(), Map.class);
//// JSONObject jsonObject = JSON.parse(message.getBody());
//// JSONObject parseObject = JSON.parseObject(message.toString());
//// List<CashListRequest> listRequests = parseObject.getJSONArray("cashListRequests").toJavaList(CashListRequest.class);
//// BigDecimal spendMoney = parseObject.getBigDecimal("spendMoney");
//// BigDecimal consumeMoney = parseObject.getBigDecimal("consumeMoney");
//// Integer spendCount = parseObject.getInteger("spendCount");
//// Integer consumeCount = parseObject.getInteger("consumeCount");
//// String projectName = parseObject.getString("projectName");
//// String memberPhone = parseObject.getString("memberPhone");
//
// JSONObject tradeRecordObj = (JSONObject) map1.get("accountTradeRecord");
// AccountTradeRecord accountTradeRecord = tradeRecordObj.toJavaObject(AccountTradeRecord.class);
// JSONObject storeObj = (JSONObject) map1.get("baseStore");
// BaseStore baseStore = storeObj.toJavaObject(BaseStore.class);
//
// if (Constant.account_type_recharge_consume.equals(accountTradeRecord.getAccountType())) {
// if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
// try {
// ChuangLanSmsUtil.sendCashByRechargeSms(baseStore, accountTradeRecord.getMemberPhone(), accountTradeRecord.getAccountSpendMoney(), accountTradeRecord.getAccountConsumeMoney());
// } catch (Exception e) {
// log.error("SsmCashListener.sendMiss:", e);
// //即放入死信队列-推送后续队列内消息即为抢单失败-
// channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
// }
// }
// } else if (Constant.account_type_project_consume.equals(accountTradeRecord.getAccountType())) {//疗程卡支付
// //设置短信账户 发送 否则不发送
// if (StringUtils.isNotBlank(baseStore.getSmsAccount())) {
// try {
// ChuangLanSmsUtil.sendCashByCourseSms(baseStore, accountTradeRecord.getMemberPhone(), accountTradeRecord.getTradeName(), accountTradeRecord.getAccountSpendCount(), accountTradeRecord.getAccountConsumeCount());
// } catch (Exception e) {
// log.error("SsmCashListener.sendMiss:", e);
// //即放入死信队列-推送后续队列内消息即为抢单失败-
// channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
// }
// }
// }
// //手动设置ACK接收确认当前消息消费完毕
// channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
// }
//
// /**
// * 监听死信队列-即发送短信失败
// *
// * @param message
// * @param map
// * @param channel
// * @throws InterruptedException
// * @throws IOException
// */
// @RabbitListener(queues = "deal_queue")
// public static void sendMiss2(Message message, @Headers Map<String, Object> map, Channel channel) throws InterruptedException, IOException {
// String msg = new String(message.getBody(), "UTF-8");
// channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
// log.error("SsmCashListener.sendMiss2:", "短信发送失败");
// }
//
//}

@ -0,0 +1,43 @@
package com.ssm.core.bean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 使
*/
@Component
@Order(2)
@Slf4j
public class MyApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("开始执行MyApplicationRunnerImpl-run方法");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH,1);
Date time = calendar.getTime();
String format1 = format.format(time);
//下一个月1号
format1=format1+"-01";
//执行redis定时任务
redisTask(format1);
System.out.println("MyApplicationRunnerImpl-run方法执行完毕");
}
public void redisTask(String Date){
}
}

@ -0,0 +1,83 @@
package com.ssm.core.util;
import com.ssm.manage.utils.Constant;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.nio.file.Files;
public class Base64DecodedMultipartFileUtil implements MultipartFile {
private final byte[] imgContent;
private final String header;
public Base64DecodedMultipartFileUtil(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new Base64DecodedMultipartFileUtil(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

@ -0,0 +1,232 @@
package com.ssm.core.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.ssm.core.utils.FtpUtils;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class EasyExcelUtil {
private static final String SUFFIX_XLS = ".xls";
private static final String SUFFIX_XLSX = ".xlsx";
private static final String REGEX_EXCEL = ".+(.xls|.xlsx|.XLS|.XLSX)$";
public static String templateResponseExports(String templateFileName, Object obj, List list, HttpServletRequest request, HttpServletResponse response) throws SmsException {
String fileName = System.currentTimeMillis() + SUFFIX_XLSX;
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + FtpUtils.setFileDownloadHeader(request, fileName));
ExcelWriter excelWriter = null;
InputStream stream = null;
try {
stream = EasyExcelUtil.class.getClassLoader().getResourceAsStream(templateFileName);
excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(stream).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.fill(obj, writeSheet);
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(list, fillConfig, writeSheet);
} catch (Exception e) {
log.error("EasyExcelUtil.templateResponseExports:",e);
throw new SmsException(ResponseCode.FILE_DOWNLOAD_FAILED);
} finally {
// 千万别忘记关闭流
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (excelWriter != null) {
excelWriter.finish();
}
}
return fileName;
}
public static String templateResponseExport(String templateFileName, Class<?> clas, List list, HttpServletRequest request, HttpServletResponse response) throws SmsException {
OutputStream out = null;
try {
String fileName = System.currentTimeMillis() + SUFFIX_XLSX;
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + FtpUtils.setFileDownloadHeader(request, fileName));
out = response.getOutputStream();
simpleTemplateFill(templateFileName, clas, list, out);
return fileName;
} catch (IOException e) {
log.error("EasyExcelUtil.templateResponseExport:",e);
throw new SmsException(ResponseCode.FILE_DOWNLOAD_FAILED);
}
}
public static String simpleResponseExport(String sheetName, Class<?> clas, List list, HttpServletRequest request, HttpServletResponse response) throws SmsException {
OutputStream out = null;
try {
String fileName = sheetName + System.currentTimeMillis() + SUFFIX_XLSX;
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + FtpUtils.setFileDownloadHeader(request, fileName));
out = response.getOutputStream();
simpleFill(sheetName, clas, list, out);
return fileName;
} catch (IOException e) {
log.error("EasyExcelUtil.simpleResponseExport:",e);
throw new SmsException(ResponseCode.FILE_DOWNLOAD_FAILED);
}
}
public static void simpleFill(String sheetName, Class<?> clas, List list, OutputStream out) {
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(out, clas)
// 去除默认样式
.useDefaultStyle(false)
// .registerWriteHandler(getStyleStrategy())
.build();
WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
excelWriter.write(list, writeSheet);
} finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}
public static void simpleTemplateFill(String templateFileName, Class<?> clas, List list, OutputStream out) throws SmsException {
// 方案2 分多次 填充 会使用文件缓存(省内存)
ExcelWriter excelWriter = null;
InputStream stream = null;
try {
stream = EasyExcelUtil.class.getClassLoader().getResourceAsStream(templateFileName);
excelWriter = EasyExcel.write(out, clas).withTemplate(stream).build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(list, fillConfig, writeSheet);
} catch (Exception e) {
log.error("EasyExcelUtil.simpleTemplateFill:",e);
throw new SmsException(ResponseCode.FILE_DOWNLOAD_FAILED);
} finally {
// 千万别忘记关闭流
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
log.error("EasyExcelUtil.simpleTemplateFill:",e);
}
}
if (excelWriter != null) {
excelWriter.finish();
}
}
}
public static List simpleWrite(MultipartFile multipartFile, Class<?> clas) throws SmsException {
if (multipartFile == null || !verifyFilename(multipartFile.getOriginalFilename())) {
throw new SmsException(ResponseCode.FILE_UPLOAD_FAILED);
}
try {
// 解析每行结果在listener中处理
ExcelListener listener = new ExcelListener();
InputStream inputStream = multipartFile.getInputStream();
ExcelReader excelReader = EasyExcel.read(inputStream, clas, listener).build();
ReadSheet readSheet = new ReadSheet();
readSheet=EasyExcel.readSheet(0).build();
excelReader.read(readSheet);
return listener.getDatas();
} catch (IOException e) {
log.error("EasyExcelUtil.simpleWrite:",e);
}catch (Exception e){
log.error("Exception:",e);
throw new SmsException(ResponseCode.FILE_UPLOAD_FAILED);
}
throw new SmsException(ResponseCode.FILE_UPLOAD_FAILED);
}
public static List simpleWrite(MultipartFile multipartFile, Class<?> clas, int headRowNumber) throws SmsException {
if (multipartFile == null || !verifyFilename(multipartFile.getOriginalFilename())) {
throw new SmsException(ResponseCode.FILE_UPLOAD_FAILED);
}
try {
// 解析每行结果在listener中处理
ExcelListener listener = new ExcelListener();
InputStream inputStream = multipartFile.getInputStream();
ExcelReader excelReader = EasyExcel.read(inputStream, clas, listener).build();
ReadSheet readSheet = EasyExcel.readSheet(0).build();
readSheet.setHeadRowNumber(headRowNumber);
excelReader.read(readSheet);
return listener.getDatas();
} catch (IOException e) {
log.error("EasyExcelUtil.simpleWrite:",e);
}
throw new SmsException(ResponseCode.FILE_UPLOAD_FAILED);
}
public static boolean verifyFilename(String fileName) {
Matcher matcher = Pattern.compile(REGEX_EXCEL).matcher(fileName);
return matcher.matches();
}
/**
*
*/
public static HorizontalCellStyleStrategy getStyleStrategy() {
//内容样式策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置 自动换行
contentWriteCellStyle.setWrapped(true);
// 字体策略
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short) 12);
contentWriteCellStyle.setWriteFont(contentWriteFont);
//头策略使用默认
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setShrinkToFit(false);
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
}
public static CellStyle cellStyle(Workbook workbook) {
CellStyle cellStyle = workbook.createCellStyle();
//居中
cellStyle.setAlignment(HorizontalAlignment.LEFT);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
//设置边框
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
return cellStyle;
}
}

@ -0,0 +1,58 @@
package com.ssm.core.util;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class ExcelListener<T> extends AnalysisEventListener<T> {
/**
* data
*
*/
private List<T> datas = new ArrayList<>();
/**
* AnalysisContext sheet
*/
@Override
public void invoke(T t, AnalysisContext context) {
//数据存储到list供批量处理或后续自己业务逻辑处理。
datas.add(t);
//根据业务自行 do something
doSomething();
/*
if(datas.size()<=100){
datas.add(object);
}else {
doSomething();
datas = new ArrayList<Object>();
}
*/
}
/**
*
*/
private void doSomething() {
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
/*
datas.clear();
*/
}
public List<T> getDatas() {
return datas;
}
public void setDatas(List<T> datas) {
this.datas = datas;
}
}

@ -0,0 +1,74 @@
package com.ssm.core.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
public class ExcelUtils {
public static Workbook readExcel(String filePath) throws IOException {
Workbook wb = null;
if(filePath==null){
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = null;
is = new FileInputStream(filePath);
if(".xls".equals(extString)){
wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(extString)){
wb = new XSSFWorkbook(is);
}else{
wb = null;
}
return wb;
}
public static Workbook readExcel(String fileName,InputStream inputStream) throws IOException {
if(fileName.endsWith(".xls")){
return new HSSFWorkbook(inputStream);
}else if(fileName.endsWith(".xlsx")){
return new XSSFWorkbook(inputStream);
}else{
return null;
}
}
public static Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
if(cell.getCellTypeEnum().equals(CellType.STRING)){
value = cell.getRichStringCellValue().getString();
}else if(cell.getCellTypeEnum().equals(CellType.NUMERIC)){
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
}else if(cell.getCellTypeEnum().equals(CellType.BOOLEAN)){
value = cell.getBooleanCellValue();
// }else if(cell.getCellTypeEnum().equals(CellType.BLANK)){
}
return value;
}
}

@ -0,0 +1,82 @@
package com.ssm.core.util;
import org.apache.poi.hssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
public class ExportExcel<T> {
public void exportExcel(String[] headers,Collection<T> dataset, String fileName,HttpServletResponse response) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(fileName);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 20);
// 产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
try {
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射根据javabean属性的先后顺序动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
// 其它数据类型都当作字符串简单处理
if(value != null && value != ""){
textValue = value.toString();
}
if (textValue != null) {
HSSFRichTextString richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
}
getExportedFile(workbook, fileName,response);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* : EXCEL
* @return
*/
public void getExportedFile(HSSFWorkbook workbook, String name,HttpServletResponse response) throws Exception {
BufferedOutputStream fos = null;
try {
String fileName = name + ".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
fos = new BufferedOutputStream(response.getOutputStream());
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
fos.close();
}
}
}
}

@ -0,0 +1,366 @@
package com.ssm.core.util;
import cn.hutool.core.text.StrBuilder;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.BeiSenResponse;
import com.ssm.manage.entity.RefundOrderList;
import com.ssm.manage.entity.SmsMessages;
import com.ssm.manage.excelEntity.ExcelCourseMoney;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.xml.transform.Source;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
public class Http {
// public static void main(String[] args) throws Exception{
// HttpClient httpClient = HttpClients.createDefault();
// HttpPost httpPost = new HttpPost("https://api.4321.sh/sms/send");
// httpPost.addHeader("Content-Type","application/json");
// Map<String,Object> map = new HashMap<>();
// map.put("apikey","N714828db9");
// map.put("secret","71482cf8d1725360");
// map.put("sign_id","141506");
// map.put("mobile","13169783923");
// map.put("content","短信内容");
// String json = JSON.toJSONString(map);
// httpPost.setEntity(new StringEntity(json,"UTF-8"));
// HttpResponse response = httpClient.execute(httpPost);
// HttpEntity entity = response.getEntity();
// String res = EntityUtils.toString(entity);
// System.out.println(res);
// }
// public static void main(String[] args) {
// //1、创建一个文件对象
// File excelFile = new File("C:\\Users\\Administrator\\Downloads/订单表.xlsx");
// //2、判断文件是否存在不存在则创建一个Excel文件
// if (!excelFile.exists()) {
// try {
// excelFile.createNewFile();//创建一个新的文件
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// //3、指定需要那个class去写。然后写到第一个sheet名字为模版然后文件流会自动关闭
// EasyExcel.write(excelFile, ExcelCourseMoney.class).sheet("订单模版").doWrite(data());
// }
//
// public static List<ExcelCourseMoney> data(){
// //创建一个List集合 LC JZ NT A
// List ExcelCourseMoney = new ArrayList<>();
//
// /*
// *xls版本的Excel最多一次可写0 ...65535行
// * xlsx 版本的Excel最多一次可写0...1048575行
// */
// //超出报异常java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
// for (int i=0;i<65535;i++){
// ExcelCourseMoney data = new ExcelCourseMoney();
// data.setStartTime("20220224"+(i+1));
// data.setEndTime("商品名称"+i);
// data.setStoreName("45"+i);
// data.setOpenning(BigDecimal.ZERO);
// data.setBalance(BigDecimal.ZERO);
// data.setCourseMoney(BigDecimal.ZERO);
// data.setCourseRepay(BigDecimal.ZERO);
// data.setCashRefund(BigDecimal.ZERO);
// data.setCoursePromotion(BigDecimal.ZERO);
// data.setInit(BigDecimal.ZERO);
// data.setCourseTurnStore(BigDecimal.ZERO);
// data.setCardChange(BigDecimal.ZERO);
// data.setCourseRepayMoney(BigDecimal.ZERO);
// data.setCashMoney(BigDecimal.ZERO);
// data.setCourseRefundMoney(BigDecimal.ZERO);
// data.setCourseTurnCharge(BigDecimal.ZERO);
// data.setCourseTurnStoreMoney(BigDecimal.ZERO);
// ExcelCourseMoney.add(data);
// }
//
// return ExcelCourseMoney;//返回list集合
// }
public static void main(String[] args) throws Exception {
System.out.println(new SnowflakeUtil(1023));
String email = "0000000001@qq.com";
String substring = email.substring(0, 10);
System.out.println(substring);
int parseInt = Integer.parseInt(substring);
System.out.println(parseInt);
// Long lojj = 462349002668224512L;
// LocalDate today = LocalDate.now();
//
// // 获取昨天的日期
// LocalDate yesterday = today.minusDays(1);
// String time = yesterday.toString();
// String starttime = time+" 00:00:00";
// String endtime = time+" 23:59:59";
// // 打印结果
// System.out.println("今天的日期: " + starttime);
// System.out.println("昨天的日期: " + endtime);
// String stfikj = "w0001";
// String substring1 = stfikj.substring(1);
//
// String res= "{\n" +
// "\t\"access_token\": \"X4eTEiMr-8gOE0yuGgrbzDoHLgAPjsbIqNkJ-AxejxHoHml-Iz0oEEe9zvFJ2I60-jfw3j7bc\",\n" +
// "\t\"token_type\": \"bearer\",\n" +
// "\t\"expires_in\": 7200,\n" +
// "\t\"refresh_token\": \"Z0HaROZY-Fi1zWmOarWVfyFoifLWb-V-eKwafhZbw6KBsog-dF6S3iv30LClJ8MCYXh1hhNO9\"\n" +
// "}";
// BeiSenResponse beiSenResponse = JSON.parseObject(res,BeiSenResponse.class);
// System.out.println("beiSenResponse = " + beiSenResponse);
// String property = System.getProperty("user.dir");
// System.out.println(property);
// String ste = "http:ss%s";
// String rrrr = String.format(ste, "rrrr");
// System.out.println(rrrr);
// String errorMessage = SmsMessages.Fields.errorMessage;
// System.out.println(errorMessage);
// long timestamp = 1698810670000L;
// Instant instant = Instant.ofEpochMilli(timestamp);
// LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// System.out.println(localDateTime.toString());
// int cc = 10000;
// int bb = 10000;
// System.out.println(cc==bb);
// String num = "20230919002";
// int i1 = Integer.parseInt(num.substring(8));
// System.out.println(i1 + 1);
// String s2 = JSON.toJSONString("{type: 1,memberId: 415976925485662208,memberName: 温竣翔,mobilePhone: 13751714617,compensation: 0,refundType: ,refundAccount: null,refundReason: ,refundNumber:1,sourceDocNum: 0120230907002,payee: ,refundMoney: 0,courseListRequest: [{mobilePhone:13751714617,memberName:温竣翔,memberId:415976925485662208,courseProjectName:结业门店转卡消耗美容疗程代码,courseCompensation:0,manageStaffName:,refundNumber:1,courseRefundMoney:0,debtMoney:null,kaiKaDate:null,anotherName:null,entities:[],salesmanList:null,courseAccountId:417828171493376000,storeId:369234373443874816,storeName:总店,courseNum:0120230907002,courseProjectId:370516178726032323,courseProjectNum:11000003,courseProjectMoney:0,courseCount:1,courseStandardCount:1,courseStandardMoney:0,courseRestCount:1,courseConsumeCount:1,courseType:2,endTime:null,updateBy:null,updateId:null,updateTime:null,price:0,courseRestPrice:0,courseConsumePrice:0,storeNum:null,courseProjectMoneys:0,courseCounts:1,unrecordedNumber:null,unrecordedAmount:0,promotionDocId:417828057518047232,cancelMoney:0,cancelNum:null,expenditureMoney:null,explainModify:null,salesmens:[],staffLists:[{id:370759919093182464,staffName:周文娟,brandNumber:903,identityCard:null,ratio:100},{ratio:0}]}, {mobilePhone: 13751714617,memberName: 温竣翔,memberId:415976925485662208,courseProjectName: T-健康养生洗,courseCompensation: 0,manageStaffName: ,refundNumber: 10,courseRefundMoney: 980,debtMoney: null,kaiKaDate: null,anotherName: null,entities: [],salesmanList: null,courseAccountId: 417828057672327168,storeId: 369234373443874816,storeName: 总店,courseNum: 0120230907002,courseProjectId: 370516522705096861,courseProjectNum: 30500001,courseProjectMoney: 980,courseCount: 10,courseStandardCount: 10,courseStandardMoney: 980,courseRestCount: 10,courseConsumeCount: 10,courseType: 1,endTime: null,updateBy: null,updateId: null,updateTime: null,price: 98,courseRestPrice: 980,courseConsumePrice: 980,storeNum: null,courseProjectMoneys: 980,courseCounts: 10,unrecordedNumber: null,unrecordedAmount: 0,promotionDocId: 417828057518047232,cancelMoney: 0,cancelNum: null,expenditureMoney: null,explainModify: null,salesmens: [],staffLists: [{staffName: ,brandNumber: ,ratio: 100}]}]}");
// System.out.println("s2 = " + s2);
// // \u000d System.out.println("coder Hydra");
// //\u000d\u0054\u0068\u0072\u0065\u0061\u0064\u002e\u0073\u006c\u0065\u0065\u0070\u0028\u0032\u0030\u0030\u0030\u0029\u003b
// Float f = 0.01F;
// Double d = 0.01D;
// Double a = f.doubleValue();
// System.out.println(a);
// System.out.println(BigDecimal.valueOf(f));
// System.out.println(BigDecimal.valueOf(d));
// System.out.println(f);//0.01
// System.out.println(d);//0.01
// BigDecimal bigDecimal1 = new BigDecimal(f);
// BigDecimal bigDecimal2 = new BigDecimal(Float.toString(f));
// BigDecimal bigDecimal3 = new BigDecimal(d);
// BigDecimal bigDecimal4 = new BigDecimal(Double.toString(d));
// System.out.println(bigDecimal1);//0.00999999977648258209228515625
// System.out.println(bigDecimal1.floatValue());//0.01
// System.out.println(bigDecimal2);//0.01
// System.out.println(bigDecimal3);//0.01000000000000000020816681711721685132943093776702880859375
// System.out.println(bigDecimal3.doubleValue());//0.01
// System.out.println(bigDecimal4);//0.01
//
// System.out.println(AESUtils.decrypt("7ea529d4b30354d7875b73d41631fd55"));
///**
// * 尊敬的.{}会员:您本次消费.{}次,消费赠送.{}次,剩余.{}次,剩余赠送.{}次。欢迎您再次莅临!本店的联系电话.{}客服热线18620905828
// */
//
///**
// * 现金消费
// * "尊敬的"+memberName+"会员:您本次消费【"+projectName+"】【" +projectTime+
// * "】次。欢迎您再次莅临客服热线18620905828";
// */
///**
// * 充值卡消费
// *
// * "尊敬的"+memberName+"会员:您本次消费折后金额"+ (spendMoney.add(giftspendMoney)).setScale(2,BigDecimal.ROUND_HALF_UP) +"元," +
// * "使用赠送金额"+giftspendMoney.setScale(2,BigDecimal.ROUND_HALF_UP)+"元"+
// * ",会员卡内余额"+ restMoney.setScale(2,BigDecimal.ROUND_HALF_UP) +"元。赠送卡内余额"+giftRestMoney.setScale(2,BigDecimal.ROUND_HALF_UP)+
// * "元。欢迎您再次莅临客服热线18620905828";
// */
///**
// * 购买疗程
// * "【"+courseList.getProjectName()+"】次数"+courseList.getNumberTimes()+"次赠送次数0次。"
// * "尊敬的"+memberName+"会员:您本次购买" + projectName + "欢迎您再次莅临客服热线18620905828";
// */
//
///**
// * 充值开卡
// * "尊敬的"+rechargeAccount.getMemberName()+"会员:您本次充值金额为【"+rechargeMoney.setScale(2,BigDecimal.ROUND_HALF_UP)+"】" +
// * "元,赠送金额为【"+gifMoney.setScale(2,BigDecimal.ROUND_HALF_UP)+"】元,会员卡余额为【"
// * +rechargeAccount.getCardRestMoney().setScale(2,BigDecimal.ROUND_HALF_UP)+"】元" +
// * ",赠送余额为【"+rechargeAccount.getCardGiftMoney()+"】元。欢迎您再次莅临客服热线18620905828";
// */
// //
//
//
//
// String profix = "尊敬的${memberName}会员:您本次消费${numberTime}次,消费赠送${giftTime}次," +
// "剩余${remainderTime}次,剩余赠送${remainderGiftTime}次。欢迎您再次莅临!本店的联系电话${storePhone}";
// String memberName = "陆秀冲";
// String numberTime = String.valueOf(2);
// String giftTime = String.valueOf(0);
// String remainderTime = String.valueOf(8);
// String remainderGiftTime = String.valueOf(0);
// String storePhone = "15913619401";
// Map<String,String> hash = new HashMap<>();
// hash.put("memberName",memberName);
// hash.put("numberTime",numberTime);
// hash.put("giftTime",giftTime);
// hash.put("remainderTime",remainderTime);
// hash.put("remainderGiftTime",remainderGiftTime);
// hash.put("storePhone",storePhone);
// String s = smsReplace(hash, profix);
// System.out.println("s = " + s);
//
// String postfix = "尊敬的${memberName}会员:您本次消费${numberTime}次," +
// "剩余${remainderTime}次。欢迎您再次莅临!本店的联系电话${storePhone}客服热线18620905828";
// String s1 = smsReplace(hash, postfix);
// System.out.println("s1 = " + s1);
//
// //尊敬的陆秀冲会员您本次消费2次消费赠送0次剩余8次剩余赠送0次。欢迎您再次莅临本店的联系电话15913619401客服热线18620905828
//
// //尊敬的陆秀冲会员您本次消费2次剩余8次。欢迎您再次莅临本店的联系电话15913619401客服热线18620905828
//
//
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(new Date());
// calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-2);
// SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
// String format = simpleDateFormat1.format(calendar.getTime());
// System.out.println(format);
// Date parse = simpleDateFormat1.parse(format);
// calendar.setTime(parse);
// calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DATE));
// String format1 = simpleDateFormat1.format(calendar.getTime());
// calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMinimum(Calendar.DATE));
// String format2 = simpleDateFormat1.format(calendar.getTime());
// System.out.println(format1+"-------"+format2);
// format2 = format2 + " 00:00:00";
// format1 = format1 + " 23:59:59";
// System.out.println(format1+"-------"+format2);
//
//
//
// System.out.println(parse);
// System.out.println(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
// String date = "202307";
// int i = Integer.parseInt(date);
// int x = i-1;
// String newDate = String.valueOf(x);
// System.out.println(date);
// System.out.println(newDate);
// Date date1 = new Date();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//// simpleDateFormat.
// System.out.println(BigDecimal.valueOf(5));
// System.out.println(BigDecimal.valueOf(Double.valueOf(5)));
//
//// int i ;
//// while (true){
//// i = 1;
//// i = 2;
//// System.out.println(i);
//// if(i==1){
//// System.out.println(i);
//// break;
//// }
//// }
// List<Integer> list = new ArrayList<>();
// list.add(1);
// list.add(2);
// list.add(3);
// list.add(4);
// list.add(5);
// boolean b = list.stream().anyMatch(item -> {
// System.out.println(item);
// return item > 3;
// });
// System.out.println(new BigDecimal(0.1));
// System.out.println(new BigDecimal("0.1"));
// System.out.println(AESUtils.decrypt("7ea529d4b30354d7875b73d41631fd55"));
//// System.out.println(new BigDecimal("1").add(null));
// String docNum = "LCA00120230426001";
// System.out.println(docNum.length());
// System.out.println(docNum.substring(docNum.length() - 11, docNum.length() - 3));
// RefundOrderList refundOrderList = new RefundOrderList();
// refundOrderList.setStoreNum("A128");
// System.out.println(refundOrderList.getStoreNum().length());
// System.out.println(docNum.substring(11+refundOrderList.getStoreNum().length()));
// int mm = Integer.parseInt(docNum.substring(11+refundOrderList.getStoreNum().length())) + 1;
// System.out.println(mm);
//// String decrypt = AESUtils.decrypt("19128280160");
//// String encrypt = AESUtils.encrypt("19128280160");
//// System.out.println(encrypt);
// //LCA001 20230325 001
// //ZLCA001 20230325 001
// //LC001 20230325 001
// //ALC001 202325 001
//// docNum.su
//// ssmCourseService.selectOne()
// String substring = docNum.substring(docNum.length()-11, docNum.length() - 3);
// System.out.println(substring);
// StrBuilder strBuilder = new StrBuilder(substring);
// StrBuilder insert = strBuilder.insert(6, "-").insert(4, "-");
// System.out.println(insert);
//// String date = "9430-07-11";
//// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//// Date parse = simpleDateFormat.parse(date);
//// String format = simpleDateFormat.format(parse);
//// System.out.println(parse);
//// System.out.println(format);
//// Date parse1 = (Date) JSON.parse(date);
//// System.out.println(parse1);
//// int yyyy = 2023;
//// int date = 3;
//// Date date1 = new Date();
//// System.out.println(date1);
//// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
//// String format = simpleDateFormat.format(date1);
//// System.out.println(format);
//// try {
//// Date parse = simpleDateFormat.parse(yyyy+"-0"+date);
//// String date = "2022-06";
//// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
//// try {
//// Date parse = simpleDateFormat.parse(date);
//// System.out.println(parse.before(new Date()));
//// } catch (ParseException e) {
//// e.printStackTrace();
//// }
}
private static String smsReplace(Map<String, String> hash, String postfix) {
String replace = postfix.replace("${memberName}", hash.get("memberName"));
String replace1 = replace.replace("${courseName}", hash.get("courseName"));
String replace2 = replace1.replace("${courseNumberTime}", hash.get("courseNumberTime"));
String replace3 = replace2.replace("${courseGiftNumberTime}", hash.get("courseGiftNumberTime"));
String replace4 = replace3.replace("${courseReaminderTime}", hash.get("courseReaminderTime"));
String replace5 = replace4.replace("${courseReaminderGiftTime}", hash.get("courseReaminderGiftTime"));
String replace6 = replace5.replace("${rechargeMoney}", hash.get("rechargeMoney"));
String replace7 = replace6.replace("${rechargeGiftMoney}", hash.get("rechargeGiftMoney"));
String replace8 = replace7.replace("${rechargeRestMoney}", hash.get("rechargeRestMoney"));
String replace9 = replace8.replace("${rechargeGiftRestMoney}", hash.get("rechargeGiftMoney"));
String replace10 = replace9.replace("${projectName}", hash.get("projectName"));
String replace11 = replace10.replace("${projectTime}", hash.get("projectTime"));
String replace12 = replace11.replace("${rechargeCashMoney}", hash.get("rechargeCashMoney"));
String replace13 = replace12.replace("${rechargeSpendGeneralMoney}", hash.get("rechargeSpendGeneralMoney"));
String replace14 = replace13.replace("${rechargeSpendGiftMoney}", hash.get("rechargeSpendGiftMoney"));
String replace15 = replace14.replace("${courseCashTime}", hash.get("courseCashTime"));
String replace16 = replace15.replace("${courseGiftCashTime}", hash.get("courseGiftCashTime"));
String replace17 = replace16.replace("${storePhone}", hash.get("storePhone"));
String replace18 = replace17.replace("${customerPhone}", hash.get("customerPhone"));
return replace18;
}
}

@ -0,0 +1,37 @@
package com.ssm.core.util;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* 访ip
*/
public class IpUtil {
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 获取到多个ip时取第一个作为客户端真实ip
if (StringUtils.isNotEmpty(ip) && ip.contains(",")) {
String[] ipArray = ip.split(",");
if (ArrayUtils.isNotEmpty(ipArray)) {
ip = ipArray[0];
}
}
return ip;
}
}

@ -0,0 +1,99 @@
package com.ssm.core.util;
import com.ssm.core.utils.AESUtils;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.jasypt.util.text.BasicTextEncryptor;
import java.math.BigDecimal;
import java.util.Random;
/**
* @Created with Intellij IDEA
* @Author :
* @Date : 2018/5/18 - 10:37
* @Copyright (C), 2018-2018
* @Descripition : Jasypt
*/
public class JasyptUtils {
/**
* Jasypt
*
* @param password jasypt.encryptor.password
* @param value
* @return
*/
public static String encryptPwd(String password, String value) {
PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
encryptOr.setConfig(cryptOr(password));
String result = encryptOr.encrypt(value);
return result;
}
/**
*
*
* @param password jasypt.encryptor.password
* @param value
* @return
*/
public static String decyptPwd(String password, String value) {
PooledPBEStringEncryptor encryptOr = new PooledPBEStringEncryptor();
encryptOr.setConfig(cryptOr(password));
String result = encryptOr.decrypt(value);
return result;
}
/**
* @param password salt
* @return
*/
public static SimpleStringPBEConfig cryptOr(String password) {
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(password);
config.setAlgorithm(StandardPBEByteEncryptor.DEFAULT_ALGORITHM);
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName(null);
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
return config;
}
public static void main(String[] args) throws Exception {
// String docnum = "SYA00620230814001";
// String substring = docnum.substring(docnum.length() - 11, docnum.length() - 5);
// System.out.println("substring = " + substring);
//spring.datasource.url=jdbc:mysql://127.0.0.1:3306/dcmy-newedition?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8&allowMultiQueries=true
//spring.datasource.username=ENC(O1BQh3ko5C6HZslX7Mi6Yw==)
//spring.datasource.password=ENC(jrlD4uGPqs4isJc70wkGgdX8IeVhqlaigr9NmoZU/gnB+u0J6mUBZZEI2zPu1E9rvkTEjt/EsIRzGpLHy88080PchNTKTTRxX7UwIeWgDAsMxW/wwdUBCct8a2NvAw27hVPFuD8KXSD5uEa9eQMl8Ws+t7vWnfDufO+cA9NVgZe+ngaRITTegg/XKCZkGo/JtjQY54UKF0+EtiCGuBTYbP5L+xeI8u9K7pcA1zEtVwoAoS5MkTlVtqV8FycWJKAc)
//spring.datasource.username=ENC(O1BQh3ko5C6HZslX7Mi6Yw==)
//spring.datasource.password=ENC(jrlD4uGPqs4isJc70wkGgdX8IeVhqlaigr9NmoZU/gnB+u0J6mUBZZEI2zPu1E9rvkTEjt/EsIRzGpLHy88080PchNTKTTRxX7UwIeWgDAsMxW/wwdUBCct8a2NvAw27hVPFuD8KXSD5uEa9eQMl8Ws+t7vWnfDufO+cA9NVgZe+ngaRITTegg/XKCZkGo/JtjQY54UKF0+EtiCGuBTYbP5L+xeI8u9K7pcA1zEtVwoAoS5MkTlVtqV8FycWJKAc)
// System.out.println(AESUtils.encrypt("13927759532"));
// System.out.println(AESUtils.encrypt("1392779532"));
// System.out.println(AESUtils.encrypt("root123456"));
// System.out.println(AESUtils.decrypt("993f014869ca9314b5edcb80eca2eb1f"));
// System.out.println(AESUtils.encrypt("13662780023"));
//// 'spring.datasource.username=ENC(O1BQh3ko5C6HZslX7Mi6Yw==)\nspring.datasource.password=ENC(TJU64ImcZASn8YLoEFQLOA==)';
// System.out.println(AESUtils.encrypt("13543507408"));
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需的salt
textEncryptor.setPassword("wwqYunxi");
System.out.println("用户===》"+textEncryptor.decrypt("qaa0BOUMC69RlSjW1EBYjg=="));
System.out.println("密码===》"+textEncryptor.decrypt("5l0HQCNMy2H5gLhLP3NwcI/F4Q7uI1d+qE14OoS2LdQtxV0VPgvINj0Oh69MPW8SEt/KLbld+yQ="));
System.out.println("用户===》"+textEncryptor.encrypt("root"));
System.out.println("密码===》"+textEncryptor.encrypt("KKOwmQr4JjY6eFPeLZ/dpzxESv+Bb8uQTNYCKyPV"));
//org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fukajinSchedule': Unsatisfied dependency expressed through field 'ssmRechargeService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ssmRechargeServiceImpl': Unsatisfied dependency expressed through field 'ssmStoreMemberService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'ssmStoreMemberServiceImpl': Unsatisfied dependency expressed through field 'quartzManage'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'quartzManage': Unsatisfied dependency expressed through field 'scheduler'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scheduler' defined in class path resource [com/ssm/config/QuartzConfig.class]: Invocation of init method failed; nested exception is org.quartz.JobPersistenceException: Failed to obtain DB connection from data source 'quartzDS': java.sql.SQLException: Connections could not be acquired from the underlying database! [See nested exception: java.sql.SQLException: Connections could not be acquired from the underlying database!]
// at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
// at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
// at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
// at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
// at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
// at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
// at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
}
}

@ -0,0 +1,25 @@
//package com.ssm.core.util;
//
//import org.apache.ibatis.plugin.Interceptor;
//import org.apache.ibatis.plugin.Invocation;
//import org.springframework.stereotype.Component;
//
//import java.util.Properties;
//
//@Component
//public class MybatisInterceptor implements Interceptor {
// @Override
// public Object intercept(Invocation invocation) throws Throwable {
// return null;
// }
//
// @Override
// public Object plugin(Object target) {
// return null;
// }
//
// @Override
// public void setProperties(Properties properties) {
//
// }
//}

@ -0,0 +1,140 @@
package com.ssm.core.util;
import com.ssm.util.RedisClient;
import java.util.Objects;
public class RedisLock {
private RedisClient<String> redisClient;
private static final int DEFAULT_ACQUIRY_RESOLUTION_MILLIS = 100;
/**
* Lock key path.
*/
private String lockKey;
/**
* 线
*/
private int expireSecs = 60;
/**
* 线饿
*/
private int timeoutMsecs = 10 * 1000;
private volatile boolean locked = false;
private String expiresStr = "";
/**
* Detailed constructor with default acquire timeout 10000 msecs and lock expiration of 60000 msecs.
*
* @param lockKey lock key (ex. account:1, ...)
*/
public RedisLock(RedisClient<String> redisClient, String lockKey) {
this.redisClient = redisClient;
this.lockKey = lockKey + "_lock";
}
/**
* Detailed constructor with default lock expiration of 60000 msecs.
*
*/
public RedisLock(RedisClient<String> redisClient, String lockKey, int timeoutMsecs) {
this(redisClient, lockKey);
this.timeoutMsecs = timeoutMsecs;
}
/**
* Detailed constructor.
*
*/
public RedisLock(RedisClient<String> redisClient, String lockKey, int timeoutMsecs, int expireSecs) {
this(redisClient, lockKey, timeoutMsecs);
this.expireSecs = expireSecs;
}
/**
* @return lock key
*/
public String getLockKey() {
return lockKey;
}
/**
* lock.
* : 使redis setnx,.
* reidskeykey,, value(:value,)
* :
* 1.setnxkey,(),
* 2.,,,
*
* @return true if lock is acquired, false acquire timeouted
* @throws InterruptedException in case of thread interruption
*/
public synchronized boolean lock() throws InterruptedException {
int timeout = timeoutMsecs;
while (true) {
long expires = System.currentTimeMillis() + expireSecs + 1;
expiresStr = String.valueOf(expires); //锁到期时间
if (redisClient.setnx(lockKey, expiresStr)) {
redisClient.expire(lockKey,expireSecs);
// lock acquired
locked = true;
return true;
}
String currentValueStr = redisClient.get(lockKey); //redis里的时间
if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
//判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的
// lock is expired
String oldValueStr = redisClient.getset(lockKey, expiresStr);
//获取上一个锁到期时间,并设置现在的锁到期时间,
//只有一个线程才能获取上一个线上的设置时间因为jedis.getSet是同步的
if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
//防止误删覆盖因为key是相同的了他人的锁——这里达不到效果这里值会被覆盖但是因为什么相差了很少的时间所以可以接受
//[分布式的情况下]:如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁
// lock acquired
locked = true;
return true;
}
}
timeout -= DEFAULT_ACQUIRY_RESOLUTION_MILLIS;
if(timeout <= 0){
break;
}
/*
100 , 使,饿,,,
,,,,.
使
*/
Thread.sleep(DEFAULT_ACQUIRY_RESOLUTION_MILLIS);
}
return false;
}
/**
* Acqurired lock release.
*/
public synchronized void unlock() {
if (locked) {
String s = redisClient.get(lockKey);
if(Objects.equals(s,expiresStr)) {
redisClient.delete(lockKey);
locked = false;
}
}
}
}

@ -0,0 +1,135 @@
package com.ssm.core.util;
import java.util.Random;
/**
* Twitter
*
* 0 01
* 4141使69
* 10101024
* 12idID124096ID
* 1bit 41bit 10bit 12bit
* 0-10111001100111011111011101100001110100101-00 00000000-0000 00000000
*
* https://shardingsphere.apache.org/document/current/cn/features/sharding/concept/key-generator/
*/
public class SnowflakeUtil {
/**
*
*/
private final static long startTimestamp = 1594448397348L;
/**
*
*/
private final static long workerIdBits = 10L;
private final static long sequenceBits = 12L;
/**
*
*/
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);// 2^(10-1)
private final static long maxSequence = -1L ^ (-1L << sequenceBits);//2^(12-1)
/**
*
*/
private final static long workerIdShift = sequenceBits;
private final static long timestampShift = sequenceBits + workerIdBits;
/**
* id
*/
private volatile long workerId;// 轻量级同步
/**
*
*/
private long sequence = 0;
/**
*
*/
private long lastTimestamp = 0;
/**
*
* @param workerId id
*/
public SnowflakeUtil(long workerId) {
// 校验
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %s or less than 0", maxWorkerId));
}
this.workerId = workerId;
}
/**
* Id
*
* @return
*/
public synchronized long nextId() {
long timestamp = getNowTimestamp();
// 检验时间戳
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %s milliseconds", lastTimestamp - timestamp));
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & maxSequence;
if (sequence == 0L) {
timestamp = getNextTimestamp();
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return (timestamp - startTimestamp) << timestampShift //时间戳部分
| (workerId) << workerIdShift // 工作进程id部分
| (sequence); //序列号
}
/**
*
*
* @return
*/
private long getNextTimestamp() {
long timestamp = getNowTimestamp();
while (timestamp < lastTimestamp) {
timestamp = getNowTimestamp();
}
return timestamp;
}
/**
*
*
* @return
*/
private long getNowTimestamp() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
int a=0/2;
System.out.println(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
// SnowflakeUtil util = new SnowflakeUtil(1023);
// Runnable r2 = () ->{
//// SnowflakeUtil util = new SnowflakeUtil(1022);
// for (int i = 0; i < 10; i++) {
// long id = util.nextId();
// System.out.println(id);
// }
// };
// Runnable r1 = () ->{
//// SnowflakeUtil util = new SnowflakeUtil(1022);// 存在重复的问题,
// for (int i = 0; i < 10; i++) {
// long id = util.nextId();
// System.out.println(id);
// }
// };
//
// new Thread(r1).start();
// new Thread(r2).start();
}
}

@ -0,0 +1,138 @@
package com.ssm.core.util;
import java.lang.reflect.Field;
import java.util.Comparator;
/**
*
*
*/
public class StrComparatorUtils<T> implements Comparator<T> {
private String str1, str2;
private int pos1, pos2, len1, len2;
// 传入类中需要比较的字段
private String propertyName;
private boolean isDesc = false;
/**
*
* @param propertyName
*/
public StrComparatorUtils(String propertyName) {
this.propertyName = propertyName;
}
/**
*
* @param propertyName
* @param isDesc false
*/
public StrComparatorUtils(String propertyName, boolean isDesc) {
this.propertyName = propertyName;
this.isDesc = isDesc;
}
public int compare(T o1, T o2) {
if (isDesc) {
str2 = getPropertyValue(o1);
str1 = getPropertyValue(o2);
} else {
str1 = getPropertyValue(o1);
str2 = getPropertyValue(o2);
}
len1 = str1.length();
len2 = str2.length();
pos1 = pos2 = 0;
int result = 0;
while (result == 0 && pos1 < len1 && pos2 < len2) {
char ch1 = str1.charAt(pos1);
char ch2 = str2.charAt(pos2);
if (Character.isDigit(ch1)) {
result = Character.isDigit(ch2) ? compareNumbers() : -1;
} else if (Character.isLetter(ch1)) {
result = Character.isLetter(ch2) ? compareOther(true) : 1;
} else {
result = Character.isDigit(ch2) ? 1
: Character.isLetter(ch2) ? -1
: compareOther(false);
}
pos1++;
pos2++;
}
return result == 0 ? len1 - len2 : result;
}
private String getPropertyValue(T o1) {
String str = "";
try {
Field field = o1.getClass().getDeclaredField(propertyName);
field.setAccessible(true);
Object obj = field.get(o1);
if (obj != null){
return obj.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
private int compareNumbers() {
int end1 = pos1 + 1;
while (end1 < len1 && Character.isDigit(str1.charAt(end1))) {
end1++;
}
int fullLen1 = end1 - pos1;
while (pos1 < end1 && str1.charAt(pos1) == '0') {
pos1++;
}
int end2 = pos2 + 1;
while (end2 < len2 && Character.isDigit(str2.charAt(end2))) {
end2++;
}
int fullLen2 = end2 - pos2;
while (pos2 < end2 && str2.charAt(pos2) == '0') {
pos2++;
}
int delta = (end1 - pos1) - (end2 - pos2);
if (delta != 0) {
return delta;
}
while (pos1 < end1 && pos2 < end2) {
delta = str1.charAt(pos1++) - str2.charAt(pos2++);
if (delta != 0) {
return delta;
}
}
pos1--;
pos2--;
return fullLen2 - fullLen1;
}
private int compareOther(boolean isLetters) {
char ch1 = str1.charAt(pos1);
char ch2 = str2.charAt(pos2);
if (ch1 == ch2) {
return 0;
}
if (isLetters) {
ch1 = Character.toUpperCase(ch1);
ch2 = Character.toUpperCase(ch2);
if (ch1 != ch2) {
ch1 = Character.toLowerCase(ch1);
ch2 = Character.toLowerCase(ch2);
}
}
return ch1 - ch2;
}
}

@ -0,0 +1,31 @@
package com.ssm.core.util;
import com.ssm.manage.entity.RechargeAccount;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.SsmRechargeAccountService;
import com.ssm.manage.service.impl.SsmRechargeAccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class text {
public static void main(String[] args) {
SsmRechargeAccountService ssmRechargeAccountService = new SsmRechargeAccountServiceImpl();
List<Long> longs = Arrays.asList(347470857126223872L, 347158924979441664L);
List<RechargeAccount> rechargeAccountList = ssmRechargeAccountService.selectByPrimaryKeyList(longs);
System.out.println(rechargeAccountList.size());
}
@Autowired
SsmBaseStoreService ssmBaseStoreService;
public void test(){
}
}

@ -0,0 +1,45 @@
//package com.ssm.filter;
//import com.ssm.manage.entity.SmsException;
//import com.ssm.manage.response.ResponseCode;
//import org.apache.ibatis.executor.Executor;
//import org.apache.ibatis.mapping.MappedStatement;
//import org.apache.ibatis.plugin.*;
//import org.springframework.stereotype.Component;
//
//import java.util.Properties;
//
//@Intercepts({
// @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
//})
//@Component
//public class DeleteInterceptor implements Interceptor {
//
// @Override
// public Object intercept(Invocation invocation) throws Throwable {
// Object[] args = invocation.getArgs();
// MappedStatement mappedStatement = (MappedStatement) args[0];
// Object parameterObject = args[1];
// // 判断是否为DELETE操作
// if (mappedStatement.getSqlCommandType().name().equals("DELETE")) {
// // 判断参数是否为空
// if (parameterObject == null) {
// throw new SmsException(ResponseCode.MSG,"删除条件不能为空");
// }
// // 可根据具体情况判断参数类型或其他条件
// // 进行其他处理,如记录日志等
// }
// // 执行原始的方法
// return invocation.proceed();
// }
//
// @Override
// public Object plugin(Object target) {
// return Plugin.wrap(target, this);
// }
//
// @Override
// public void setProperties(Properties properties) {
// // 可以在配置文件中配置一些属性,进行初始化设置
// }
//}
//

@ -0,0 +1,235 @@
package com.ssm.filter;
import cn.hutool.extra.servlet.ServletUtil;
import com.google.gson.Gson;
import com.ssm.manage.response.*;
import com.ssm.manage.service.SsmSysRolePowerService;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.manage.utils.StringUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private RedisClient<UserResponse> redisClient;
private static final ThreadLocal<StaffResponse> threadLocal = new ThreadLocal<>();
@Autowired
private RedisClient<StaffResponse> staffResponseRedisClient;
@Autowired
private RedisClient<StaffTemporaryVo> staffTemporaryVoRedisClient;
@Autowired
private RedisClient<MemberResponse> memberResponseRedisClient;
@Autowired
private SsmSysRolePowerService ssmSysRolePowerService;
private static String STAFF_KEY = "staffKey";
private static String USER_KEY = "userKey";
private static String MEMBER_KEY = "memberKey";
public static String hduserKey = "hduserKey";
@Override
public boolean preHandle(@NotNull HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String clientIP = ServletUtil.getClientIP(request);
StringBuffer requestURL = request.getRequestURL();
if (requestURL.toString().contains("error") || requestURL.toString().contains("swagger")) {
return true;
}
HttpSession session = request.getSession();
String cacheToken = SessionHelp.getToken(session);
String loginAccount = SessionHelp.getLoginAccount(session);
String token = request.getHeader("token");
// //判断session中是否有登录信息
// if (StringUtils.isNotBlank(loginAccount) && StringUtils.isNotBlank(token) && token.equals(cacheToken)) {
// return true;
// }
if (StringUtils.isBlank(token)){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
GenericResponse genericResponse = new GenericResponse();
genericResponse.setCodeAndMsg(ResponseCode.TOKEN_IS_EXPIRED);
Gson gson = new Gson();
try {
out = response.getWriter();
out.append(gson.toJson(genericResponse));
} catch (Exception e) {
log.error("LoginInterceptor.preHandle", e);
} finally {
if (out != null) {
out.close();
}
return false;
}
}else {
//根据token去做验证
if (redisClient.hasKey(USER_KEY + loginAccount)){
UserResponse userResponse = redisClient.get(USER_KEY + loginAccount);
cacheToken = userResponse.getToken();
if (StringUtils.isNotBlank(cacheToken) && cacheToken.equals(token)){
return true;
}else {
//同一个账户 当前请求token和redis中最新的token不一致 销毁当前Session
session.invalidate();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
GenericResponse genericResponse = new GenericResponse();
genericResponse.setCodeAndMsg(ResponseCode.TOKEN_IS_EXPIRED);
Gson gson = new Gson();
try {
out = response.getWriter();
out.append(gson.toJson(genericResponse));
} catch (Exception e) {
log.error("LoginInterceptor.preHandle", e);
} finally {
if (out != null) {
out.close();
}
return false;
}
}
}
else if (staffResponseRedisClient.hasKey(STAFF_KEY + loginAccount)){
StaffResponse staffResponse = staffResponseRedisClient.get(STAFF_KEY + loginAccount);
cacheToken = staffResponse.getToken();
if (StringUtils.isNotBlank(cacheToken) && cacheToken.equals(token)){
threadLocal.set(staffResponse);
return true;
}else {
//同一个账户 当前请求token和redis中最新的token不一致 销毁当前Session
session.invalidate();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
GenericResponse genericResponse = new GenericResponse();
genericResponse.setCodeAndMsg(ResponseCode.TOKEN_IS_EXPIRED);
Gson gson = new Gson();
try {
out = response.getWriter();
out.append(gson.toJson(genericResponse));
} catch (Exception e) {
log.error("LoginInterceptor.preHandle", e);
} finally {
if (out != null) {
out.close();
}
return false;
}
}
}
else if (memberResponseRedisClient.hasKey(MEMBER_KEY + loginAccount)){
MemberResponse memberResponse = memberResponseRedisClient.get(MEMBER_KEY + loginAccount);
cacheToken = memberResponse.getToken();
if (StringUtils.isNotBlank(cacheToken) && cacheToken.equals(token)){
return true;
}else {
//同一个账户 当前请求token和redis中最新的token不一致 销毁当前Session
session.invalidate();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
GenericResponse genericResponse = new GenericResponse();
genericResponse.setCodeAndMsg(ResponseCode.TOKEN_IS_EXPIRED);
Gson gson = new Gson();
try {
out = response.getWriter();
out.append(gson.toJson(genericResponse));
} catch (Exception e) {
log.error("LoginInterceptor.preHandle", e);
} finally {
if (out != null) {
out.close();
}
return false;
}
}
}
else if (staffTemporaryVoRedisClient.hasKey(Constant.staffTemporary + token)){
StaffTemporaryVo staffTemporaryVo = staffTemporaryVoRedisClient.get(Constant.staffTemporary + token);
cacheToken = staffTemporaryVo.getToken();
if (StringUtils.isNotBlank(cacheToken) && cacheToken.equals(token)){
return true;
}else {
//同一个账户 当前请求token和redis中最新的token不一致 销毁当前Session
session.invalidate();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
GenericResponse genericResponse = new GenericResponse();
genericResponse.setCodeAndMsg(ResponseCode.TOKEN_IS_EXPIRED);
Gson gson = new Gson();
try {
out = response.getWriter();
out.append(gson.toJson(genericResponse));
} catch (Exception e) {
log.error("LoginInterceptor.preHandle", e);
} finally {
if (out != null) {
out.close();
}
return false;
}
}
}
else {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = null;
GenericResponse genericResponse = new GenericResponse();
genericResponse.setCodeAndMsg(ResponseCode.NOT_LOGIN);
Gson gson = new Gson();
try {
out = response.getWriter();
out.append(gson.toJson(genericResponse));
} catch (Exception e) {
log.error("LoginInterceptor.preHandle", e);
} finally {
if (out != null) {
out.close();
}
return false;
}
}
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
// 提供一个静态方法来获取当前线程中的用户信息
public static StaffResponse getCurrentUserInfo() {
return threadLocal.get();
}
public static void clearThreadLocal() {
threadLocal.remove();
}
}

@ -0,0 +1,52 @@
//package com.ssm.filter;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.web.servlet.HandlerInterceptor;
//import org.springframework.web.servlet.ModelAndView;
//
//import javax.servlet.ServletOutputStream;
//import javax.servlet.WriteListener;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpServletResponseWrapper;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.OutputStreamWriter;
//import java.io.PrintWriter;
//import java.math.BigDecimal;
//import java.nio.charset.StandardCharsets;
//
//@Slf4j
//public class ResponseInterceptor implements HandlerInterceptor {
// private static ThreadLocal<ByteArrayOutputStream> bufferThreadLocal = new ThreadLocal<>();
// @Override
// public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
// ModelAndView modelAndView) throws Exception {
// ByteArrayOutputStream buffer = bufferThreadLocal.get();
// String responseBody = null;
// if (buffer != null) {
// responseBody = buffer.toString(response.getCharacterEncoding()).trim();
// }
//
// // 在这里对响应数据进行处理
//
// // 输出响应数据(可选)
// if (responseBody != null && !responseBody.isEmpty()) {
// response.getWriter().write(responseBody);
// }
// log.error("拦截器生效了");
// // 获取响应的输出流
// }
// @Override
// public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// // 创建缓冲区
// bufferThreadLocal.set(new ByteArrayOutputStream());
// return true;
// }
//
// @Override
// public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// // 移除缓冲区
// bufferThreadLocal.remove();
// }
//
//}
Loading…
Cancel
Save