diff --git a/dm_web/src/main/java/com/ssm/DmWebApp.java b/dm_web/src/main/java/com/ssm/DmWebApp.java new file mode 100644 index 0000000..cb96a25 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/DmWebApp.java @@ -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); + } +} diff --git a/dm_web/src/main/java/com/ssm/Listener/SsmCashListener.java b/dm_web/src/main/java/com/ssm/Listener/SsmCashListener.java new file mode 100644 index 0000000..4acfcfd --- /dev/null +++ b/dm_web/src/main/java/com/ssm/Listener/SsmCashListener.java @@ -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 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 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 map, Channel channel) throws InterruptedException, IOException { +// String msg = new String(message.getBody(), "UTF-8"); +// channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); +// log.error("SsmCashListener.sendMiss2:", "短信发送失败"); +// } +// +//} diff --git a/dm_web/src/main/java/com/ssm/core/bean/MyApplicationRunnerImpl.java b/dm_web/src/main/java/com/ssm/core/bean/MyApplicationRunnerImpl.java new file mode 100644 index 0000000..30168d5 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/bean/MyApplicationRunnerImpl.java @@ -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){ + + } + +} \ No newline at end of file diff --git a/dm_web/src/main/java/com/ssm/core/util/Base64DecodedMultipartFileUtil.java b/dm_web/src/main/java/com/ssm/core/util/Base64DecodedMultipartFileUtil.java new file mode 100644 index 0000000..a42250c --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/Base64DecodedMultipartFileUtil.java @@ -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; + } + } + + + + + +} diff --git a/dm_web/src/main/java/com/ssm/core/util/EasyExcelUtil.java b/dm_web/src/main/java/com/ssm/core/util/EasyExcelUtil.java new file mode 100644 index 0000000..5e1e02c --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/EasyExcelUtil.java @@ -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; + } +} diff --git a/dm_web/src/main/java/com/ssm/core/util/ExcelListener.java b/dm_web/src/main/java/com/ssm/core/util/ExcelListener.java new file mode 100644 index 0000000..bc5980d --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/ExcelListener.java @@ -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 extends AnalysisEventListener { + + /** + * 自定义用于暂时存储data。 + * 可以通过实例获取该值 + */ + private List 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(); + } + */ + } + + /** + * 根据业务自行实现该方法 + */ + private void doSomething() { + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + /* + datas.clear(); + 解析结束销毁不用的资源 + */ + } + + public List getDatas() { + return datas; + } + + public void setDatas(List datas) { + this.datas = datas; + } +} \ No newline at end of file diff --git a/dm_web/src/main/java/com/ssm/core/util/ExcelUtils.java b/dm_web/src/main/java/com/ssm/core/util/ExcelUtils.java new file mode 100644 index 0000000..b20ad0a --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/ExcelUtils.java @@ -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; + } + +} + diff --git a/dm_web/src/main/java/com/ssm/core/util/ExportExcel.java b/dm_web/src/main/java/com/ssm/core/util/ExportExcel.java new file mode 100644 index 0000000..1e9177c --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/ExportExcel.java @@ -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 { + public void exportExcel(String[] headers,Collection 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 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(); + } + } + } +} diff --git a/dm_web/src/main/java/com/ssm/core/util/Http.java b/dm_web/src/main/java/com/ssm/core/util/Http.java new file mode 100644 index 0000000..1534739 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/Http.java @@ -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 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 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 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 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 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; + } + +} diff --git a/dm_web/src/main/java/com/ssm/core/util/IpUtil.java b/dm_web/src/main/java/com/ssm/core/util/IpUtil.java new file mode 100644 index 0000000..4f3dd43 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/IpUtil.java @@ -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; + } +} diff --git a/dm_web/src/main/java/com/ssm/core/util/JasyptUtils.java b/dm_web/src/main/java/com/ssm/core/util/JasyptUtils.java new file mode 100644 index 0000000..953d1c7 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/JasyptUtils.java @@ -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) + } + +} \ No newline at end of file diff --git a/dm_web/src/main/java/com/ssm/core/util/MybatisInterceptor.java b/dm_web/src/main/java/com/ssm/core/util/MybatisInterceptor.java new file mode 100644 index 0000000..5ade5d3 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/MybatisInterceptor.java @@ -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) { +// +// } +//} diff --git a/dm_web/src/main/java/com/ssm/core/util/RedisLock.java b/dm_web/src/main/java/com/ssm/core/util/RedisLock.java new file mode 100644 index 0000000..e8cb9c8 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/RedisLock.java @@ -0,0 +1,140 @@ +package com.ssm.core.util; + +import com.ssm.util.RedisClient; + +import java.util.Objects; + +public class RedisLock { + + private RedisClient 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 redisClient, String lockKey) { + this.redisClient = redisClient; + this.lockKey = lockKey + "_lock"; + } + + /** + * Detailed constructor with default lock expiration of 60000 msecs. + * + */ + public RedisLock(RedisClient redisClient, String lockKey, int timeoutMsecs) { + this(redisClient, lockKey); + this.timeoutMsecs = timeoutMsecs; + } + + /** + * Detailed constructor. + * + */ + public RedisLock(RedisClient 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命令,缓存了锁. + * reids缓存的key是锁的key,所有的共享, value是锁的到期时间(注意:这里把过期时间放在value了,没有时间上设置其超时时间) + * 执行过程: + * 1.通过setnx尝试设置某个key的值,成功(当前没有这个锁)则返回,成功获得锁 + * 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; + } + } + } + +} diff --git a/dm_web/src/main/java/com/ssm/core/util/SnowflakeUtil.java b/dm_web/src/main/java/com/ssm/core/util/SnowflakeUtil.java new file mode 100644 index 0000000..2b52c88 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/SnowflakeUtil.java @@ -0,0 +1,135 @@ +package com.ssm.core.util; + +import java.util.Random; + +/** + * 雪花算法是由 Twitter 公布的分布式主键生成算法,它能够保证不同进程主键的不重复性,以及相同进程主键的有序性。 + * 算法描述: + * 0 最高位是符号位,始终为0不可用,因为1为负数。 + * 41位的时间序列,精确到毫秒级,41位的长度可以使用69年。时间位还有一个很重要的作用是可以根据时间进行排序。 + * 10位的机器标识,10位的长度最多支持部署1024个节点 + * 12位的计数序列号,序列号即一系列的自增id,可以支持同一节点同一毫秒生成多个ID序号,12位的计数序列号支持每个节点每毫秒产生4096个ID序号 + * 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(); + + + } +} diff --git a/dm_web/src/main/java/com/ssm/core/util/StrComparatorUtils.java b/dm_web/src/main/java/com/ssm/core/util/StrComparatorUtils.java new file mode 100644 index 0000000..59e993d --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/StrComparatorUtils.java @@ -0,0 +1,138 @@ +package com.ssm.core.util; + +import java.lang.reflect.Field; +import java.util.Comparator; + +/** + * 根据传入类的属性进行排序 + * 说明:属性必须是字符串类型 + */ +public class StrComparatorUtils implements Comparator { + 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; + } +} diff --git a/dm_web/src/main/java/com/ssm/core/util/text.java b/dm_web/src/main/java/com/ssm/core/util/text.java new file mode 100644 index 0000000..7470b56 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/core/util/text.java @@ -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 longs = Arrays.asList(347470857126223872L, 347158924979441664L); + List rechargeAccountList = ssmRechargeAccountService.selectByPrimaryKeyList(longs); + System.out.println(rechargeAccountList.size()); + } + + @Autowired + SsmBaseStoreService ssmBaseStoreService; + + + public void test(){ + + } +} diff --git a/dm_web/src/main/java/com/ssm/filter/DeleteInterceptor.java b/dm_web/src/main/java/com/ssm/filter/DeleteInterceptor.java new file mode 100644 index 0000000..502f202 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/filter/DeleteInterceptor.java @@ -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) { +// // 可以在配置文件中配置一些属性,进行初始化设置 +// } +//} +// diff --git a/dm_web/src/main/java/com/ssm/filter/LoginInterceptor.java b/dm_web/src/main/java/com/ssm/filter/LoginInterceptor.java new file mode 100644 index 0000000..5fa9ae6 --- /dev/null +++ b/dm_web/src/main/java/com/ssm/filter/LoginInterceptor.java @@ -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 redisClient; + + private static final ThreadLocal threadLocal = new ThreadLocal<>(); + + @Autowired + private RedisClient staffResponseRedisClient; + @Autowired + private RedisClient staffTemporaryVoRedisClient; + + @Autowired + private RedisClient 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(); + } + +} diff --git a/dm_web/src/main/java/com/ssm/filter/ResponseInterceptor.java b/dm_web/src/main/java/com/ssm/filter/ResponseInterceptor.java new file mode 100644 index 0000000..2e614df --- /dev/null +++ b/dm_web/src/main/java/com/ssm/filter/ResponseInterceptor.java @@ -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 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(); +// } +// +//}