instruction
stringlengths 77
90.1k
|
---|
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsReportStatisticsDto;import com.chinatower.product.sys.mapper.SmsMonitorHourReceiveListMapper;import com.chinatower.product.sys.service.SmsMonitorHourReceiveListService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SmsMonitorHourReceiveListServiceImpl extends BaseServiceImpl<SmsReportStatisticsDto, String> implements SmsMonitorHourReceiveListService { @Autowired SmsMonitorHourReceiveListMapper monitorStatisticsMapper; @Override public BaseMapper<SmsReportStatisticsDto, String> getMappser() { return monitorStatisticsMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsReportStatisticsDto> selectListByPage(SmsReportStatisticsDto reportStatisticsDto) { return monitorStatisticsMapper.selectListByPage(reportStatisticsDto); }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsReportStatisticsDto;import com.chinatower.product.sys.mapper.SmsMonitorHourSendListMapper;import com.chinatower.product.sys.service.SmsMonitorHourSendListService;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.text.SimpleDateFormat;import java.util.*;@Servicepublic class SmsMonitorHourSendListServiceImpl extends BaseServiceImpl<SmsReportStatisticsDto, String> implements SmsMonitorHourSendListService { @Autowired SmsMonitorHourSendListMapper monitorStatisticsMapper; @Override public BaseMapper<SmsReportStatisticsDto, String> getMappser() { return monitorStatisticsMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsReportStatisticsDto> selectListByPage(SmsReportStatisticsDto reportStatisticsDto) { return monitorStatisticsMapper.selectListByPage(reportStatisticsDto); }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsReportStatisticsDto;import com.chinatower.product.sys.mapper.SmsMonitorReceiveTopMapper;import com.chinatower.product.sys.service.SmsMonitorReceiveTopService;import com.chinatower.product.sys.service.SmsMonitorSendTopService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SmsMonitorReceiveTopServiceImpl extends BaseServiceImpl<SmsReportStatisticsDto, String> implements SmsMonitorReceiveTopService { @Autowired SmsMonitorReceiveTopMapper receiveTopMapper; @Override public BaseMapper<SmsReportStatisticsDto, String> getMappser() { return receiveTopMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsReportStatisticsDto> selectListByPage(SmsReportStatisticsDto reportStatisticsDto) { return receiveTopMapper.selectListByPage(reportStatisticsDto); }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsReportStatisticsDto;import com.chinatower.product.sys.mapper.SmsMonitorSendTopMapper;import com.chinatower.product.sys.service.SmsMonitorSendTopService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SmsMonitorSendTopServiceImpl extends BaseServiceImpl<SmsReportStatisticsDto, String> implements SmsMonitorSendTopService { @Autowired SmsMonitorSendTopMapper sendTopMapper; @Override public BaseMapper<SmsReportStatisticsDto, String> getMappser() { return sendTopMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsReportStatisticsDto> selectListByPage(SmsReportStatisticsDto reportStatisticsDto) { return sendTopMapper.selectListByPage(reportStatisticsDto); }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsHourDto;import com.chinatower.product.sys.entity.SmsMonitorDto;import com.chinatower.product.sys.entity.SmsReportStatisticsDto;import com.chinatower.product.sys.mapper.SmsMonitorStatisticsMapper;import com.chinatower.product.sys.mapper.SmsReportStatisticsMapper;import com.chinatower.product.sys.mapper.SysUserMapper;import com.chinatower.product.sys.service.SmsMonitorStatisticsService;import org.apache.commons.collections4.CollectionUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.*;@Servicepublic class SmsMonitorStatisticsServiceImpl extends BaseServiceImpl<SmsReportStatisticsDto, String> implements SmsMonitorStatisticsService { @Autowired SmsMonitorStatisticsMapper monitorStatisticsMapper; @Autowired SmsReportStatisticsMapper reportStatisticsMapper; @Override public BaseMapper<SmsReportStatisticsDto, String> getMappser() { return monitorStatisticsMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsReportStatisticsDto> selectListByPage(SmsReportStatisticsDto reportStatisticsDto) { return monitorStatisticsMapper.selectListByPage(reportStatisticsDto); } /** * 柱状图数据 * * @param statisticsDto * @return */ @Override public SmsMonitorDto getSmsSysTop(SmsReportStatisticsDto statisticsDto) { SmsMonitorDto result = new SmsMonitorDto(); List<String> Xaxis = new ArrayList<>(); List<Integer> totalTopYaxis = new ArrayList<>(); List<Integer> todayTopYaxis = new ArrayList<>(); // 查询短信系统 List<SmsReportStatisticsDto> list = reportStatisticsMapper.getSysNameInfo(""); if (CollectionUtils.isNotEmpty(list)) { for (SmsReportStatisticsDto dto : list) { Xaxis.add(dto.getSysName()); // 查询对应的总数量 SmsReportStatisticsDto statisticsDto1 = new SmsReportStatisticsDto(); statisticsDto1.setSysCode(dto.getSysCode()); // 查询总数 Integer totalNum = monitorStatisticsMapper.getSmsSendNum(statisticsDto1); totalTopYaxis.add(totalNum); statisticsDto1.setSendTime("today"); // 查询今日 Integer todayNum = monitorStatisticsMapper.getSmsSendNum(statisticsDto1); todayTopYaxis.add(todayNum); } result.setXaxis(Xaxis); result.setTotalTopYaxis(totalTopYaxis); result.setTodayTopYaxis(todayTopYaxis); } return result; } /** * 系统总数量(短信总量,接受号码个数)折线图数据 * * @param statisticsDto * @return */ @Override public SmsMonitorDto queryMonitorSmsHourList(SmsReportStatisticsDto statisticsDto) { SmsMonitorDto result = new SmsMonitorDto(); List<String> Xaxis = new ArrayList<>(); List<Integer> sysHourSendTotalCount = new ArrayList<>(); List<Integer> sysHourReceiveCount = new ArrayList<>(); List<String> dateList = get24HourBeforeList(); for (int i = 0; i <dateList.size() ; i++) { String dateStr = dateList.get(i); SmsReportStatisticsDto statisticsDto1 = new SmsReportStatisticsDto(); statisticsDto1.setSendTime(dateStr); // 查询小时发送总数 Integer totalNum = monitorStatisticsMapper.getSmsSendHourJobNum(statisticsDto1); sysHourSendTotalCount.add(totalNum); // 查询小时号码接收个数 Integer receiveNum = monitorStatisticsMapper.getSmsReceiveHourJobNum(statisticsDto1); sysHourReceiveCount.add(receiveNum); } result.setXaxis(dateList); result.setSysHourSendTotalCount(sysHourSendTotalCount); result.setSysHourReceiveCount(sysHourReceiveCount); return result; }// /**// * 所有单独系统展示折线图数据// * @param statisticsDto// * @return// */// @Override// public SmsMonitorDto queryMonitorSmsHourList(SmsReportStatisticsDto statisticsDto) {// List<SmsMonitorDto> list = new ArrayList<>();// SmsMonitorDto monitorDto = new SmsMonitorDto();// List<SmsHourDto> hourDtosList = new ArrayList<>();// // 查询短信系统// List<SmsReportStatisticsDto> sysList = reportStatisticsMapper.getSysNameInfo("");// List<String> dateList = get24HourList();// monitorDto.setXaxis(dateList);// if (CollectionUtils.isNotEmpty(sysList)) {// for (SmsReportStatisticsDto dto : sysList) {// List<Integer> hour24List = new ArrayList<>();// SmsHourDto hourDto = new SmsHourDto();// hourDto.setSysName(dto.getSysName());// // 根据时间段查询数据// for (int i = 0; i <dateList.size() ; i++) {// SmsReportStatisticsDto dto1 = new SmsReportStatisticsDto();// String dateStr = dateList.get(i);// dto1.setSendTime(dateStr);// dto1.setTableNameStr(tableInfo());// dto1.setSysCode(dto.getSysCode());// // 根据日期查询数据// Integer hour24Num = monitorStatisticsMapper.getSmsSendHourNum(dto1);// hour24List.add(hour24Num);// hourDto.setHourNum(hour24List);// }// hourDtosList.add(hourDto);// monitorDto.setHourCount(hourDtosList);// list.add(monitorDto);// }// }// return monitorDto;// } @Override public List<SmsReportStatisticsDto> getMonitorMainData(SmsReportStatisticsDto statisticsDto) { List<SmsReportStatisticsDto> statisticsDtoList = monitorStatisticsMapper.getMonitorMainData(statisticsDto); if(CollectionUtils.isNotEmpty(statisticsDtoList)){ // 查询接收电话号码数量 statisticsDto.setTableNameStr(tableInfo()); Integer sysReceiveNum = monitorStatisticsMapper.getSmsReceiveTodayNum(statisticsDto); for (int i = 0; i <statisticsDtoList.size() ; i++) { statisticsDtoList.get(i).setSysReceiveCount(sysReceiveNum); } } return statisticsDtoList; } // 当前时间24小时数据 private List<String> get24HourList() { Date day = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 00"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH"); String s = df.format(day); Date date = null; try { date = df.parse(s); } catch ( ParseException e) { e.printStackTrace(); } ArrayList<String> dates = new ArrayList<>(); for (int i = 0; i < 24; i++) { Calendar cal = Calendar.getInstance(); cal.setTime(date); if (i != 0) { cal.add(Calendar.HOUR, 1); } date = cal.getTime(); String s1 = format.format(date); dates.add(s1); } return dates; } // 当前时间往前推24小时时间段 private List<String> get24HourBeforeList(){ //时间格式化 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH"); Calendar calendar=Calendar.getInstance(); Date date=new Date(); calendar.setTime(date); ArrayList<String> dates = new ArrayList<String>(); //当前时间循环24小时减下去 for(int i=0;i<24;i++){ calendar.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY) - 1); String time = sdf.format(calendar.getTime()); dates.add(time); } Collections.sort(dates); return dates; } private String tableInfo(){ String tableName = ""; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar calendar = Calendar.getInstance(); Date date1=new Date(); calendar.setTime(date1); String date = sdf.format(calendar.getTime());// String date = "2020-11-22"; Integer year = Integer.valueOf(date.substring(0,date.indexOf("-"))); Integer month = Integer.valueOf(date.substring(date.indexOf("-")+1,date.lastIndexOf("-"))); String newMonth=""; if(month <10){ newMonth = month.toString().replaceAll("0",""); }else{ newMonth = month.toString(); } tableName = "_"+year+"_"+newMonth; return tableName; } /** * (短信发送数据量,接受数量,成功数量)柱状图数据统计 * * @param statisticsDto * @return */ @Override public SmsMonitorDto queryMonitorSmsBarList(String sendTime) { SmsMonitorDto result = new SmsMonitorDto(); List<String> Xaxis = new ArrayList<>(); List<Integer> totalSendCount = new ArrayList<>(); List<Integer> sysReceiveCount = new ArrayList<>(); List<Integer> succeedCount = new ArrayList<>(); List<SmsReportStatisticsDto> dateList = monitorStatisticsMapper.getSmsBarData(sendTime); for (int i = 0; i <dateList.size() ; i++) { Xaxis.add(dateList.get(i).getSysName()); totalSendCount.add(dateList.get(i).getTotalSendCount()); sysReceiveCount.add(dateList.get(i).getSysReceiveCount()); succeedCount.add(dateList.get(i).getSucceedCount()); } result.setXaxis(Xaxis); result.setTotalSendCount(totalSendCount); result.setSucceedCount(succeedCount); result.setSysReceiveCount(sysReceiveCount); return result; }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsPushAlarmDto;import com.chinatower.product.sys.manager.SmsPushAlarmRedisManager;import com.chinatower.product.sys.mapper.SmsPushAlarmMapper;import com.chinatower.product.sys.service.SmsPushAlarmService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SmsPushAlarmServiceImpl extends BaseServiceImpl<SmsPushAlarmDto, String> implements SmsPushAlarmService { @Autowired SmsPushAlarmMapper pushAlarmMapper; @Autowired SmsPushAlarmRedisManager smsPushAlarmRedisManager; @Override public BaseMapper<SmsPushAlarmDto, String> getMappser() { return pushAlarmMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsPushAlarmDto> selectListByPage(SmsPushAlarmDto pushAlarmDto) { return pushAlarmMapper.selectListByPage(pushAlarmDto); } @Override public SmsPushAlarmDto selectBatchPushAlarmById(int id) { return pushAlarmMapper.selectBatchPushAlarmById(id); } @Override public String insetRedis(SmsPushAlarmDto dto){ return smsPushAlarmRedisManager.insetRedis(dto); } @Override public String updateRedis(SmsPushAlarmDto dto) { return smsPushAlarmRedisManager.updateRedis(dto); } @Override public String delRedis(SmsPushAlarmDto dto) { return smsPushAlarmRedisManager.delRedis(dto); }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.core.constant.UserRoleConstant;import com.chinatower.product.sys.entity.SmsReportStatisticsDto;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.sys.mapper.SmsReportStatisticsMapper;import com.chinatower.product.sys.mapper.SysUserMapper;import com.chinatower.product.sys.service.SmsReportStatisticsService;import com.chinatower.product.sys.service.SysUserService;import org.apache.commons.io.output.ByteArrayOutputStream;import org.apache.commons.lang3.StringUtils;import org.apache.poi.hssf.usermodel.*;import org.apache.poi.ss.usermodel.HorizontalAlignment;import org.apache.poi.ss.usermodel.VerticalAlignment;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.io.ByteArrayInputStream;import java.io.IOException;import java.math.BigDecimal;import java.util.List;@Servicepublic class SmsReportStatisticsServiceImpl extends BaseServiceImpl<SmsReportStatisticsDto, String> implements SmsReportStatisticsService { @Autowired SmsReportStatisticsMapper reportStatisticsMapper; @Autowired SysUserMapper userMapper; @Autowired private SysUserService sysUserService; @Override public BaseMapper<SmsReportStatisticsDto, String> getMappser() { return reportStatisticsMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsReportStatisticsDto> selectListByPage(SmsReportStatisticsDto reportStatisticsDto) { return reportStatisticsMapper.selectListByPage(reportStatisticsDto); } @Override public ByteArrayInputStream exportSmsStatistics(String sysCode, String sendTime,String smsGate) throws IOException { boolean flag = true; SmsReportStatisticsDto dto = new SmsReportStatisticsDto(); if(StringUtils.isNotEmpty(sendTime) && !"undefined".equals(sendTime)){ dto.setSendTime(sendTime); String begin = sendTime.substring(0, sendTime.indexOf(" - ")); String end = sendTime.substring(sendTime.indexOf(" - ") + 3, sendTime.length()); dto.setBegin(begin +" 00:00:00.0"); dto.setEnd(end +" 23:59:59.59"); } if(StringUtils.isNotEmpty(sysCode) && !"undefined".equals(sysCode)){ dto.setSysCode(sysCode); }else{ Subject subject = SecurityUtils.getSubject(); CurrentUser currentUser = (CurrentUser) subject.getPrincipal(); String username = currentUser.getUsername(); List<String> list = sysUserService.queryUserRole(username); for(String role : list){ if(UserRoleConstant.USER_ROLE.contains(role)){ flag = false; break; } } if (!"admin".equals(username)) { SysUser sysUser = userMapper.login(username); if (null != sysUser) { dto.setSysCode(sysUser.getSysCode()); } } } if(StringUtils.isNotEmpty(smsGate) && !"undefined".equals(smsGate)){ dto.setSmsGate(smsGate); } HSSFWorkbook workbook = null; // 查询报表数据 List<SmsReportStatisticsDto> statisticsDtoList = reportStatisticsMapper.querySmsStatisticsList(dto); // 设置表单 workbook = exportSmsStatisticsExcel(statisticsDtoList); ByteArrayOutputStream os = new ByteArrayOutputStream(); workbook.write(os); os.flush(); os.close(); return new ByteArrayInputStream(os.toByteArray()); } /** * 导出报表信息 */ private HSSFWorkbook exportSmsStatisticsExcel(List<SmsReportStatisticsDto> statisticsDtoList) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("短信报表明细情况"); HSSFRow rowTitle = null; HSSFRow rowData = null; HSSFCellStyle cellStyle = workbook.createCellStyle(); cellStyle.setAlignment(HorizontalAlignment.CENTER); cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); cellStyle.setWrapText(true); HSSFFont f = workbook.createFont(); f.setFontHeightInPoints((short) 12); f.setBold(true); cellStyle.setFont(f); HSSFCellStyle cs = workbook.createCellStyle(); cs.setWrapText(true); HSSFCell cell = null; cell = sheet.createRow(0).createCell((int) 0); cell.setCellValue("URL Link"); // 内容居中 HSSFCellStyle conCenterStyle = workbook.createCellStyle(); conCenterStyle.setAlignment(HorizontalAlignment.CENTER); conCenterStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 单元格 HSSFCellStyle prizeStyle = workbook.createCellStyle(); prizeStyle.setWrapText(true); prizeStyle.setAlignment(HorizontalAlignment.CENTER); prizeStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 设置标题数组 String[] titles = new String[9]; titles = new String[]{"系统名称", "账号", "总发送数","已知条数", "成功数量","计费条数", "失败数量","未知条数","未知计费条数" ,"成功率","发送网关","统计时间"}; int rowNum = 1; SmsReportStatisticsDto detailDto = null; // 设置内容 for (int i = 0; i < statisticsDtoList.size(); i++) { detailDto = statisticsDtoList.get(i); rowData = sheet.createRow(rowNum); rowData.setHeight((short) 400); // 系统名称 cell = rowData.createCell(0); cell.setCellValue(transformationStr(detailDto.getSysName(), "String")); cell.setCellStyle(conCenterStyle); // 账号 cell = rowData.createCell(1); cell.setCellValue(transformationStr(detailDto.getUsername(), "String")); cell.setCellStyle(conCenterStyle); // 总发送数量 cell = rowData.createCell(2); if(detailDto.getTotalSendCount() ==null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getTotalSendCount()); } cell.setCellStyle(conCenterStyle); // 已只数量 cell = rowData.createCell(3); if(detailDto.getCountSend() ==null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getCountSend()); } // 成功发送量 cell = rowData.createCell(4); if(detailDto.getSucceedCount() == null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getSucceedCount()); } //计费条数 cell = rowData.createCell(5); if(detailDto.getChargingCount() ==null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getChargingCount()); } cell.setCellStyle(conCenterStyle); // 失败发送量 cell = rowData.createCell(6); if(detailDto.getFailCount() ==null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getFailCount()); } cell.setCellStyle(conCenterStyle); // 未回调数量 cell = rowData.createCell(7); if(detailDto.getCallbackSendCount() ==null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getCallbackSendCount()); } // 未计费数量 cell = rowData.createCell(8); if(detailDto.getUnknownChargingCount() ==null){ cell.setCellValue(0); }else{ cell.setCellValue(detailDto.getUnknownChargingCount()); } // 成功率 cell = rowData.createCell(9); cell.setCellValue(transformationStr(detailDto.getSuccessRate(), "String")); cell.setCellStyle(conCenterStyle); // 发送网关 cell = rowData.createCell(10); if(StringUtils.isNotBlank(detailDto.getSmsGate()) && detailDto.getSmsGate().equals("0")){ cell.setCellValue("艾派"); }else if(StringUtils.isNotBlank(detailDto.getSmsGate()) && detailDto.getSmsGate().equals("1")){ cell.setCellValue("中商盛达"); }else{ cell.setCellValue(""); } cell.setCellStyle(conCenterStyle); // 统计时间 cell = rowData.createCell(11); cell.setCellValue(transformationStr(detailDto.getTimeBucketStr(), "String")); ++rowNum; } // 设置第一行标题 rowTitle = sheet.createRow(0); for (int i = 0; i < titles.length; i++) { sheet.setDefaultColumnStyle(i, cs); cell = rowTitle.createCell(i); cell.setCellStyle(cellStyle); cell.setCellValue(titles[i]); } sheet.setColumnWidth(0, 6000); sheet.setColumnWidth(1, 6000); sheet.setColumnWidth(2, 6000); sheet.setColumnWidth(3, 6000); sheet.setColumnWidth(4, 6000); sheet.setColumnWidth(5, 6000); sheet.setColumnWidth(6, 6000); sheet.setColumnWidth(7, 6000); sheet.setColumnWidth(8, 6000); sheet.setColumnWidth(9, 6000); sheet.setColumnWidth(10, 6000); sheet.setColumnWidth(11, 6000); return workbook; } /** * 格式化 */ private String transformationStr(String value, String type) { if ("String".equals(type)) { if (org.apache.commons.lang3.StringUtils.isEmpty(value) || "null".equals(value)) { return ""; } else { return value; } } else if ("BigDecimal".equals(type)) { if (StringUtils.isEmpty(value)) { value = "0"; } return new BigDecimal(value).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString(); } return ""; }} |
package com.chinatower.product.sys.service.impl;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.core.Constants;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.core.util.BuliderCodeUtil;import com.chinatower.product.core.util.HttpClientUtil;import com.chinatower.product.sys.core.feign.model.StringRedisModel;import com.chinatower.product.sys.core.util.HttpUtil;import com.chinatower.product.sys.entity.SmsSignDo;import com.chinatower.product.sys.entity.SmsSignDo;import com.chinatower.product.sys.manager.SmsPushAlarmRedisManager;import com.chinatower.product.sys.mapper.SmsSignMapper;import com.chinatower.product.sys.service.SmsSignService;import com.chinatower.product.sys.service.SmsSignService;import com.chinatower.product.sys.util.CacheUtil;import lombok.extern.slf4j.Slf4j;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Date;import java.util.List;@Slf4j@Servicepublic class SmsSignServiceImpl extends BaseServiceImpl<SmsSignDo,String> implements SmsSignService { public static String netUrl; @Value("${feign.netUrl}") public void setNetUrl(String netUrl) { SmsSignServiceImpl.netUrl = netUrl; } @Autowired SmsSignMapper smsSignMapper; @Autowired private CacheUtil cacheUtil; @Override public BaseMapper<SmsSignDo, String> getMappser() { return smsSignMapper; } public List<SmsSignDo> selectListByPage(SmsSignDo emailDO) { return smsSignMapper.selectListByPage(emailDO); } /** * 每次新增都需要审核,所以状态设置为禁用 * @param SmsSignDo * @return */ @Transactional public Integer addSign(SmsSignDo SmsSignDo) { // 模板类型、模板名称、模板内容、模板状态 // 模板code SmsSignDo.setCode(BuliderCodeUtil.builderCode()); // 模板状态 String validStatus = SmsSignDo.getValidStatus();// if(validStatus.equals("on")){ SmsSignDo.setValidStatus("N");// }else {// SmsSignDo.setValidStatus("Y");// } //模板创建人 Subject subject = SecurityUtils.getSubject(); CurrentUser currentUser = (CurrentUser)subject.getPrincipal(); SmsSignDo.setAddname(currentUser.getUsername()); // 模板添加时间 SmsSignDo.setAddtime(new Date()); // 添加到缓存 cacheUtil.setEx(Constants.CMPP_SMS_SIGN + SmsSignDo.getCode(), JSONObject.toJSONString(SmsSignDo),null); //String insert = HttpClientUtil.postClient("insert", SmsSignDo.getCode(), SmsSignDo.getContent()); //log.info("--- 添加缓存 :{}",insert); return smsSignMapper.addSign(SmsSignDo); } @Transactional public Integer delSign(int id) { // 根据模板ID查询的模板code值 SmsSignDo SmsSignDo = smsSignMapper.selectTempById(id); // 删除缓存// String del = HttpClientUtil.postClient("del", SmsSignDo.getCode(), null); String del = delRedis(Constants.CMPP_SMS_SIGN + SmsSignDo.getCode()); log.info("--- 删除缓存 :{}",del); return smsSignMapper.delSign(id); } @Override public Integer auditSign(int id) { // 根据模板ID查询的模板code值 SmsSignDo SmsSignDo = smsSignMapper.selectTempById(id); // 删除缓存 //String del = HttpClientUtil.postClient("del", SmsSignDo.getCode(), null); //log.info("--- 删除缓存 :{}",del); SmsSignDo.setValidStatus("Y"); //更新缓存 cacheUtil.stringPut(Constants.CMPP_SMS_SIGN + SmsSignDo.getCode(), JSONObject.toJSONString(SmsSignDo),null); return smsSignMapper.updateSign(SmsSignDo); } /** * 每次修改都需要审核,所以修改后就要把状态设置为禁用 * @param SmsSignDo * @return */ @Override public Integer updateSign(SmsSignDo SmsSignDo) { // 修改缓存 //String del = HttpClientUtil.postClient("update", SmsSignDo.getCode(), SmsSignDo.getContent()); //log.info("--- 修改缓存 :{}",del); String validStatus = SmsSignDo.getValidStatus();// if(validStatus.equals("on")){ SmsSignDo.setValidStatus("N");// }else {// SmsSignDo.setValidStatus("Y");// } //修改缓存 cacheUtil.stringPut(Constants.CMPP_SMS_SIGN + SmsSignDo.getCode(), JSONObject.toJSONString(SmsSignDo),null); return smsSignMapper.updateSign(SmsSignDo); } @Override public SmsSignDo selectSignById(int id) { SmsSignDo SmsSignDo = smsSignMapper.selectTempById(id); return SmsSignDo; } // 删除缓存 public String delRedis(String key){ String resultStr = ""; // 删除redis 数据 try { StringRedisModel stringRedisModel = new StringRedisModel(); stringRedisModel.setKey(key); stringRedisModel.setSystem("DEFAULT"); HttpUtil httpUtil = new HttpUtil(); resultStr = HttpUtil.httpPostWithJSON(netUrl + Constants.CACHE_SERVICE_STRING_DELETE_API, JSON.toJSONString(stringRedisModel)); }catch (Exception e) { e.printStackTrace(); return "{'status':'1','msg':'请求失败'}"; } return resultStr; }} |
package com.chinatower.product.sys.service.impl;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.entity.SmsPushAlarmDto;import com.chinatower.product.sys.manager.SmsSingleAlarmRedisManager;import com.chinatower.product.sys.mapper.SmsSingleAlarmMapper;import com.chinatower.product.sys.service.SmsSingleAlarmService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class SmsSingleAlarmServiceImpl extends BaseServiceImpl<SmsPushAlarmDto, String> implements SmsSingleAlarmService { @Autowired SmsSingleAlarmMapper singleAlarmMapper; @Autowired SmsSingleAlarmRedisManager smsPushAlarmRedisManager; @Override public BaseMapper<SmsPushAlarmDto, String> getMappser() { return singleAlarmMapper; } /** * 分页查询 * * @param * @return */ @Override public List<SmsPushAlarmDto> selectListByPage(SmsPushAlarmDto pushAlarmDto) { return singleAlarmMapper.selectListByPage(pushAlarmDto); } @Override public SmsPushAlarmDto selectSingleAlarmById(int id) { return singleAlarmMapper.selectSingleAlarmById(id); } @Override public String insetRedis(SmsPushAlarmDto dto) { return smsPushAlarmRedisManager.insetRedis(dto); } @Override public String updateRedis(SmsPushAlarmDto dto) { return smsPushAlarmRedisManager.updateRedis(dto); } @Override public String delRedis(SmsPushAlarmDto dto) { return smsPushAlarmRedisManager.delRedis(dto); }} |
package com.chinatower.product.sys.service.impl;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.core.Constants;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.core.util.BuliderCodeUtil;import com.chinatower.product.core.util.HttpClientUtil;import com.chinatower.product.sys.core.feign.model.StringRedisModel;import com.chinatower.product.sys.core.util.HttpUtil;import com.chinatower.product.sys.entity.SmsTemplateDo;import com.chinatower.product.sys.entity.SmsTypeDo;import com.chinatower.product.sys.manager.SmsPushAlarmRedisManager;import com.chinatower.product.sys.mapper.SmsTemplateMapper;import com.chinatower.product.sys.mapper.SmsTypeMapper;import com.chinatower.product.sys.service.SmsTemplateService;import com.chinatower.product.sys.util.CacheUtil;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Date;import java.util.List;@Slf4j@Servicepublic class SmsTemplateServiceImpl extends BaseServiceImpl<SmsTemplateDo,String> implements SmsTemplateService { public static String netUrl; @Value("${feign.netUrl}") public void setNetUrl(String netUrl) { SmsTemplateServiceImpl.netUrl = netUrl; } @Autowired SmsTemplateMapper smsTemplateMapper; @Autowired SmsTypeMapper smsTypeMapper; @Autowired private CacheUtil cacheUtil; @Override public BaseMapper<SmsTemplateDo, String> getMappser() { return smsTemplateMapper; } public List<SmsTemplateDo> selectListByPage(SmsTemplateDo emailDO) { return smsTemplateMapper.selectListByPage(emailDO); } /** * 每次新增都需要审核,所以状态设置为禁用 * @param SmsTemplateDo * @return */ @Transactional public Integer addTemplate(SmsTemplateDo SmsTemplateDo) { // 模板类型、模板名称、模板内容、模板状态 // 模板code SmsTemplateDo.setCode(BuliderCodeUtil.builderCode()); // 模板状态 String validStatus = SmsTemplateDo.getValidStatus();// if(validStatus.equals("on")){ SmsTemplateDo.setValidStatus("N");// }else {// SmsTemplateDo.setValidStatus("Y");// } //模板创建人 Subject subject = SecurityUtils.getSubject(); CurrentUser currentUser = (CurrentUser)subject.getPrincipal(); SmsTemplateDo.setAddname(currentUser.getUsername()); // 模板添加时间 SmsTemplateDo.setAddtime(new Date()); //查询短信类型 if(StringUtils.isNotEmpty(SmsTemplateDo.getSmsType())){ SmsTypeDo smsTypeDo = smsTypeMapper.selectSmsTypeById(Integer.parseInt(SmsTemplateDo.getSmsType())); SmsTemplateDo.setPriority(smsTypeDo.getSmsPriority()); SmsTemplateDo.setTimeLimit(smsTypeDo.getTimeLimit()); } // 添加到缓存 //String insert = HttpClientUtil.postClient("insert", SmsTemplateDo.getCode(), SmsTemplateDo.getContent()); //log.info("--- 添加缓存 :{}",insert); cacheUtil.setEx(Constants.CMPP_SMS_TEMPLATE + SmsTemplateDo.getCode(), JSONObject.toJSONString(SmsTemplateDo),null); return smsTemplateMapper.addTemplate(SmsTemplateDo); } @Transactional public Integer delTemplate(int id) { // 根据模板ID查询的模板code值 SmsTemplateDo SmsTemplateDo = smsTemplateMapper.selectTempById(id); // 删除缓存 //String del = HttpClientUtil.postClient("del", SmsTemplateDo.getCode(), null); //log.info("--- 删除缓存 :{}",del); cacheUtil.delString(Constants.CMPP_SMS_TEMPLATE + SmsTemplateDo.getCode()); return smsTemplateMapper.delTemplate(id); } @Override public Integer auditTemplate(int id) { // 根据模板ID查询的模板code值 SmsTemplateDo SmsTemplateDo = smsTemplateMapper.selectTempById(id); // 删除缓存// String del = HttpClientUtil.postClient("del", SmsTemplateDo.getCode(), null);// String del = delRedis(Constants.CMPP_SMS_TEMPLATE + SmsTemplateDo.getCode());// log.info("--- 删除缓存 :{}",del); SmsTemplateDo.setValidStatus("Y"); //修改缓存中的数据 cacheUtil.stringPut(Constants.CMPP_SMS_TEMPLATE + SmsTemplateDo.getCode(), JSONObject.toJSONString(SmsTemplateDo),null); return smsTemplateMapper.updateTemplate(SmsTemplateDo); } /** * 每次修改都需要审核,所以修改后就要把状态设置为禁用 * @param SmsTemplateDo * @return */ @Override public Integer updateTemplate(SmsTemplateDo SmsTemplateDo) { // 修改缓存 //String update = HttpClientUtil.postClient("update", SmsTemplateDo.getCode(), SmsTemplateDo.getContent()); //log.info("--- 修改缓存 :{}",update); String validStatus = SmsTemplateDo.getValidStatus();// if(validStatus.equals("on")){ SmsTemplateDo.setValidStatus("N");// }else {// SmsTemplateDo.setValidStatus("Y");// } //查询短信类型 if(StringUtils.isNotEmpty(SmsTemplateDo.getSmsType())){ SmsTypeDo smsTypeDo = smsTypeMapper.selectSmsTypeById(Integer.parseInt(SmsTemplateDo.getSmsType())); SmsTemplateDo.setPriority(smsTypeDo.getSmsPriority()); SmsTemplateDo.setTimeLimit(smsTypeDo.getTimeLimit()); } //String del = HttpClientUtil.postClient("del", "DEFAULT_smsTemplate_"+SmsTemplateDo.getCode(),null); //log.info("--- 修改完模板删除sms中redis :{}",del); cacheUtil.stringPut(Constants.CMPP_SMS_TEMPLATE + SmsTemplateDo.getCode(), JSONObject.toJSONString(SmsTemplateDo),null); return smsTemplateMapper.updateTemplate(SmsTemplateDo); } @Override public SmsTemplateDo selectTempById(int id) { SmsTemplateDo SmsTemplateDo = smsTemplateMapper.selectTempById(id); return SmsTemplateDo; } // 删除缓存 public String delRedis(String key){ String resultStr = ""; // 删除redis 数据 try { StringRedisModel stringRedisModel = new StringRedisModel(); stringRedisModel.setKey(key); stringRedisModel.setSystem("DEFAULT"); HttpUtil httpUtil = new HttpUtil(); resultStr = HttpUtil.httpPostWithJSON(netUrl + Constants.CACHE_SERVICE_STRING_DELETE_API, JSON.toJSONString(stringRedisModel)); }catch (Exception e) { e.printStackTrace(); return "{'status':'1','msg':'请求失败'}"; } return resultStr; }} |
package com.chinatower.product.sys.service.impl;import com.alibaba.fastjson.JSON;import com.chinatower.product.core.Constants;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.core.util.BuliderCodeUtil;import com.chinatower.product.core.util.HttpClientUtil;import com.chinatower.product.sys.core.feign.model.StringRedisModel;import com.chinatower.product.sys.core.util.HttpUtil;import com.chinatower.product.sys.entity.SmsTemplateDo;import com.chinatower.product.sys.entity.SmsTypeDo;import com.chinatower.product.sys.manager.SmsPushAlarmRedisManager;import com.chinatower.product.sys.mapper.SmsTemplateMapper;import com.chinatower.product.sys.mapper.SmsTypeMapper;import com.chinatower.product.sys.service.SmsTemplateService;import com.chinatower.product.sys.service.SmsTypeService;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import java.util.Date;import java.util.List;@Slf4j@Servicepublic class SmsTypeServiceImpl extends BaseServiceImpl<SmsTypeDo,String> implements SmsTypeService { @Autowired SmsTypeMapper smsTypeMapper; @Override public BaseMapper<SmsTypeDo, String> getMappser() { return smsTypeMapper; } public List<SmsTypeDo> selectListByPage(SmsTypeDo smsTypeDo) { return smsTypeMapper.selectListByPage(smsTypeDo); } @Transactional public Integer addSmsType(SmsTypeDo smsTypeDo) { Subject subject = SecurityUtils.getSubject(); CurrentUser currentUser = (CurrentUser)subject.getPrincipal(); smsTypeDo.setOpUser(currentUser.getUsername()); smsTypeDo.setOpTime(new Date()); return smsTypeMapper.addSmsType(smsTypeDo); } @Transactional public Integer delSmsType(int id) { return smsTypeMapper.delSmsType(id); } @Override public Integer updateSmsType(SmsTypeDo smsTypeDo) { Subject subject = SecurityUtils.getSubject(); CurrentUser currentUser = (CurrentUser)subject.getPrincipal(); smsTypeDo.setOpUser(currentUser.getUsername()); smsTypeDo.setOpTime(new Date()); return smsTypeMapper.updateSmsType(smsTypeDo); } @Override public SmsTypeDo selectSmsTypeById(int id) { SmsTypeDo smsTypeDo = smsTypeMapper.selectSmsTypeById(id); return smsTypeDo; } @Override public List<SmsTypeDo> selectAllSmsType() { return smsTypeMapper.selectAllSmsType(); }} |
package com.chinatower.product.sys.service.impl;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.sys.mapper.SysRefererMapper;import com.chinatower.product.sys.service.*;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.Set;@Service@Slf4jpublic class SysRefererServiceImpl implements SysRefererService { @Autowired private SysRefererMapper sysRefererMapper; @Override public Set<String> getIp() { Set<String> ip = sysRefererMapper.getIp(); log.info("ip包含:{}", JSONObject.toJSONString(ip)); return ip; }} |
package com.chinatower.product.sys.service.impl;import com.alibaba.fastjson.JSONArray;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.CurrentMenu;import com.chinatower.product.core.base.CurrentRole;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.base.impl.BaseServiceImpl;import com.chinatower.product.sys.core.shiro.Principal;import com.chinatower.product.sys.entity.SysMenu;import com.chinatower.product.sys.entity.SysRole;import com.chinatower.product.sys.entity.SysRoleUser;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.core.exception.MyException;import com.chinatower.product.sys.mapper.SysRoleUserMapper;import com.chinatower.product.sys.mapper.SysUserMapper;import com.chinatower.product.sys.service.MenuService;import com.chinatower.product.sys.service.RoleService;import com.chinatower.product.sys.service.RoleUserService;import com.chinatower.product.sys.service.SysUserService;import com.chinatower.product.core.util.BeanUtil;import com.chinatower.product.core.util.Checkbox;import com.chinatower.product.core.util.JsonUtil;import com.chinatower.product.core.util.Md5Util;import java.util.ArrayList;import java.util.List;import org.apache.commons.lang3.StringUtils;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.HashSet;import java.util.Set;/** * @author zhuxiaomeng * @date 2017/12/4. * @email [email protected] */@Servicepublic class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> implements SysUserService { @Autowired SysUserMapper sysUserMapper; @Autowired SysRoleUserMapper sysRoleUserMapper; @Autowired RoleService roleService; @Autowired RoleUserService roleUserService; @Autowired MenuService menuService; private static final String ADMIN = "admin"; @Override public BaseMapper<SysUser, String> getMappser() { return sysUserMapper; } @Override public SysUser login(String username) { return sysUserMapper.login(username); } @Override public int deleteByPrimaryKey(String id) { return sysUserMapper.deleteByPrimaryKey(id); } @Override public int insert(SysUser record) { return sysUserMapper.insert(record); } @Override public int insertSelective(SysUser record) { String pwd = Md5Util.getMD5(record.getPassword().trim(), record.getUsername().trim()); record.setPassword(pwd); return super.insertSelective(record); } @Override public SysUser selectByPrimaryKey(String id) { return sysUserMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(SysUser record) { return super.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(SysUser record) { return sysUserMapper.updateByPrimaryKey(record); } @Override public List<SysRoleUser> selectByCondition(SysRoleUser sysRoleUser) { return sysRoleUserMapper.selectByCondition(sysRoleUser); } /** * 分页查询 * * @param * @return */ @Override public List<SysUser> selectListByPage(SysUser sysUser) { return sysUserMapper.selectListByPage(sysUser); } @Override public int count() { return sysUserMapper.count(); } @Override public int add(SysUser user) { //密码加密 String pwd = Md5Util.getMD5(user.getPassword().trim(), user.getUsername().trim()); user.setPassword(pwd); return sysUserMapper.add(user); } @Override public JsonUtil delById(String id, boolean flag) { if (StringUtils.isEmpty(id)) { return JsonUtil.error("获取数据失败"); } JsonUtil j = new JsonUtil(); try { SysUser sysUser = selectByPrimaryKey(id); if (ADMIN.equals(sysUser.getUsername())) { return JsonUtil.error("超管无法删除"); } SysRoleUser roleUser = new SysRoleUser(); roleUser.setUserId(id); int count = roleUserService.selectCountByCondition(roleUser); if (count > 0) { return JsonUtil.error("账户已经绑定角色,无法删除"); } if (flag) { //逻辑 sysUser.setDelFlag(Byte.parseByte("1")); updateByPrimaryKeySelective(sysUser); } else { //物理 sysUserMapper.delById(id); } j.setMsg("删除成功"); } catch (MyException e) { j.setMsg("删除失败"); j.setFlag(false); e.printStackTrace(); } return j; } @Override public int checkUser(String username) { return sysUserMapper.checkUser(username); } @Override public List<Checkbox> getUserRoleByJson(String id) { List<SysRole> roleList = roleService.selectListByPage(new SysRole()); SysRoleUser sysRoleUser = new SysRoleUser(); sysRoleUser.setUserId(id); List<SysRoleUser> kList = selectByCondition(sysRoleUser); List<Checkbox> checkboxList = new ArrayList<>(); Checkbox checkbox; for (SysRole sysRole : roleList) { checkbox = new Checkbox(); checkbox.setId(sysRole.getId()); checkbox.setName(sysRole.getRoleName()); for (SysRoleUser sysRoleUser1 : kList) { if (sysRoleUser1.getRoleId().equals(sysRole.getId())) { checkbox.setCheck(true); break; } } checkboxList.add(checkbox); } return checkboxList; } @Override public int rePass(SysUser user) { return sysUserMapper.rePass(user); } @Override public List<SysUser> getUserByRoleId(String roleId) { return sysUserMapper.getUserByRoleId(roleId); } @Override public void setMenuAndRoles(String username) { SysUser s = new SysUser(); s.setUsername(username); s = this.selectOne(s); CurrentUser currentUser = new CurrentUser(s.getId(), s.getUsername(), s.getAge(), s.getEmail(), s.getPhoto(), s.getRealName()); Subject subject = Principal.getSubject(); /*角色权限封装进去*/ //根据用户获取菜单 Session session = subject.getSession(); List<SysMenu> menuList = menuService.getUserMenu(s.getId()); JSONArray json = menuService.getMenuJsonByUser(menuList); session.setAttribute("menu", json); List<CurrentMenu> currentMenuList = new ArrayList<>(); Set<SysRole> roleList = new HashSet<>(); for (SysMenu m : menuList) { CurrentMenu currentMenu = new CurrentMenu(); BeanUtil.copyNotNullBean(m, currentMenu); currentMenuList.add(currentMenu); roleList.addAll(m.getRoleList()); } List<CurrentRole> currentRoleList = new ArrayList<>(); for (SysRole r : roleList) { CurrentRole role = new CurrentRole(); BeanUtil.copyNotNullBean(r, role); currentRoleList.add(role); } currentUser.setCurrentRoleList(currentRoleList); currentUser.setCurrentMenuList(currentMenuList); session.setAttribute("currentPrincipal", currentUser); } /** * 更新session头像 */ @Override public void updateCurrent(SysUser sysUser) { CurrentUser principal = Principal.getPrincipal(); if(principal.getId().equals(sysUser.getId())){ //当前用户 CurrentUser currentUse = Principal.getCurrentUse(); Session session=Principal.getSession(); currentUse.setPhoto(sysUser.getPhoto()); session.setAttribute("currentPrincipal",currentUse); } } @Override public List<String> queryUserRole(String username) { return sysUserMapper.queryUserRole(username); }} |
package com.chinatower.product.core.annotation;import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})@Inheritedpublic @interface UserData {} |
package com.chinatower.product.core;/** * Hello world! * */public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); }} |
package com.chinatower.product.core.base;import com.alibaba.fastjson.JSON;import com.google.common.collect.Maps;import lombok.extern.slf4j.Slf4j;import org.apache.shiro.authz.AuthorizationException;import org.apache.shiro.authz.UnauthorizedException;import org.springframework.beans.propertyeditors.CustomDateEditor;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.InitBinder;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;/** * @author zhuxiaomeng * @date 2017/12/19. * @email [email protected] */@Slf4jpublic abstract class BaseController<T> { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new CustomDateEditor( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true)); binder.registerCustomEditor(Date.class, new CustomDateEditor( new SimpleDateFormat("yyyy-MM-dd"), true)); } @ExceptionHandler({UnauthorizedException.class, AuthorizationException.class}) public String authorizationException(HttpServletRequest request, HttpServletResponse response) { if (isAjaxRequest(request)) { Map<String, Object> map = Maps.newHashMap(); map.put("code", "403"); map.put("message", "无权限"); return JSON.toJSONString(map); } else { String message = "权限不足"; try { message = URLEncoder.encode(message, "utf-8"); } catch (UnsupportedEncodingException e) { log.error("BaseController:" + e.getMessage()); e.printStackTrace(); } return "redirect:/error/403?message=" + message; } } private static boolean isAjaxRequest(HttpServletRequest request) { String requestedWith = request.getHeader("x-requested-with"); return requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest"); }} |
package com.chinatower.product.core.base;import org.apache.ibatis.annotations.Param;import tk.mybatis.mapper.common.IdsMapper;import java.io.Serializable;import java.util.List;/** * @author zhuxiaomeng * @date 2017/12/12. * @email [email protected] * mapper封装 crud */public interface BaseMapper<T, E extends Serializable> extends tk.mybatis.mapper.common.Mapper<T>, LenInsertListAndinsertUseGeneratedKeysMapper<T>, IdsMapper<T> { /* *//** * 根据id删除 * @param id * @return *//* int deleteByPrimaryKey(E id); *//** * 插入 * @param record * @return *//* int insert(T record); *//** *插入非空字段 * @param record * @return *//* int insertSelective(T record); *//** * 根据id查询 * @param id * @return *//* T selectByPrimaryKey(E id); *//** * 更新非空数据 * @param record * @return *//* int updateByPrimaryKeySelective(T record); *//** * 更新 * @param record * @return *//* int updateByPrimaryKey(T record); */ /** * 查询 * * @param record * @return */ List<T> selectListByPage(T record);} |
package com.chinatower.product.core.base;import com.chinatower.product.core.util.ReType;import org.apache.ibatis.session.RowBounds;import java.io.Serializable;import java.util.List;/** * @author zhuxiaomeng * @date 2017/12/13. * @email [email protected] * 通用service层 */public interface BaseService<T, E extends Serializable> { public List<T> select(T t); public List<T> selectAll(); public List<T> selectByIds(String ids); public int selectCount(T t); public int deleteByPrimaryKey(E id); public int insert(T record); public int insertSelective(T record); public int updateByPrimaryKeySelective(T record); public int updateByPrimaryKey(T record); public List<T> selectListByPage(T record); public int deleteByPrimaryKey(Object o); public int delete(T t); public boolean existsWithPrimaryKey(Object o); public T selectByPrimaryKey(Object o); public T selectOne(T t); public int deleteByIds(String s); public int insertList(List<T> list); public int insertUseGeneratedKeys(T t); public int deleteByExample(Object o); public List<T> selectByExample(Object o); public int selectCountByExample(Object o); public T selectOneByExample(Object o); public int updateByExample(T t, Object o); public int updateByExampleSelective(T t, Object o); public List<T> selectByExampleAndRowBounds(Object o, RowBounds rowBounds); public List<T> selectByRowBounds(T t, RowBounds rowBounds); public ReType show(T t, int page, int limit); public ReType getList(T t, int page, int limit); public String showAll(T t);} |
package com.chinatower.product.core.base;import java.io.Serializable;import java.util.Date;import lombok.Getter;import lombok.Setter;import lombok.ToString;/** * @author zhuxiaomeng * @date 2017/12/30. * @email [email protected] */@Getter@Setter@ToStringpublic class CurrentMenu implements Serializable { /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 1L; private String id; private String name; private String pId; private String url; private Integer orderNum; private String icon; private String createBy; private Date createDate; private String updateBy; private Date updateDate; private String permission; private Byte menuType; /**菜单排序id 填充菜单展示id*/ private int num; public CurrentMenu(String id, String name, String pId, String url, Integer orderNum, String icon, String permission, Byte menuType, int num) { this.id = id; this.name = name; this.pId = pId; this.url = url; this.orderNum = orderNum; this.icon = icon; this.permission = permission; this.menuType = menuType; this.num = num; } public CurrentMenu() { }} |
package com.chinatower.product.core.base;import java.io.Serializable;import lombok.Data;import lombok.Getter;import lombok.Setter;import lombok.ToString;/** * @author zhuxiaomeng * @date 2017/12/30. * @email [email protected] */@Datapublic class CurrentRole implements Serializable { /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 1L; private String id; private String roleName; private String remark; public CurrentRole(String id, String roleName, String remark) { this.id = id; this.roleName = roleName; this.remark = remark; } public CurrentRole() { }} |
package com.chinatower.product.core.base;import java.io.Serializable;import java.util.Date;import java.util.List;import lombok.Getter;import lombok.Setter;import lombok.ToString;@Getter@Setter@ToStringpublic class CurrentUser implements Serializable { private String id; private String username; private String password; private Integer age; private String email; private String photo; private String realName; private String createBy; private String updateBy; private Date createDate; private Date updateDate; private Byte delFlag; private List<CurrentMenu> currentMenuList; private List<CurrentRole> currentRoleList; private static final long serialVersionUID = 1L; public CurrentUser(String id, String username, Integer age, String email, String photo, String realName) { this.id = id; this.username = username; this.age = age; this.email = email; this.photo = photo; this.realName = realName; } public CurrentUser() { }} |
package com.chinatower.product.core.base.impl;import com.alibaba.fastjson.JSON;import com.chinatower.product.core.base.BaseMapper;import com.chinatower.product.core.base.BaseService;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.exception.MyException;import com.chinatower.product.core.util.ReType;import com.github.pagehelper.Page;import com.github.pagehelper.PageHelper;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.session.RowBounds;import org.apache.shiro.SecurityUtils;import java.io.Serializable;import java.lang.reflect.Field;import java.util.Date;import java.util.List;import java.util.UUID;/** * @author zhuxiaomeng * @date 2017/12/13. * @email [email protected] */@Slf4jpublic abstract class BaseServiceImpl<T, E extends Serializable> implements BaseService<T, E> { /** * general field(通用字段) */ private static final String CREATE_BY = "createBy"; private static final String CREATE_DATE = "createDate"; private static final String UPDATE_BY = "updateBy"; private static final String UPDATE_DATE = "updateDate"; //系统默认 id 如果主键为其他字段 则需要自己手动 生成 写入 id private static final String ID = "id"; private static final String STR = "java.lang.String"; public abstract BaseMapper<T, E> getMappser(); @Override public List<T> select(T t) { return getMappser().select(t); } @Override public List<T> selectAll() { return getMappser().selectAll(); } @Override public List<T> selectByIds(String ids) { return getMappser().selectByIds(ids); } @Override public int selectCount(T t) { return getMappser().selectCount(t); } @Override public int deleteByPrimaryKey(E id) { return getMappser().deleteByPrimaryKey(id); } @Override public int insert(T record) { try { record = addValue(record, true); }catch (Exception e){ } return getMappser().insert(record); } /** * 通用注入创建 更新信息 可通过super调用 * * @param record * @param flag * @return */ public T addValue(T record, boolean flag) { CurrentUser currentUser = (CurrentUser) SecurityUtils.getSubject().getSession().getAttribute("currentPrincipal"); //统一处理公共字段 Class<?> clazz = record.getClass(); String operator, operateDate; try { if (flag) { //添加 id uuid支持 Field idField = clazz.getDeclaredField(ID); idField.setAccessible(true); Object o = idField.get(record); Class<?> type = idField.getType(); String name = type.getName(); if ((o == null) && STR.equals(name)) { //已经有值的情况下 不覆盖 idField.set(record, UUID.randomUUID().toString().replace("-", "").toLowerCase()); } operator = CREATE_BY; operateDate = CREATE_DATE; } else { operator = UPDATE_BY; operateDate = UPDATE_DATE; } Field field = clazz.getDeclaredField(operator); field.setAccessible(true); field.set(record, currentUser.getId()); Field fieldDate = clazz.getDeclaredField(operateDate); fieldDate.setAccessible(true); fieldDate.set(record, new Date()); } catch (NoSuchFieldException e) { //无此字段 } catch (IllegalAccessException e) { e.printStackTrace(); } return record; } @Override public int insertSelective(T record) { try { record = addValue(record, true); }catch (Exception e){ } return getMappser().insertSelective(record); } @Override public int updateByPrimaryKeySelective(T record) { try { record = addValue(record, false); }catch (Exception e){ } return getMappser().updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(T record) { try { record = addValue(record, false); }catch (Exception e){ } return getMappser().updateByPrimaryKey(record); } public List<T> selectListByPage(T record) { return getMappser().selectListByPage(record); } @Override public int deleteByPrimaryKey(Object o) { return getMappser().deleteByPrimaryKey(o); } @Override public int delete(T t) { return getMappser().delete(t); } @Override public boolean existsWithPrimaryKey(Object o) { return getMappser().existsWithPrimaryKey(o); } @Override public T selectByPrimaryKey(Object o) { return getMappser().selectByPrimaryKey(o); } @Override public T selectOne(T t) { return getMappser().selectOne(t); } @Override public int deleteByIds(String s) { return getMappser().deleteByIds(s); } @Override public int insertList(List<T> list) { return getMappser().insertList(list); } @Override public int insertUseGeneratedKeys(T t) { return getMappser().insertUseGeneratedKeys(t); } /** * 公共展示类 * * @param t 实体 * @param page 页 * @param limit 行 * @return */ @Override public ReType show(T t, int page, int limit) { List<T> tList = null; Page<T> tPage = PageHelper.startPage(page, limit); try { tList = getMappser().selectListByPage(t); } catch (MyException e) { log.error("class:BaseServiceImpl ->method:show->message:" + e.getMessage()); e.printStackTrace(); } return new ReType(tPage.getTotal(), tList); } @Override public String showAll(T t) { List<T> tList = null; try { tList = getMappser().selectListByPage(t); } catch (MyException e) { log.error("class:BaseServiceImpl ->method:show->message:" + e.getMessage()); e.printStackTrace(); } return JSON.toJSONString(tList); } @Override public ReType getList(T t, int page, int limit) { List<T> tList = null; Page<T> tPage = PageHelper.startPage(page, limit); try { tList = getMappser().selectListByPage(t); } catch (MyException e) { log.error("class:BaseServiceImpl ->method:getList->message:" + e.getMessage()); e.printStackTrace(); } return new ReType(tPage.getTotal(),tPage.getPageNum(), tList); } @Override public int deleteByExample(Object o) { return getMappser().deleteByExample(o); } @Override public List<T> selectByExample(Object o) { return getMappser().selectByExample(o); } @Override public int selectCountByExample(Object o) { return getMappser().selectCountByExample(o); } @Override public T selectOneByExample(Object o) { return getMappser().selectOneByExample(o); } @Override public int updateByExample(T t, Object o) { return getMappser().updateByExample(t,o); } @Override public int updateByExampleSelective(T t, Object o) { return getMappser().updateByExampleSelective(t,o); } @Override public List<T> selectByExampleAndRowBounds(Object o, RowBounds rowBounds) { return getMappser().selectByExampleAndRowBounds(o,rowBounds); } @Override public List<T> selectByRowBounds(T t, RowBounds rowBounds) { return getMappser().selectByRowBounds(t,rowBounds); }} |
package com.chinatower.product.core.base;import org.apache.ibatis.annotations.InsertProvider;import org.apache.ibatis.annotations.Options;import java.util.List;/** * @author zhuxiaomeng * @date 2018/10/12. * @email [email protected] */@tk.mybatis.mapper.annotation.RegisterMapperpublic interface LenInsertListAndinsertUseGeneratedKeysMapper<T> { @Options(useGeneratedKeys = true, keyProperty = "id") @InsertProvider(type = MySpecialProvider.class, method = "dynamicSQL") int insertList(List<T> recordList); @Options(useGeneratedKeys = true, keyProperty = "id") @InsertProvider(type = MySpecialProvider.class, method = "dynamicSQL") int insertUseGeneratedKeys(T record);} |
package com.chinatower.product.core.base;import org.apache.ibatis.mapping.MappedStatement;import tk.mybatis.mapper.entity.EntityColumn;import tk.mybatis.mapper.entity.EntityTable;import tk.mybatis.mapper.mapperhelper.EntityHelper;import tk.mybatis.mapper.mapperhelper.MapperHelper;import tk.mybatis.mapper.mapperhelper.MapperTemplate;import tk.mybatis.mapper.mapperhelper.SqlHelper;import java.util.Set;/** * @author zhuxiaomeng * @date 2018/10/12 * @email [email protected] * 重写 SpecialProvider 使得批量方法支持主键自增和自定义自增 (仅测试了mysql) */public class MySpecialProvider extends MapperTemplate { public MySpecialProvider(Class<?> mapperClass, MapperHelper mapperHelper) { super(mapperClass, mapperHelper); } public String insertList(MappedStatement ms) { final Class<?> entityClass = getEntityClass(ms); //开始拼sql StringBuilder sql = new StringBuilder(); sql.append(SqlHelper.insertIntoTable(entityClass, tableName(entityClass))); boolean keyIsAuto = keyIsAuto(entityClass); sql.append(SqlHelper.insertColumns(entityClass, keyIsAuto, false, false)); sql.append(" VALUES "); sql.append("<foreach collection=\"list\" item=\"record\" separator=\",\" >"); sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">"); //获取全部列 Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass); for (EntityColumn column : columnList) { if (column.isId() && column.isInsertable()) { if (!keyIsAuto) { sql.append(column.getColumnHolder("record")).append(","); } } else if (column.isInsertable()) { sql.append(column.getColumnHolder("record")).append(","); } } sql.append("</trim>"); sql.append("</foreach>"); return sql.toString(); } /** * 调用insertList insertUseGeneratedKeys * 判断是否为 自增主键 当@GeneratedValue(generator = "JDBC") 为主键自增 删除此注解为自定义 * * @param entityClass 当前实体 * @return 是否为自增主键 true 是 false 否 */ private boolean keyIsAuto(Class<?> entityClass) { EntityTable entityTable = EntityHelper.getEntityTable(entityClass); entityTable.getEntityClassColumns(); Set<EntityColumn> entityClassPKColumns = entityTable.getEntityClassPKColumns(); for (EntityColumn entityColumn : entityClassPKColumns) { String generator = entityColumn.getGenerator(); if ("JDBC".equals(generator)) { return true; } } return false; } public String insertUseGeneratedKeys(MappedStatement ms) { final Class<?> entityClass = getEntityClass(ms); //开始拼sql StringBuilder sql = new StringBuilder(); sql.append(SqlHelper.insertIntoTable(entityClass, tableName(entityClass))); boolean keyIsAuto = keyIsAuto(entityClass); sql.append(SqlHelper.insertColumns(entityClass, keyIsAuto, false, false)); sql.append(SqlHelper.insertValuesColumns(entityClass, keyIsAuto, false, false)); return sql.toString(); }} |
package com.chinatower.product.core.constant;public class RabbitmqConstant { //创建vhost名称前缀 public static final String RABBITMQ_VHOST_PREFIX = "SMS_"; //rabbbitmq认证请求头值 public static final String AUTH_HEADER = "authorization"; //rabbitmq认证值前缀 public static final String AUTH_VALUE_PREFIX = "Basic ";} |
package com.chinatower.product.core.constant;public class UserRoleConstant { public static final String USER_ROLE = "admin,monitor";} |
package com.chinatower.product.core;public class Constants { public static final String CMPP_SMS_TEMPLATE="DEFAULT_smsTemplate_"; public static final String CMPP_SMS_SIGN="DEFAULT_smsSign_"; //ReType返回成功的标识 public static final Integer API_SUCCES_STATUS_CODE = 0; //ReType返回失败的标识 public static final Integer API_ERR_STATUS_CODE = 500; //缓存服务API接口请求成功标识 public static final String CACHE_SUCCES_STATUS_CODE = "0"; //缓存服务API接口请求失败标识 public static final String CACHE_ERR_STATUS_CODE = "1"; //缓存服务API接口请求状态key public static final String CACHE_STATUS_FLAG = "status"; //缓存服务API接口请求数据key public static final String CACHE_DATA_FLAG = "data"; //缓存组件中的系统 public static final String CACHE_SYSTEM = "DEFAULT"; //缓存服务中修改string类型数据的接口地址 public static final String CACHE_SERVICE_STRING_PUT_API = "/string/put"; //缓存服务中获取string类型数据的接口地址 public static final String CACHE_SERVICE_STRING_GET_API = "/string/get"; //缓存服务中判断hash类型数据是否存在的接口地址 public static final String CACHE_SERVICE_HASH_EXIST_API = "/hash/exist"; //缓存服务中获取hash类型数据的接口地址 public static final String CACHE_SERVICE_HASH_GET_API = "/hash/get"; //缓存服务中获取kay剩余时间的接口地址 public static final String CACHE_SERVICE_KEY_KEYLIVE_API = "/keylive"; //缓存服务中hash类型删除某字段的接口地址 public static final String CACHE_SERVICE_HASH_hdel_API = "/hash/hdel"; //缓存服务中hash类型将键key存储的值加上整数increment的接口地址 public static final String CACHE_SERVICE_HASH_HINCRYBY_API = "/hash/hincryby"; //缓存服务中hash类型新增或修改的接口地址 public static final String CACHE_SERVICE_HASH_ADD_API = "/hash/add"; //缓存服务中删除string类型数据的接口地址 public static final String CACHE_SERVICE_STRING_DELETE_API = "/string/delete"; //缓存服务中添加string类型数据的接口地址 public static final String CACHE_SERVICE_STRING_ADD_API = "/string/add"; //系统对接短信组件是否开启发送redis中key后缀 public static final String CACHE_SMS_SYSTEM_SEND_ISENABLE_SUFFIX = "_sms_isEnabled"; //短信组件当前发送流量在redis中key前缀 public static final String CACHE_SMS_GATEWAY_SEND_RATE_PREFIX = "sms_rate_gate_"; //短信组件网关配置在redis中key public static final String CACHE_SMS_GATEWAY_CONFIG_KEY = "sms_gateway_config_list"; //短信组件白名单敏感词配置在redis中key public static final String CACHE_SMS_ALLOW_WORD_CONFIG_KEY = "sms_allow_keyword_config_list"; //短信组件黑名单敏感词配置在redis中key public static final String CACHE_SMS_BLOCK_WORD_CONFIG_KEY = "sms_block_keyword_config_list"; //短信组件手机号告警配置在redis中key前缀 public static final String CACHE_SMS_PUSH_ALARM_KEY_PREFIX = "DEFAULT_smsPushAlarmPhone_"; //短信组件短信告警配置在redis中key后缀 public static final String CACHE_SMS_PUSH_ALARM_KEY_SUFFIX = "_sms_pushAlarm"; //统一通知平台过滤ip在redis中key前缀 public static final String CACHE_INFORM_MANAGE_IP_FILTER_BLACK_KEY_PREFIX = "inform_manage_filter_ip_black_"; //统一通知平台过滤ip在redis中key前缀 public static final String CACHE_INFORM_MANAGE_IP_FILTER_NORMAL_KEY_PREFIX = "inform_manage_filter_ip_normal"; public static final String CACHE_INFORM_MANAGE_IP_COUNT_KEY_PREFIX = "inform_manage_count_"; public static final String CACHE_INFORM_MANAGE_IP_TIME_KEY_PREFIX = "inform_manage_time_"; //短信组件白名单敏感词配置表名 public static final String SMS_ALLOW_WORD_TABLE = "sms_allow_word"; //短信组件黑名单敏感词配置表名 public static final String SMS_BLOCK_WORD_TABLE = "sms_block_word"; //短信组件cmpp_submit表前缀 public static final String SMS_CMPP_SUBMIT_TABLE_PREFIX = "cmpp_submit_"; //短信组件sms_produce_log表前缀 public static final String SMS_PRODUCE_LOG_TABLE_PREFIX = "sms_produce_log_"; //短信组件sms_send_log表前缀 public static final String SMS_SEND_LOG_TABLE_PREFIX = "sms_send_log_"; //短信组件sms_receive_log表前缀 public static final String SMS_RECEIVE_LOG_TABLE_PREFIX = "sms_receive_log_";} |
package com.chinatower.product.core.exception;import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import java.util.Map;/** * @author zhuxiaomeng * @date 2018/5/6. * @email [email protected] */@ControllerAdvicepublic class CustomErrorViewResolver implements ErrorViewResolver { static final String PAGE_500 = "/error/500"; static final String PAGE_404 = "/error/404"; static final String PAGE_403 = "/error/403"; static final String OTHER_ERROR = "/error/error"; @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { boolean isServerError = status.is5xxServerError(); ModelAndView andView = new ModelAndView(); andView.addObject("message", model.get("message")); if (status.value() == 404) { andView.setViewName(PAGE_404); } else if (status.value() == 403) { andView.setViewName(PAGE_403); } else if (isServerError) { andView.setViewName(PAGE_500); } else { andView.addObject("status", status.value()); andView.setViewName(OTHER_ERROR); } return andView; }} |
package com.chinatower.product.core.exception;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import lombok.extern.slf4j.Slf4j;import org.apache.shiro.authz.UnauthorizedException;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;/** * @author zhuxiaomeng * @date 2017/12/8. * @email [email protected] */@Slf4jpublic class CustomException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView mv=new ModelAndView("/error/error"); if(e instanceof UnauthorizedException){ //处理拦截shiro 无权限 mv.setViewName("/login"); return mv; } e.printStackTrace(); MyException myExecption=null; if(e instanceof MyException){ myExecption=(MyException)e; }else{ myExecption=new MyException("未知错误"); } //错误信息 String message=myExecption.getMessage(); ModelAndView modelAndView=new ModelAndView(); //将错误信息传到页面 modelAndView.addObject("message",message); //指向到错误界面 return mv; }} |
package com.chinatower.product.core.exception;/** * @author zhuxiaomeng * @date 2017/12/15. * @email [email protected] */public class MyException extends RuntimeException { private String message; public MyException(String message){ super(message); this.message=message; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }} |
package com.chinatower.product.core.freemarker;import com.jagregory.shiro.freemarker.ShiroTags;import freemarker.template.Configuration;import freemarker.template.TemplateException;import java.io.IOException;import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;/** * @author zhuxiaomeng * @date 2017/12/11. * @email [email protected] */public class MyFreemarkerConfig extends FreeMarkerConfigurer { @Override public void afterPropertiesSet() throws IOException, TemplateException { super.afterPropertiesSet(); Configuration configuration=this.getConfiguration(); configuration.setSharedVariable("shiro",new ShiroTags()); configuration.setNumberFormat("#"); }} |
package com.chinatower.product.core.redis;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;import javax.annotation.Resource;import java.util.concurrent.TimeUnit;/** * @author zhuxiaomeng * @date 2018/11/24. * @email [email protected] */@Servicepublic class RedisService { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<Object, Object> redisTemplate; @Resource(name = "stringRedisTemplate") private ValueOperations<String, String> valueOps; @Resource(name = "redisTemplate") private ValueOperations<Object, Object> valOpsObj; @Value("${redis.prefix}") private String prefix; /** * 获取缓存字符串 根据key * * @param key 字符串key * @return value */ public String get(String key) { key = prefix + key; return valueOps.get(key); } /** * set value and cache timeout by str key * * @param key 字符串key * @param value 字符串value * @param second 过期时间 单位 秒 */ public void set(String key, String value, Long second) { key = prefix + key; valueOps.set(key, value, second,TimeUnit.SECONDS); } /** * get object value by key * * @param key obj key * @return obj value */ public Object getObj(Object key) { key = prefix + key.toString(); return valOpsObj.get(key); } /** * set value by key * * @param key obj key * @param value obj value * @param second 过期时间 单位户 秒 */ public void setObj(Object key, Object value, Long second) { key = prefix + key.toString(); valOpsObj.set(key, value, second,TimeUnit.SECONDS); } /** * delete by key * * @param key key */ public void del(String key) { stringRedisTemplate.delete(prefix + key); } /** * delete by key * * @param key obj key */ public void delObj(Object key) { redisTemplate.delete(prefix + key.toString()); }} |
package com.chinatower.product.core.util;import org.springframework.util.StringUtils;import sun.misc.BASE64Decoder;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;public class AESUtil { //密钥 (需要前端和后端保持一致)十六位作为密钥 private static final String KEY = "WHVe7wGPY%0!W!3c"; //密钥偏移量 (需要前端和后端保持一致)十六位作为密钥偏移量 private static final String IV = "2#P3z#IFE9zrYgD*"; //算法 private static final String ALGORITHMSTR = "AES/CBC/PKCS5Padding"; /** * base 64 decode * @param base64Code 待解码的base 64 code * @return 解码后的byte[] * @throws Exception */ public static byte[] base64Decode(String base64Code) throws Exception{ return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code); } /** * AES解密 * @param encryptBytes 待解密的byte[] * @return 解密后的String * @throws Exception */ public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHMSTR); byte[] temp = IV.getBytes("UTF-8"); IvParameterSpec iv = new IvParameterSpec(temp); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"), iv); byte[] decryptBytes = cipher.doFinal(encryptBytes); //System.out.print(new String(decryptBytes)); return new String(decryptBytes); } /** * 将base 64 code AES解密 * @param encryptStr 待解密的base 64 code * @return 解密后的string * @throws Exception */ public static String aesDecrypt(String encryptStr) throws Exception { return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr)); }} |
package com.chinatower.product.core.util;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/** * @author zhuxiaomeng * @date 2018/1/5. * @email [email protected] */public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ApplicationContextUtil.applicationContext=applicationContext; } public static ApplicationContext getContext(){ return applicationContext; } public static Object getBean(String arg){ return applicationContext.getBean(arg); }} |
package com.chinatower.product.core.util;import java.beans.PropertyDescriptor;import java.util.HashSet;import java.util.Set;import org.springframework.beans.BeanUtils;import org.springframework.beans.BeanWrapper;import org.springframework.beans.BeanWrapperImpl;/** * @author zhuxiaomeng * @date 2017/12/18. * @email [email protected] * 对象操作 */public class BeanUtil { public static String[] getNullPropertyNames(Object source) { final BeanWrapper src = new BeanWrapperImpl(source); PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<>(); for (PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null){ emptyNames.add(pd.getName()); } } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } /** * 非空拷贝 * @param source * @param target */ public static void copyNotNullBean(Object source, Object target) { BeanUtils.copyProperties(source, target, getNullPropertyNames(source)); }} |
package com.chinatower.product.core.util;import java.util.Random;/** *@author Soul liang *@desc 随机生成六位数码 * @Vesion 1.0 * @create 2019/7/11 **/public class BuliderCodeUtil { public static String builderCode() { //生成策略_8位偏移量 StringBuffer buffer = new StringBuffer("abcdefghijklmnopqrstuvwxyz"); StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = buffer.length(); for (int i = 0; i < 8; i++) { if(i==4){ sb.append("_"); } sb.append(buffer.charAt(r.nextInt(range))); } return sb.toString(); }} |
package com.chinatower.product.core.util;import lombok.Getter;import lombok.Setter;/** * @author zhuxiaomeng * @date 2017/12/21. * @email [email protected] * 复选框类 */@Getter@Setterpublic class Checkbox { private String id; private String name; /**默认未选择*/ private boolean check=false;} |
package com.chinatower.product.core.util;import com.chinatower.product.core.base.CurrentUser;import org.apache.shiro.SecurityUtils;import org.apache.shiro.session.Session;/** * @author zhuxiaomeng * @date 2017/12/4. * @email [email protected] * * 管理工具类 */public class CommonUtil { /** * 获取当前用户 */ public static CurrentUser getUser() { org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(); return (CurrentUser) session.getAttribute("currentPrincipal"); }} /** * 获取权限 * @return */ /*public static List<SysPermission> getPermission(){ SysUser user=CommonUtil.getUser(); if(user!=null){ } }}*/ |
package com.chinatower.product.core.util;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;/** * @author zhuxiaomeng * @date 2017/12/6. * @email [email protected] * 获取上下文 */public class ContextUtil { public static HttpServletRequest getServletRequest(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return request; } public static HttpSession getSession(){ return getServletRequest().getSession(); }} |
package com.chinatower.product.core.util;import org.apache.shiro.authc.UsernamePasswordToken;/** * @author zhuxiaomeng * @date 2018/8/18. * @email [email protected] */public class CustomUsernamePasswordToken extends UsernamePasswordToken { private String type; public CustomUsernamePasswordToken(final String username, final String password, String loginType) { super(username,password); this.type = loginType; } public String getType() { return type; } public void setType(String type) { this.type = type; }} |
package com.chinatower.product.core.util;import com.alibaba.fastjson.JSON;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import java.util.HashMap;import java.util.Map;/** *@author Soul liang *@desc HttpClient * @Vesion 1.0 * @create 2019/7/19 **/@Componentpublic class HttpClientUtil { /** *@author Soul liang * @param url 路径 * @param key key值 * @param value value值 * @Vesion 1.0 * @create 2019/7/22 **/ public static String netUrl; public static String prekey; // 使用Value值获取配置文件中的值 @Value("${codis.netUrl}") public void setNetUrl(String netUrl) { this.netUrl = netUrl; } @Value("${codis.prekey}") public void setPrekey(String prekey) { this.prekey = prekey; } public static String postClient(String url,String key,Object value){ String subX = getIndex(key); System.out.println(subX); StringBuilder str = new StringBuilder(prekey); key = str.append(subX).toString(); Map<String,Object> map = new HashMap<>(); map.put("key",key); map.put("value",value); String postParams = JSON.toJSONString(map); StringBuilder Burl = new StringBuilder(netUrl); String postUrl = Burl.append(url).toString(); CloseableHttpClient httpClient = null; HttpPost postMethod = null; HttpResponse response = null; try { httpClient = HttpClients.createDefault(); postMethod = new HttpPost(postUrl);//传入URL地址 //传入请求参数 StringEntity stringEntity = new StringEntity(postParams, ContentType.APPLICATION_JSON); postMethod.setEntity(stringEntity); System.out.println("POST 请求...." + postMethod.getURI()); response = httpClient.execute(postMethod);//获取响应 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("HTTP Status Code:" + statusCode); if (statusCode != HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String ent = EntityUtils.toString(entity); return ent; } HttpEntity httpEntity = response.getEntity(); String reponseContent = EntityUtils.toString(httpEntity); EntityUtils.consume(httpEntity);//释放资源 System.out.println("响应内容:" + reponseContent); return reponseContent; } catch (Exception e) { e.printStackTrace(); return "{'flag':'1','msg':'请求失败'}"; } } /** * @param string 字符串 * @return 前缀不变,后缀删除 '_' 字符 */ public static String getIndex(String string) { // 对于自定义数据,将‘_’字符去除 StringBuilder strBulider = new StringBuilder(); char[] chars = string.toCharArray(); for (char aChar : chars) { if('_'!=aChar){ strBulider.append(aChar); } } String instr = strBulider.toString(); return instr; }} |
package com.chinatower.product.core.util;import javax.servlet.http.HttpServletRequest;/** * @author zhuxiaomeng * @date 2017/12/28. * @email [email protected] */public class IpUtil { public static String getIp(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("X-Real-IP"); } if(ip==null || ip.length()==0 || "unknown".equalsIgnoreCase(ip)){ ip=request.getRemoteAddr(); } return ip; }} |
package com.chinatower.product.core.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JdbcUtil { public static Connection getConnection() { Connection con = null; String driverName = "com.mysql.jdbc.Driver";// String dbURL = "jdbc:mysql://localhost:3306/z_eas?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false"; String dbURL="jdbc:mysql://localhost:3306/z_eas?useUnicode=true&characterEncoding=UTF-8"; String userName = "root"; String userPwd = "123"; try { Class.forName(driverName); con = DriverManager.getConnection(dbURL, userName, userPwd); } catch (Exception e) { System.out.println("获取连接失败." + e.getMessage()); } return con; } public static void main(String[] args) throws SQLException { Connection con= getConnection(); Statement statement = con.createStatement(); String sql = "select * from z_user"; ResultSet rs = statement.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString("username")); } }} |
package com.chinatower.product.core.util;import com.alibaba.fastjson.JSONObject;import lombok.Data;/** * @author zhuxiaomeng * @date 2017/12/15. * @email [email protected] * ajax 回执 */@Datapublic class JsonUtil { //默认成功 private boolean flag = true; private String msg; private JSONObject josnObj; private Integer status; private Object data; public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public JsonUtil() { } public JsonUtil(boolean flag, String msg) { this.flag = flag; this.msg = msg; } public JsonUtil(boolean flag, String msg, Integer status) { this.flag = flag; this.msg = msg; this.status = status; } /** * restful 返回 */ public static JsonUtil error(String msg) { return new JsonUtil(false, msg); } public static JsonUtil sucess(String msg) { return new JsonUtil(true, msg); }} |
package com.chinatower.product.core.util;import org.apache.shiro.authc.AuthenticationToken;/** * @author zhuxiaomeng * @date 2018/8/19. * @email [email protected] */public class JwtToken implements AuthenticationToken { private String token; private String type; public JwtToken(String token,String type) { this.token = token; this.type=type; } @Override public Object getPrincipal() { return token; } @Override public Object getCredentials() { return token; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getType() { return type; } public void setType(String type) { this.type = type; }} |
package com.chinatower.product.core.util;import com.auth0.jwt.JWT;import com.auth0.jwt.JWTVerifier;import com.auth0.jwt.algorithms.Algorithm;import com.auth0.jwt.exceptions.JWTDecodeException;import com.auth0.jwt.interfaces.DecodedJWT;import java.util.Arrays;import java.util.Date;import java.util.List;public class JWTUtil { /** * 过期时间3小时 */ private static final long EXPIRE_TIME = 3 * 60 * 60 * 1000; /** * 校验token是否正确 * * @param token 密钥 * @param secret 用户的密码 * @return 是否正确 */ public static boolean verify(String token, String username, String secret) { try { Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", username) .build(); DecodedJWT jwt = verifier.verify(token); return true; } catch (Exception exception) { return false; } } /** * @return token中包含的用户名 */ public static String getUsername(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } catch (JWTDecodeException e) { return null; } } /** * 获取当前用户 * * @param token jwt加密信息 * @return 解析的当前用户信息 */ public static Principal getPrincipal(String token) { try { Principal principal = new Principal(); DecodedJWT jwt = JWT.decode(token); principal.setUserId(jwt.getClaim("userId").asString()); principal.setUserName(jwt.getClaim("username").asString()); String[] roleArr = jwt.getClaim("roles").asArray(String.class); if (roleArr != null) { principal.setRoles(Arrays.asList(roleArr)); } return principal; } catch (JWTDecodeException e) { return null; } } /** * 获取角色组 * * @param token * @return */ public static String[] getRoles(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("roles").asArray(String.class); } catch (JWTDecodeException e) { return null; } } /** * 生成签名 * * @param username 用户名 * @param userId 用户id * @param secret 用户的密码 * @return 加密的token */ public static String sign(String username, String userId, List<String> roles, String secret) { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); String[] roleArr = new String[roles.size()]; roleArr = roles.toArray(roleArr); // 附带username信息 return JWT.create() .withClaim("userId", userId) .withClaim("username", username) .withArrayClaim("roles", roleArr) .withExpiresAt(date) .sign(algorithm); }} |
package com.chinatower.product.core.util;import org.apache.shiro.crypto.hash.Md5Hash;/** * @author zhuxiaomeng * @date 2017/12/7. * @email [email protected] * 采用md5加密 确保数据安全性 */public class Md5Util { public static String getMD5(String msg,String salt){ return new Md5Hash(msg,salt,4).toString(); } /** * 测试 * @param args */ public static void main(String[] args) { String str= getMD5("123456","tom"); System.out.println(str); }} |
package com.chinatower.product.core.util;/** * @author zhuxiaomeng * @date 2017/12/6. * @email [email protected] * 分页工具 */public class PageUtil <T>{ /**当前页*/ private int curPageNo=1; private int pageCount;//总页数 private int pageSize=5;//每页大小 默认5 private int upPageNo;//上一页 private int nextPageNo;//下一页 private int startPage;//开始页 private T t; public int getCurPageNo() { return curPageNo; } public void setCurPageNo(int curPageNo) { if(curPageNo<=0){ this.curPageNo=1; } if(curPageNo!=1&&curPageNo>0){ upPageNo=curPageNo-1; } nextPageNo=curPageNo+1; this.curPageNo = curPageNo; this.startPage=(curPageNo-1)*pageSize; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { if(pageCount%pageSize>0){ this.pageCount=pageCount/pageSize+1; }else { this.pageCount = pageCount/pageSize; } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getUpPageNo() { return upPageNo; } public void setUpPageNo(int upPageNo) { this.upPageNo = upPageNo; } public int getNextPageNo() { return nextPageNo; } public void setNextPageNo(int nextPageNo) { this.nextPageNo = nextPageNo; } public int getStartPage() { return startPage; } public void setStartPage(int startPage) { this.startPage = startPage; }} |
package com.chinatower.product.core.util;import lombok.Data;import java.util.ArrayList;import java.util.List;/** * @author zhuxiaomeng * @date 2018/11/22. * @email [email protected] * <p> * 博客管理current user message */@Datapublic class Principal { private String userId; private String userName; private List<String> roles = new ArrayList<>(); private String photo;} |
package com.chinatower.product.core.util;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;import lombok.Data;import java.io.Serializable;import java.util.List;import java.util.Map;/** * @author zhuxiaomeng * @date 2017/12/19. * @email [email protected] * 查询返回json格式依照ui默认属性名称 */@Datapublic class ReType implements Serializable{ /**状态*/ public int code=0; /**状态信息*/ public String msg=""; /**数据总数*/ public long count; /**页码*/ public long pageNum; public List<?> data; public ReType() { } public ReType(long count, List<?> data) { this.count = count; this.data = data; } public ReType(long count,long pageNum, List<?> data) { this.count = count; this.pageNum=pageNum; this.data = data; } /** * 动态添加属性 map 用法可以参考 activiti 模块中 com.len.JsonTest 测试类中用法 * @param count * @param data * @param map * @param node 绑定节点字符串 这样可以更加灵活 * @return */ public static String jsonStrng(long count,List<?> data,Map<String, Map<String,Object>> map,String node){ JSONArray jsonArray=JSONArray.parseArray(JSON.toJSONString(data)); JSONObject object=new JSONObject(); for(int i=0;i<jsonArray.size();i++){ JSONObject jsonData = (JSONObject) jsonArray.get(i); jsonData.putAll(map.get(jsonData.get(node))); } object.put("count",count); object.put("data",jsonArray); object.put("code",0); object.put("msg",""); return object.toJSONString(); }} |
package com.chinatower.product.core.util;import com.google.common.base.MoreObjects;import java.io.Serializable;/** * @author lzt */public class SmsResponse<T> implements Serializable { private static final long serialVersionUID = -750644833749014618L; private boolean success; private T result; private String error; public SmsResponse() { } public boolean isSuccess() { return this.success; } public void setSuccess(boolean success) { this.success = success; } public T getResult() { return this.result; } public void setResult(T result) { this.success = true; this.result = result; } public String getError() { return this.error; } public void setError(String error) { this.success = false; this.error = error; } public String toString() { return MoreObjects.toStringHelper(this).add("success", this.success).add("result", this.result) .add("error", this.error).omitNullValues().toString(); }} |
package com.chinatower.product.core.util;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/** * @author zhuxiaomeng * @date 2018/1/5. * @email [email protected] * 参照一些案例在此对 在此对网上分享者说声感谢 by:zxm * 通过封装applicationContext上线文 * 获取 spring bean对象 bean启动时候 已经被打印出,可直接根据name、class、name class获取 * * 很多地方能用得到 */@Componentpublic class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; } } public static ApplicationContext getApplicationContext() { return applicationContext; } /*** * 根据name获取bean * @param name * @param <T> * @return */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) getApplicationContext().getBean(name); } public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } } |
package com.chinatower.product.core.util;import java.util.ArrayList;import java.util.List;import lombok.Getter;import lombok.Setter;/** * @author zhuxiaomeng * @date 2017/12/27. * @email [email protected] * * 树形工具类 */@Getter@Setterpublic class TreeUtil { /**级数*/ private int layer; private String id; private String name; private String pId; /**是否开启 默认开启*/ private boolean open=true; /**是否选择 checkbox状态可用 默认未选中*/ private boolean checked=false; private List<TreeUtil> children=new ArrayList<>();} |
package com.chinatower.product.core.util;import com.chinatower.product.core.exception.MyException;import lombok.Data;import lombok.Getter;import lombok.Setter;import org.apache.commons.io.FileUtils;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;import java.util.Arrays;import java.util.UUID;/** * Created by meng on 2018/5/8. * 文件上传工具类 */@Getter@Setter@ConfigurationProperties@Componentpublic class UploadUtil { /** * 按照当日创建文件夹 */ @Value("${lenosp.isDayType}") private boolean isDayType; /** * 自定义文件路径 */ @Value("${lenosp.uploadPath}") private String uploadPath; @Value("${lenosp.imagePath}") private String imagePath; public static final String IMAGE_SUFFIX = "bmp,jpg,png,gif,jpeg"; public UploadUtil() { } public String upload(MultipartFile multipartFile) { if (isNull(multipartFile)) { throw new MyException("上传数据/地址获取异常"); } LoadType loadType = fileNameStyle(multipartFile); try { FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), loadType.getCurrentFile()); } catch (IOException e) { e.printStackTrace(); } return loadType.getFileName(); } /** * 格式化文件名 默认采用UUID * * @return */ public LoadType fileNameStyle(MultipartFile multipartFile) { String curr = multipartFile.getOriginalFilename(); int suffixLen = curr.lastIndexOf("."); boolean flag=false; int index=-1; if("blob".equals(curr)){ flag=true; index=0; curr=UUID.randomUUID() + ".png"; } else if (suffixLen == -1) { throw new MyException("文件获取异常"); } if(!flag){ String suffix = curr.substring(suffixLen, curr.length()); index = Arrays.binarySearch(IMAGE_SUFFIX.split(","), suffix.replace(".", "")); curr = UUID.randomUUID() + suffix; } LoadType loadType = new LoadType(); loadType.setFileName(curr); //image 情况 curr = StringUtils.isEmpty(imagePath) || index == -1 ? uploadPath + File.separator + curr : imagePath + File.separator + curr; loadType.setCurrentFile(new File(curr)); return loadType; } private boolean isNull(MultipartFile multipartFile) { if (null != multipartFile) { return false; } return true; }}@Dataclass LoadType { private String fileName; private File currentFile;} |
package com.chinatower.product.core.util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Arrays;import java.util.Random;import javax.imageio.ImageIO;public class VerifyCodeUtils { //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; private static Random random = new Random(); /** * 验证码对象 * @author zhou-baicheng * */ public static class Verify{ private String code;//如 1 + 2 private Integer value;//如 3 public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } } /** * 使用系统默认字符源生成验证码 * @param verifySize 验证码长度 * @return */ public static Verify generateVerify(){ int number1 = new Random().nextInt(10) + 1;; int number2 = new Random().nextInt(10) + 1;; Verify entity = new Verify(); entity.setCode(number1 + " x " + number2); entity.setValue(number1 + number2); return entity; } /** * 使用系统默认字符源生成验证码 * @param verifySize 验证码长度 * @return */ public static String generateVerifyCode(int verifySize){ return generateVerifyCode(verifySize, VERIFY_CODES); } /** * 使用指定源生成验证码 * @param verifySize 验证码长度 * @param sources 验证码字符源 * @return */ public static String generateVerifyCode(int verifySize, String sources){ if(sources == null || sources.length() == 0){ sources = VERIFY_CODES; } int codesLen = sources.length(); Random rand = new Random(System.currentTimeMillis()); StringBuilder verifyCode = new StringBuilder(verifySize); for(int i = 0; i < verifySize; i++){ verifyCode.append(sources.charAt(rand.nextInt(codesLen-1))); } return verifyCode.toString(); } /** * 生成随机验证码文件,并返回验证码值 * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{ String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, outputFile, verifyCode); return verifyCode; } /** * 输出随机验证码图片流,并返回验证码值 * @param w * @param h * @param os * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{ String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, os, verifyCode); return verifyCode; } /** * 生成指定验证码图像文件 * @param w * @param h * @param outputFile * @param code * @throws IOException */ public static void outputImage(int w, int h, File outputFile, String code) throws IOException{ if(outputFile == null){ return; } File dir = outputFile.getParentFile(); if(!dir.exists()){ dir.mkdirs(); } try{ outputFile.createNewFile(); FileOutputStream fos = new FileOutputStream(outputFile); outputImage(w, h, fos, code); fos.close(); } catch(IOException e){ throw e; } } /** * 输出指定验证码图片流 * @param w * @param h * @param os * @param code * @throws IOException */ public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{ int verifySize = code.length(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Random rand = new Random(); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); Color[] colors = new Color[5]; Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW }; float[] fractions = new float[colors.length]; for(int i = 0; i < colors.length; i++){ colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; fractions[i] = rand.nextFloat(); } Arrays.sort(fractions); g2.setColor(Color.GRAY);// 设置边框色 g2.fillRect(0, 0, w, h); Color c = getRandColor(200, 250); g2.setColor(c);// 设置背景色 g2.fillRect(0, 2, w, h-4); //绘制干扰线 Random random = new Random(); g2.setColor(getRandColor(160, 200));// 设置线条的颜色 for (int i = 0; i < 20; i++) { int x = random.nextInt(w - 1); int y = random.nextInt(h - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g2.drawLine(x, y, x + xl + 40, y + yl + 20); } // 添加噪点 float yawpRate = 0.05f;// 噪声率 int area = (int) (yawpRate * w * h); for (int i = 0; i < area; i++) { int x = random.nextInt(w); int y = random.nextInt(h); int rgb = getRandomIntColor(); image.setRGB(x, y, rgb); } shear(g2, w, h, c);// 使图片扭曲 g2.setColor(getRandColor(100, 160)); int fontSize = h-4; Font font = new Font("Algerian", Font.ITALIC, fontSize); g2.setFont(font); char[] chars = code.toCharArray(); for(int i = 0; i < verifySize; i++){ AffineTransform affine = new AffineTransform(); affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2); g2.setTransform(affine); g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10); } g2.dispose(); ImageIO.write(image, "jpg", os); } private static Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private static int getRandomIntColor() { int[] rgb = getRandomRgb(); int color = 0; for (int c : rgb) { color = color << 8; color = color | c; } return color; } private static int[] getRandomRgb() { int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { rgb[i] = random.nextInt(255); } return rgb; } private static void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private static void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private static void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public static void main(String[] args) throws IOException{ File dir = new File("F:/verifies"); int w = 200, h = 80; for(int i = 0; i < 50; i++){ String verifyCode = generateVerifyCode(4); File file = new File(dir, verifyCode + ".jpg"); outputImage(w, h, file, verifyCode); } } } |
package com.chinatower.product.core.validator.group;/** * * @ClassName: AddGroup * @Description: 新增数据 Group * @author: liutao * @date: 2018年3月16日 下午12:15:23 */public interface AddGroup {} |
package com.chinatower.product.core.validator.group;import javax.validation.GroupSequence;/** * * @ClassName: Group * @Description: 定义校验顺序,如果AddGroup组失败,则UpdateGroup组不会再校验 * @author: liutao * @date: 2018年3月16日 下午2:29:21 */@GroupSequence({AddGroup.class, UpdateGroup.class})public interface Group {} |
package com.chinatower.product.core.validator.group;/** * * @ClassName: UpdateGroup * @Description: 更新数据 Group * @author: liutao * @date: 2018年3月16日 下午2:29:34 */public interface UpdateGroup {} |
package com.chinatower.product.core.validator;import com.chinatower.product.core.exception.MyException;import java.util.Set;import javax.validation.ConstraintViolation;import javax.validation.Validation;import javax.validation.Validator;/** * * @ClassName: ValidatorUtils * @Description: hibernate-validator校验工具类 * @author: liutao * @date: 2018年3月16日 上午11:56:34 */public class ValidatorUtils { private static Validator validator; static { validator = Validation.buildDefaultValidatorFactory().getValidator(); } /** * 校验对象 * @param object 待校验对象 * @param groups 待校验的组 * @throws MyException 校验不通过,则报BusinessException异常 */ public static void validateEntity(Object object, Class<?>... groups) throws MyException { Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); if (!constraintViolations.isEmpty()) { ConstraintViolation<Object> constraint = (ConstraintViolation<Object>)constraintViolations.iterator().next(); throw new MyException(constraint.getMessage()); } }} |
package com.chinatower.product.sys.core.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * @author zhuxiaomeng * @date 2017/12/28. * @email [email protected] * <p> * 记录日志 */@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD})@Documented@Inheritedpublic @interface Log { public enum LOG_TYPE {ADD, UPDATE, DEL, SELECT, ATHOR} ; /** * 内容 */ String desc(); /** * 类型 curd */ LOG_TYPE type() default LOG_TYPE.ATHOR;} |
package com.chinatower.product.sys.core.annotation;import com.alibaba.fastjson.JSON;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.sys.core.shiro.Principal;import com.chinatower.product.sys.entity.SysLog;import com.chinatower.product.core.util.IpUtil;import java.lang.reflect.Method;import java.util.Date;import javax.servlet.http.HttpServletRequest;import com.chinatower.product.sys.mapper.SysLogMapper;import org.apache.shiro.UnavailableSecurityManagerException;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.AfterThrowing;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Pointcut;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.ui.Model;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;/** *@author Mr.liang *@create 创建于 2019/5/31 16:42 *@desc 为增删改添加监控 * @Vesion 1.0 **/@Aspect@Componentpublic class LogAspect { @Autowired private SysLogMapper logMapper; @Pointcut("@annotation(com.chinatower.product.sys.core.annotation.Log)") private void pointcut() { } @After("pointcut()") public void insertLogSuccess(JoinPoint jp) { addLog(jp, getDesc(jp)); } private void addLog(JoinPoint jp, String text) { Log.LOG_TYPE type = getType(jp); SysLog log = new SysLog(); RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); //一些系统监控 if (requestAttributes != null) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String ip = IpUtil.getIp(request); log.setIp(ip); } log.setCreateTime(new Date()); log.setType(type.toString()); log.setText(text); Object[] obj = jp.getArgs(); StringBuffer buffer = new StringBuffer(); if (obj != null) { for (int i = 0; i < obj.length; i++) { buffer.append("[参数" + (i + 1) + ":"); Object o = obj[i]; if(o instanceof Model){ continue; } String parameter=null; try { parameter=JSON.toJSONString(o); }catch (Exception e){ continue; } buffer.append(parameter); buffer.append("]"); } } log.setParam(buffer.toString()); try { CurrentUser currentUser = Principal.getCurrentUse(); log.setUserName(currentUser.getUsername()); } catch (UnavailableSecurityManagerException e) { } logMapper.insert(log); } /** * 记录异常 * * @param joinPoint * @param e */ @AfterThrowing(value = "pointcut()", throwing = "e") public void afterException(JoinPoint joinPoint, Exception e) { System.out.print("-----------afterException:" + e.getMessage()); addLog(joinPoint, getDesc(joinPoint) + e.getMessage()); } private String getDesc(JoinPoint joinPoint) { MethodSignature methodName = (MethodSignature) joinPoint.getSignature(); Method method = methodName.getMethod(); return method.getAnnotation(Log.class).desc(); } private Log.LOG_TYPE getType(JoinPoint joinPoint) { MethodSignature methodName = (MethodSignature) joinPoint.getSignature(); Method method = methodName.getMethod(); return method.getAnnotation(Log.class).type(); }} |
package com.chinatower.product.sys.core.annotation;import com.alibaba.fastjson.JSONObject;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.exception.MyException;import com.chinatower.product.sys.entity.UserDataDto;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.sys.mapper.SysUserMapper;import com.chinatower.product.sys.service.RoleUriService;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.shiro.SecurityUtils;import org.apache.shiro.subject.Subject;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;@Component@Aspect@Slf4jpublic class UserDataAspect { @Autowired private RoleUriService roleUriService; @Autowired private SysUserMapper userMapper; @Autowired private HttpServletRequest request; /** * 设置当前用户数据权限 * 管理员,运营者等管理角色应查看到所有人数据 * 注意此注解必须要登录才能使用 */ @Around("@annotation(com.chinatower.product.core.annotation.UserData)") public Object getUserDataPermission(ProceedingJoinPoint point) throws Throwable { Object[] args = point.getArgs(); Integer flag = null; String servletPath = null; String username = null; try { //获取请求地址 servletPath = request.getServletPath(); //查询当前登录人 Subject subject = SecurityUtils.getSubject(); CurrentUser currentUser = (CurrentUser) subject.getPrincipal(); username = currentUser.getUsername(); log.info("注解UserData获取当前登录人为:{},调用的方法是:{},请求接口地址是:{},参数为:{}", username, point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName(), servletPath, JSONObject.toJSONString(args)); //获取可以获得所有数据权限的用户类型 flag = roleUriService.roleIsExitsUri(servletPath, username); }catch (Exception e) { log.error("注解UserData逻辑发生异常:{}",e); Object proceed = point.proceed(args); return proceed; } if(flag == null || flag < 1){ SysUser sysUser = userMapper.login(username); if (null != sysUser) { String sysCode = sysUser.getSysCode(); if(StringUtils.isBlank(sysCode)){ throw new MyException("请联系管理员完善用户信息"); } UserDataDto params =(UserDataDto) args[0]; params.setSysCode(sysCode); params.setUsername(username); log.info("注解UserData获取当前登录人为:{},调用的方法是:{},请求接口地址是:{},增加参数后参数为:{}", username, point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName(),servletPath,JSONObject.toJSONString(args)); }else{ throw new MyException("暂无此用户"); } } Object proceed = point.proceed(args); return proceed; }} |
package com.chinatower.product.sys.core.BootListener;import com.chinatower.product.sys.core.quartz.JobTask;import com.chinatower.product.sys.entity.SysJob;import com.chinatower.product.core.util.SpringUtil;import java.util.List;import com.chinatower.product.sys.service.JobService;import com.chinatower.product.sys.service.RoleService;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;/** * @author zhuxiaomeng * @date 2018/1/6. * @email [email protected] * <p> * 启动数据库中已经设定为 启动状态(status:true)的任务 项目启动时init */@Configuration@Slf4jpublic class DataSourceJobThread extends Thread { @Autowired RoleService roleService; @Autowired JobService jobService; @Override public void run() { try { Thread.sleep(1000); log.info("---------线程启动---------"); JobTask jobTask = SpringUtil.getBean("jobTask"); SysJob job = new SysJob(); job.setStatus(true); List<SysJob> jobList = jobService.selectListByPage(job); //开启任务 jobList.forEach(jobs -> { log.info("---任务[" + jobs.getId() + "]系统 init--开始启动---------"); jobTask.startJob(jobs); } ); if (jobList.size() == 0) { log.info("---数据库暂无启动的任务---------"); } else System.out.println("---任务启动完毕---------"); } catch (InterruptedException e) { e.printStackTrace(); } }} |
package com.chinatower.product.sys.core.BootListener;import lombok.extern.slf4j.Slf4j;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Component;/** * @author zhuxiaomeng * @date 2018/1/6. * @email [email protected] * <p> * 通过监听,开辟线程,执行定时任务 当然 也可以执行其他 */@Component@Slf4jpublic class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { log.info("-------------bean初始化完毕-------------"); /** * 通过线程开启数据库中已经开启的定时任务 灵感来自spring * spring boot继续执行 mythread开辟线程,延迟后执行 */ DataSourceJobThread myThread = (DataSourceJobThread) event.getApplicationContext().getBean( "dataSourceJobThread"); }} |
package com.chinatower.product.sys.core.BootListener;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.springframework.stereotype.Component;/** * @author zhuxiaomeng * @date 2018/1/6. * @email [email protected] */@Componentpublic class MyServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("-------contextInitialized-----------"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("------------contextDestroyed-------------"); }} |
package com.chinatower.product.sys.core.feign.model;import lombok.Data;/** * @author lzt */@Datapublic class CacheModel { private String key; private Object value; private long expireTime;} |
package com.chinatower.product.sys.core.feign.model;import lombok.Data;/** * @author lzt */@Datapublic class CacheQueryModel { private String key;} |
package com.chinatower.product.sys.core.feign.model;import lombok.Data;/** * @author lzt */@Datapublic class CacheSaveOrUpdateModel { private String key; private Object value;} |
package com.chinatower.product.sys.core.feign.model;import lombok.Data;import lombok.EqualsAndHashCode;import lombok.ToString;import java.io.Serializable;import java.util.HashMap;import java.util.Map;@EqualsAndHashCode(callSuper = true)@Data@ToString(callSuper = true)public class HashRedisModel extends RedisModel implements Serializable { private Map<String, String> values= new HashMap<>(); private String field; private Integer value;} |
package com.chinatower.product.sys.core.feign.model;import lombok.Getter;import lombok.ToString;/** * @author lzt */@Getter@ToStringpublic enum RedisEnum { DEFAULT(-1), SHARE(-1), ZUJIAN(0); private Integer database; RedisEnum(Integer database) { this.database = database; }} |
package com.chinatower.product.sys.core.feign.model;import lombok.Data;/** * @author lzt */@Datapublic class RedisModel { private String system = RedisEnum.DEFAULT.name(); private String key; /** * 定时使用 */ private Long time; /** * 检索使用 */ private String pattern="";} |
package com.chinatower.product.sys.core.feign.model;import lombok.Data;import lombok.EqualsAndHashCode;import lombok.ToString;import java.io.Serializable;/** * @author lzt */@EqualsAndHashCode(callSuper = true)@Data@ToString(callSuper = true)public class StringRedisModel extends RedisModel implements Serializable { private String value;} |
package com.chinatower.product.sys.core.filter;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import com.chinatower.product.sys.service.MenuService;import com.chinatower.product.sys.service.SysUserService;import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;import org.springframework.beans.factory.annotation.Autowired;/** * @author zhuxiaomeng * @date 2017/12/13. * @email [email protected] * 自定义拦截器 暂时不用 */public class CustomAdvicFilter extends FormAuthenticationFilter { @Autowired private SysUserService userService; @Autowired private MenuService menuService; @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { return true; }} |
package com.chinatower.product.sys.core.filter;import com.chinatower.product.core.base.CurrentUser;import java.io.IOException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import com.chinatower.product.sys.service.MenuService;import com.chinatower.product.sys.service.SysUserService;import lombok.extern.slf4j.Slf4j;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;import org.apache.shiro.web.filter.authz.AuthorizationFilter;import org.apache.shiro.web.util.WebUtils;import org.springframework.beans.factory.annotation.Autowired;/** * @author zhuxiaomeng * @date 2017/12/11. * @email [email protected] * 拦截器 校验用户是否已授权 未授权返回到登录界面 */@Slf4jpublic class PermissionFilter extends AuthorizationFilter { @Autowired private SysUserService userService; @Autowired private MenuService menuService; @Override protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception { String[] roles=(String[])o; Subject sub = getSubject(servletRequest, servletResponse); Session session= sub.getSession(); CurrentUser user= (CurrentUser) session.getAttribute("currentPrincipal"); log.info("user:{}",user); if(user==null) { return false; } return true; } @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException { saveRequest(request); WebUtils.issueRedirect(request, response, "/goLogin"); return false; }} |
package com.chinatower.product.sys.core.filter;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import org.apache.commons.lang3.StringUtils;import org.apache.shiro.web.filter.AccessControlFilter;/** * @author zhuxiaomeng * @date 2017/12/29. * @email [email protected] * * 验证码拦截 */public class VerfityCodeFilter extends AccessControlFilter{ /** 是否开启验证码验证 默认true*/ private boolean verfitiCode = true; /** 前台提交的验证码name*/ private String jcaptchaParam = "code"; /** 前端登录时flag=1, 不验证code */ private String flag = "flag"; /** 验证失败后setAttribute key*/ private String failureKeyAttribute = "shiroLoginFailure"; @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception { request.setAttribute("verfitiCode", verfitiCode);//暂时未用到非验证码 HttpServletRequest httpRequest = (HttpServletRequest)request; //2、判断验证码是否禁用 或不是表单提交 if (verfitiCode == false || !"post".equalsIgnoreCase(httpRequest.getMethod())) { return true; } Object code = getSubject(request, response).getSession().getAttribute("_code"); String storedCode=null; if(null!=code){ storedCode = code.toString(); } //表单提交,校验验证码的正确性 String currentCode = httpRequest.getParameter(jcaptchaParam); String loginFlag = httpRequest.getParameter(flag); return StringUtils.equalsIgnoreCase(loginFlag, "1") || StringUtils.equalsIgnoreCase(storedCode, currentCode); } @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { servletRequest.setAttribute(failureKeyAttribute, "code.error"); return true; } public boolean isVerfitiCode() { return verfitiCode; } public void setVerfitiCode(boolean verfitiCode) { this.verfitiCode = verfitiCode; } public String getJcaptchaParam() { return jcaptchaParam; } public void setJcaptchaParam(String jcaptchaParam) { this.jcaptchaParam = jcaptchaParam; } public String getFailureKeyAttribute() { return failureKeyAttribute; } public void setFailureKeyAttribute(String failureKeyAttribute) { this.failureKeyAttribute = failureKeyAttribute; }} |
package com.chinatower.product.sys.core.filter;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.util.Arrays;import java.util.Random;import javax.imageio.ImageIO;public class VerifyCodeUtils{ //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; private static Random random = new Random(); /** * 验证码对象 * @author zhou-baicheng * */ public static class Verify{ private String code;//如 1 + 2 private Integer value;//如 3 public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } } /** * 使用系统默认字符源生成验证码 * @param * @return */ public static Verify generateVerify(){ int number1 = new Random().nextInt(10) + 1;; int number2 = new Random().nextInt(10) + 1;; Verify entity = new Verify(); entity.setCode(number1 + " x " + number2); entity.setValue(number1 + number2); return entity; } /** * 使用系统默认字符源生成验证码 * @param verifySize 验证码长度 * @return */ public static String generateVerifyCode(int verifySize){ return generateVerifyCode(verifySize, VERIFY_CODES); } /** * 使用指定源生成验证码 * @param verifySize 验证码长度 * @param sources 验证码字符源 * @return */ public static String generateVerifyCode(int verifySize, String sources){ if(sources == null || sources.length() == 0){ sources = VERIFY_CODES; } int codesLen = sources.length(); Random rand = new Random(System.currentTimeMillis()); StringBuilder verifyCode = new StringBuilder(verifySize); for(int i = 0; i < verifySize; i++){ verifyCode.append(sources.charAt(rand.nextInt(codesLen-1))); } return verifyCode.toString(); } /** * 生成随机验证码文件,并返回验证码值 * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{ String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, outputFile, verifyCode); return verifyCode; } /** * 输出随机验证码图片流,并返回验证码值 * @param w * @param h * @param os * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{ String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, os, verifyCode); return verifyCode; } /** * 生成指定验证码图像文件 * @param w * @param h * @param outputFile * @param code * @throws IOException */ public static void outputImage(int w, int h, File outputFile, String code) throws IOException{ if(outputFile == null){ return; } File dir = outputFile.getParentFile(); if(!dir.exists()){ dir.mkdirs(); } try{ outputFile.createNewFile(); FileOutputStream fos = new FileOutputStream(outputFile); outputImage(w, h, fos, code); fos.close(); } catch(IOException e){ throw e; } } /** * 输出指定验证码图片流 * @param w * @param h * @param os * @param code * @throws IOException */ public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{ int verifySize = code.length(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Random rand = new Random(); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); Color[] colors = new Color[5]; Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW }; float[] fractions = new float[colors.length]; for(int i = 0; i < colors.length; i++){ colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; fractions[i] = rand.nextFloat(); } Arrays.sort(fractions); g2.setColor(Color.GRAY);// 设置边框色 g2.fillRect(0, 0, w, h); Color c = getRandColor(200, 250); g2.setColor(c);// 设置背景色 g2.fillRect(0, 2, w, h-4); //绘制干扰线 Random random = new Random(); g2.setColor(getRandColor(160, 200));// 设置线条的颜色 for (int i = 0; i < 20; i++) { int x = random.nextInt(w - 1); int y = random.nextInt(h - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g2.drawLine(x, y, x + xl + 40, y + yl + 20); } // 添加噪点 float yawpRate = 0.05f;// 噪声率 int area = (int) (yawpRate * w * h); for (int i = 0; i < area; i++) { int x = random.nextInt(w); int y = random.nextInt(h); int rgb = getRandomIntColor(); image.setRGB(x, y, rgb); } shear(g2, w, h, c);// 使图片扭曲 g2.setColor(getRandColor(100, 160)); int fontSize = h-4; Font font = new Font("Algerian", Font.ITALIC, fontSize); g2.setFont(font); char[] chars = code.toCharArray(); for(int i = 0; i < verifySize; i++){ AffineTransform affine = new AffineTransform(); affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2); g2.setTransform(affine); g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10); } g2.dispose(); ImageIO.write(image, "jpg", os); } private static Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private static int getRandomIntColor() { int[] rgb = getRandomRgb(); int color = 0; for (int c : rgb) { color = color << 8; color = color | c; } return color; } private static int[] getRandomRgb() { int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { rgb[i] = random.nextInt(255); } return rgb; } private static void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private static void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private static void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public static void main(String[] args) throws IOException{ File dir = new File("F:/verifies"); int w = 200, h = 80; for(int i = 0; i < 50; i++){ String verifyCode = generateVerifyCode(4); File file = new File(dir, verifyCode + ".jpg"); outputImage(w, h, file, verifyCode); } } } |
package com.chinatower.product.sys.core.quartz.CustomQuartz;import java.io.*;import com.chinatower.product.sys.core.annotation.Log;import lombok.extern.slf4j.Slf4j;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/** * @author zhuxiaomeng * @date 2018/1/29. * @email [email protected] * <p> * 定时还原数据库数据 */@Component@Slf4jpublic class DataSchdule { // @Scheduled(cron = "0 0/5 * * * ? ") @Log(type = Log.LOG_TYPE.UPDATE,desc = "定时还原数据库") public static void restData() throws IOException, InterruptedException { // SQL文件路径 try { Runtime rt = Runtime.getRuntime(); String sqlPath = "G:\\os\\sql\\lenos_test.sql"; Process process = rt .exec("D:\\java\\mysql-5.7.21-winx64\\mysql-5.7.21-winx64\\bin\\mysql.exe -hlocalhost -uroot -ppassword --default-character-set=utf8 " + "lenos_test"); OutputStream outputStream = process.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(sqlPath), "utf-8")); String str = null; StringBuffer sb = new StringBuffer(); while ((str = br.readLine()) != null) { sb.append(str + "\r\n"); } str = sb.toString(); OutputStreamWriter writer = new OutputStreamWriter(outputStream, "utf-8"); writer.write(str); writer.flush(); outputStream.close(); br.close(); writer.close(); log.info("数据库还原成功"); } catch (IOException e) { log.error("数据库还原失败"); e.printStackTrace(); } }} |
package com.chinatower.product.sys.core.quartz.CustomQuartz;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.core.util.SpringUtil;import java.text.SimpleDateFormat;import java.util.List;import com.chinatower.product.sys.service.SysUserService;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;/** * @author zhuxiaomeng * @date 2018/1/7. * @email [email protected] * * 定时 */public class JobDemo1 implements Job{ @Autowired SysUserService sys; @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("JobDemo1:启动任务======================="); run(); System.out.println("JobDemo1:下次执行时间====="+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .format(context.getNextFireTime())+"=============="); } public void run(){ ApplicationContext applicationContext= SpringUtil.getApplicationContext(); //可以 获取 //SysUserService sys=SpringUtil.getBean(SysUserServiceImpl.class); List<SysUser> userList=sys.selectListByPage(new SysUser()); System.out.println(userList.get(0).getUsername());; System.out.println("JobDemo1:执行完毕======================="); }} |
package com.chinatower.product.sys.core.quartz.CustomQuartz;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.core.util.SpringUtil;import java.text.SimpleDateFormat;import java.util.List;import com.chinatower.product.sys.service.SysUserService;import com.chinatower.product.sys.service.impl.SysUserServiceImpl;import lombok.extern.slf4j.Slf4j;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.context.ApplicationContext;/** * @author zhuxiaomeng * @date 2018/1/7. * @email [email protected] * * 定时测试类 */@Slf4jpublic class JobDemo2 implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("JobDemo2:启动任务======================="); run(); System.out.println("JobDemo2:下次执行时间====="+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .format(context.getNextFireTime())+"=============="); } public void run(){ ApplicationContext applicationContext= SpringUtil.getApplicationContext(); SysUserService sys=SpringUtil.getBean(SysUserServiceImpl.class); List<SysUser> userList=sys.selectListByPage(new SysUser()); log.info(userList.get(0).getUsername()); log.info("JobDemo2:执行完毕======================="); }} |
package com.chinatower.product.sys.core.quartz.CustomQuartz;import com.chinatower.product.core.util.SpringUtil;import java.text.SimpleDateFormat;import java.util.List;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.sys.service.SysUserService;import com.chinatower.product.sys.service.impl.SysUserServiceImpl;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.context.ApplicationContext;/** * @author zhuxiaomeng * @date 2018/1/7. * @email [email protected] * * 定时测试类 */public class JobDemo3 implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("JobDemo3:启动任务======================="); run(); System.out.println("JobDemo3:下次执行时间====="+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .format(context.getNextFireTime())+"=============="); } public void run(){ ApplicationContext applicationContext= SpringUtil.getApplicationContext(); SysUserService sys=SpringUtil.getBean(SysUserServiceImpl.class); List<SysUser> userList=sys.selectListByPage(new SysUser()); System.out.println(userList.get(0).getUsername());; System.out.println("JobDemo3:执行完毕======================="); }} |
package com.chinatower.product.sys.core.quartz.CustomQuartz;import com.chinatower.product.core.util.SpringUtil;import java.text.SimpleDateFormat;import java.util.List;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.sys.service.SysUserService;import com.chinatower.product.sys.service.impl.SysUserServiceImpl;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.context.ApplicationContext;/** * @author zhuxiaomeng * @date 2018/1/7. * @email [email protected] * * 定时测试类 */public class JobDemo4 implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("JobDemo4:启动任务======================="); run(); System.out.println("JobDemo4:下次执行时间====="+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .format(context.getNextFireTime())+"=============="); } public void run(){ ApplicationContext applicationContext= SpringUtil.getApplicationContext(); SysUserService sys=SpringUtil.getBean(SysUserServiceImpl.class); List<SysUser> userList=sys.selectListByPage(new SysUser()); System.out.println(userList.get(0).getUsername());; System.out.println("JobDemo4:执行完毕======================="); }} |
package com.chinatower.product.sys.core.quartz.CustomQuartz;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.core.util.SpringUtil;import java.text.SimpleDateFormat;import java.util.List;import com.chinatower.product.sys.service.SysUserService;import com.chinatower.product.sys.service.impl.SysUserServiceImpl;import org.quartz.Job;import org.quartz.JobExecutionContext;import org.quartz.JobExecutionException;import org.springframework.context.ApplicationContext;/** * @author zhuxiaomeng * @date 2018/1/7. * @email [email protected] * * 定时测试类 */public class JobDemo5 implements Job{ @Override public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("JobDemo5:启动任务======================="); run(); System.out.println("JobDemo5:下次执行时间====="+ new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .format(context.getNextFireTime())+"=============="); } public void run(){ ApplicationContext applicationContext= SpringUtil.getApplicationContext(); SysUserService sys=SpringUtil.getBean(SysUserServiceImpl.class); List<SysUser> userList=sys.selectListByPage(new SysUser()); System.out.println(userList.get(0).getUsername());; System.out.println("JobDemo5:执行完毕======================="); }} |
package com.chinatower.product.sys.core.quartz;import com.chinatower.product.sys.core.annotation.Log;import com.chinatower.product.sys.entity.SysJob;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.time.DateFormatUtils;import org.quartz.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.quartz.SchedulerFactoryBean;import org.springframework.stereotype.Service;import java.util.Date;import java.util.HashSet;/** * @author zhuxiaomeng * @date 2018/1/5. * @email [email protected] * <p> * 定时任务类 增删改 可参考api:http://www.quartz-scheduler.org/api/2.2.1/ * <p> * 任务名称 默认为 SysJob 类 id */@Service@Slf4jpublic class JobTask { @Autowired SchedulerFactoryBean schedulerFactoryBean; /** * true 存在 false 不存在 * * @param * @return */ public boolean checkJob(SysJob job) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(job.getId(), Scheduler.DEFAULT_GROUP); try { if (scheduler.checkExists(triggerKey)) { return true; } } catch (SchedulerException e) { e.printStackTrace(); } return false; } /** * 开启 */ @Log(desc = "开启定时任务") public boolean startJob(SysJob job) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); try { Class clazz = Class.forName(job.getClazzPath()); JobDetail jobDetail = JobBuilder.newJob(clazz).build(); // 触发器 TriggerKey triggerKey = TriggerKey.triggerKey(job.getId(), Scheduler.DEFAULT_GROUP); CronTrigger trigger = TriggerBuilder.newTrigger() .withIdentity(triggerKey) .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron())).build(); scheduler.scheduleJob(jobDetail, trigger); // 启动 if (!scheduler.isShutdown()) { scheduler.start(); log.info("---任务[" + triggerKey.getName() + "]启动成功-------"); return true; } else { log.info("---任务[" + triggerKey.getName() + "]已经运行,请勿再次启动-------"); } } catch (Exception e) { throw new RuntimeException(e); } return false; } /** * 更新 */ @Log(desc = "更新定时任务", type = Log.LOG_TYPE.UPDATE) public boolean updateJob(SysJob job) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); String createTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); TriggerKey triggerKey = TriggerKey.triggerKey(job.getId(), Scheduler.DEFAULT_GROUP); try { if (scheduler.checkExists(triggerKey)) { return false; } JobKey jobKey = JobKey.jobKey(job.getId(), Scheduler.DEFAULT_GROUP); CronScheduleBuilder schedBuilder = CronScheduleBuilder.cronSchedule(job.getCron()) .withMisfireHandlingInstructionDoNothing(); CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey) .withDescription(createTime).withSchedule(schedBuilder).build(); JobDetail jobDetail = scheduler.getJobDetail(jobKey); HashSet<Trigger> triggerSet = new HashSet<>(); triggerSet.add(trigger); scheduler.scheduleJob(jobDetail, triggerSet, true); log.info("---任务[" + triggerKey.getName() + "]更新成功-------"); return true; } catch (SchedulerException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * 删除 */ @Log(desc = "删除定时任务", type = Log.LOG_TYPE.DEL) public boolean remove(SysJob job) { Scheduler scheduler = schedulerFactoryBean.getScheduler(); TriggerKey triggerKey = TriggerKey.triggerKey(job.getId(), Scheduler.DEFAULT_GROUP); try { if (checkJob(job)) { scheduler.pauseTrigger(triggerKey); scheduler.unscheduleJob(triggerKey); scheduler.deleteJob(JobKey.jobKey(job.getId(), Scheduler.DEFAULT_GROUP)); log.info("---任务[" + triggerKey.getName() + "]删除成功-------"); return true; } } catch (SchedulerException e) { e.printStackTrace(); } return false; }} |
package com.chinatower.product.sys.core.quartz;import org.quartz.spi.TriggerFiredBundle;import org.springframework.beans.BeansException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.config.AutowireCapableBeanFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.scheduling.quartz.AdaptableJobFactory;import org.springframework.stereotype.Component;@Componentpublic class MyJobFactory extends AdaptableJobFactory{ @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object job = super.createJobInstance(bundle); capableBeanFactory.autowireBean(job); return job; }} |
package com.chinatower.product.sys.core.quartz;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.ClassPathResource;import org.springframework.scheduling.quartz.SchedulerFactoryBean;@Configurationpublic class MySchedulerListener { @Autowired MyJobFactory myJobFactory; @Bean(name ="schedulerFactoryBean") public SchedulerFactoryBean schedulerFactory() { SchedulerFactoryBean bean = new SchedulerFactoryBean(); bean.setJobFactory(myJobFactory); bean.setConfigLocation(new ClassPathResource("quartz.properties")); return bean; } } |
package com.chinatower.product.sys.core.sharding;import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;import java.sql.Timestamp;import java.util.Calendar;import java.util.Collection;import java.util.Date;/*精确分片算法:针对创建时间,制定单库分表规则使用多个逻辑表,只要分片规则一致 */public class MyPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> { @Override public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) { //遍历所有物理表名 for (String tableName : collection) { String value = preciseShardingValue.getValue(); String substring = value.substring(0, value.lastIndexOf("_")); if (tableName.endsWith(substring)) { return tableName; } } return ""; }} |
package com.chinatower.product.sys.core.sharding;import com.google.common.collect.Range;import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;import java.util.Collection;import java.util.LinkedHashSet;/* */public class MyRangeShardingAlgorithm implements RangeShardingAlgorithm<String> { @Override public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) { Range<String> valueRange = rangeShardingValue.getValueRange(); LinkedHashSet<String> result = new LinkedHashSet<String>(); String lowerEndpoint = valueRange.lowerEndpoint(); String upperEndpoint = valueRange.upperEndpoint(); Integer lowerYear = Integer.valueOf(lowerEndpoint.substring(0,lowerEndpoint.indexOf("_"))); Integer lowerMonth = Integer.valueOf(lowerEndpoint.substring(lowerEndpoint.indexOf("_")+1, lowerEndpoint.lastIndexOf("_"))); Integer upperYear = Integer.valueOf(upperEndpoint.substring(0,upperEndpoint.indexOf("_"))); Integer upperMonth = Integer.valueOf(upperEndpoint.substring(upperEndpoint.indexOf("_")+1, upperEndpoint.lastIndexOf("_"))); for (String tableName : collection) { Integer tableYear = Integer.valueOf(tableName.substring(tableName.indexOf("_")+1,tableName.lastIndexOf("_")).substring(tableName.substring(tableName.indexOf("_")+1,tableName.lastIndexOf("_")).indexOf("_")+1)); Integer tableMonth = Integer.valueOf(tableName.substring(tableName.lastIndexOf("_")+1)); if (tableYear>=lowerYear&&tableMonth>=lowerMonth&&tableYear<=upperYear&&tableMonth<=upperMonth) result.add(tableName); } return result; }} |
package com.chinatower.product.sys.core.shiro;import com.chinatower.product.core.base.CurrentMenu;import com.chinatower.product.core.base.CurrentRole;import com.chinatower.product.core.base.CurrentUser;import com.chinatower.product.core.util.BeanUtil;import com.chinatower.product.core.util.JWTUtil;import com.chinatower.product.sys.entity.SysUser;import com.chinatower.product.sys.service.SysUserService;import org.apache.commons.lang3.StringUtils;import org.apache.shiro.authc.*;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.authz.SimpleAuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.apache.shiro.util.ByteSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.ArrayList;import java.util.List;import java.util.Set;/** * @author zhuxiaomeng * @date 2017/12/4. * @email [email protected] */@Servicepublic class LoginRealm extends AuthorizingRealm { @Autowired private SysUserService userService; /** * 获取授权 * * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); CurrentUser user = (CurrentUser) principalCollection.getPrimaryPrincipal(); Set<String> realmNames = principalCollection.getRealmNames(); List<String> realmNameList = new ArrayList<>(realmNames); if ("BlogLogin".equals(realmNameList.get(0))) { String[] roles = JWTUtil.getRoles(user.getUsername()); assert roles != null; for (String role : roles) { info.addRole(role); } } else { //根据用户获取角色 根据角色获取所有按钮权限 CurrentUser cUser = (CurrentUser) Principal.getSession().getAttribute("currentPrincipal"); for (CurrentRole cRole : cUser.getCurrentRoleList()) { info.addRole(cRole.getId()); } for (CurrentMenu cMenu : cUser.getCurrentMenuList()) { if (!StringUtils.isEmpty(cMenu.getPermission())) { info.addStringPermission(cMenu.getPermission()); } } } return info; } /** * 获取认证 * * @param authenticationToken * @return * @throws AuthenticationException */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { String username = (String) authenticationToken.getPrincipal(); SysUser s = null; try { s = userService.login(username); } catch (Exception e) { e.printStackTrace(); } if (s == null) { throw new UnknownAccountException("账户密码不正确"); } CurrentUser user=new CurrentUser(); BeanUtil.copyNotNullBean(s,user); user.setPassword(null); userService.setMenuAndRoles(username); ByteSource byteSource = ByteSource.Util.bytes(username); return new SimpleAuthenticationInfo(user, s.getPassword(), byteSource, getName()); }} |
package com.chinatower.product.sys.core.shiro;import com.chinatower.product.core.base.CurrentUser;import org.apache.shiro.SecurityUtils;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;/** * @author zhuxiaomeng * @date 2017/12/28. * @email [email protected] */public class Principal { /** * 获取用户主题 * * @return */ public static Subject getSubject() { return SecurityUtils.getSubject(); } /** * 获取当前用户对象 * @return */ public static CurrentUser getPrincipal() { return (CurrentUser) getSubject().getPrincipal(); } /** * 当前session * @return */ public static Session getSession() { return getSubject().getSession(); } public static CurrentUser getCurrentUse() { return (CurrentUser) getSession().getAttribute("currentPrincipal"); }} |
package com.chinatower.product.sys.core.shiro;import java.util.concurrent.atomic.AtomicInteger;import lombok.extern.slf4j.Slf4j;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.ExcessiveAttemptsException;import org.apache.shiro.authc.credential.HashedCredentialsMatcher;import org.apache.shiro.cache.Cache;import org.apache.shiro.cache.CacheManager;import cn.hutool.core.util.StrUtil;/** * 验证器,增加了登录次数校验功能 * 限制尝试登陆次数,防止暴力破解 */@Slf4jpublic class RetryLimitCredentialsMatcher extends HashedCredentialsMatcher { private Cache<String, AtomicInteger> loginRetryCache; private int maxRetryCount = 5; public void setMaxRetryCount(int maxRetryCount) { this.maxRetryCount = maxRetryCount; } public RetryLimitCredentialsMatcher(){ } /** * * @param cacheManager * @param maxRetryCount 最大尝试次数 */ public RetryLimitCredentialsMatcher(CacheManager cacheManager,int maxRetryCount) { this.maxRetryCount = maxRetryCount; this.loginRetryCache = cacheManager.getCache("loginRetryCache"); } public RetryLimitCredentialsMatcher(CacheManager cacheManager){ this(cacheManager,5); } @Override public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { String username = (String) token.getPrincipal(); //retry count + 1 AtomicInteger retryCount = loginRetryCache.get(username) == null ? new AtomicInteger(0) : loginRetryCache.get(username); log.info("retryCount:{}, username:{}",retryCount,username); if (retryCount.incrementAndGet() > this.maxRetryCount) { log.warn("username: {} tried to login more than {} times in perid", username,this.maxRetryCount); throw new ExcessiveAttemptsException(StrUtil.format("username: {} tried to login more than {} times in perid", username,this.maxRetryCount)); } boolean matches = super.doCredentialsMatch(token, info); if (matches) { loginRetryCache.remove(username); } else { loginRetryCache.put(username, retryCount); log.info(String.valueOf(retryCount.get())); } return matches; }} |
package com.chinatower.product.sys.core.util;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;public class Aes7PaddingUtil { public static final String ALGORITHM = "AES"; public static final String ALGORITHM_MODE = "AES/CBC/NoPadding"; public static final String IV = "1234567890abcdef"; private Aes7PaddingUtil() { throw new IllegalStateException("Utility class"); } public static String encrypt(String data, String key) { try { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength += blockSize - plaintextLength % blockSize; } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(generateVirtualKey(key, 16).getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivspec = new IvParameterSpec("1234567890abcdef".getBytes(StandardCharsets.UTF_8)); cipher.init(1, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return (new BASE64Encoder()).encode(encrypted); } catch (Exception var10) { return null; } } public static String decrypt(String data, String key) { try { byte[] encrypted1 = (new BASE64Decoder()).decodeBuffer(data); Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(generateVirtualKey(key, 16).getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivspec = new IvParameterSpec("1234567890abcdef".getBytes(StandardCharsets.UTF_8)); cipher.init(2, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); return (new String(original)).trim(); } catch (Exception var7) { return null; } } private static String generateVirtualKey(String realKey, int length) { if (realKey.length() > length) { return realKey.substring(0, length); } else { int keyLen = realKey.length(); StringBuffer sb; for(sb = new StringBuffer(realKey); keyLen < length; keyLen = sb.toString().length()) { sb.append("0"); } return sb.toString(); } }} |
package com.chinatower.product.sys.core.util;import com.alibaba.fastjson.JSONObject;import lombok.extern.slf4j.Slf4j;import java.math.BigDecimal;import java.sql.*;import java.util.ArrayList;import java.util.Calendar;import java.util.List;/** * 利用jdbc备份mysql数据库--不用mysqldump * */@Slf4jpublic class AutoMysqlUtil { private String DRIVER = "com.mysql.jdbc.Driver"; private String URL = null; // "jdbc:mysql://182.xxx.xxx.xxx:3306/xd_love_dev?useUnicode=true&characterEncoding=utf8"; private String USERNAME = null;// "root"; private String PASSWORD = null;//"woaini"; private Connection conn = null; private String SQL = "SELECT * FROM ";// 数据库操作 /** * * <构造函数> * * @param url * 数据库链接地址 * @param userName * 数据库用户名 * @param password * 密码 */ public AutoMysqlUtil(String url, String userName, String password) { try { Class.forName(this.DRIVER); this.URL = url; this.USERNAME = userName; this.PASSWORD = password; } catch (ClassNotFoundException e) { e.printStackTrace(); System.err.println("can not load jdbc driver"); } } /** * 获取数据库连接 * * @return */ private Connection getConnection() { try { if (null == conn) { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } } catch (SQLException e) { e.printStackTrace(); System.err.println("get connection failure"); } return conn; } /** * 关闭数据库连接 * * @param conn */ private void closeConnection(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); System.err.println("close connection failure"); } } } /** * 获取数据库下的所有表名 */ private List<String> getTableNames() { List<String> tableNames = new ArrayList<String>(); Connection conn = getConnection(); ResultSet rs = null; try { Calendar rightNow = Calendar.getInstance(); Integer year = rightNow.get(Calendar.YEAR); Integer month = rightNow.get(Calendar.MONTH)+1; // // 获取数据库的元数据 DatabaseMetaData db = conn.getMetaData(); // 从元数据中获取到所有的表名 rs = db.getTables(null, null, "%"+year+"_"+month, new String[] { "TABLE" }); while (rs.next()) { tableNames.add(rs.getString(3)); } } catch (SQLException e) { e.printStackTrace(); System.err.println("getTableNames failure"); } finally { try { if (null != rs) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); System.err.println("close ResultSet failure"); } } return tableNames; } /** * 获取表中所有字段名称 * * @param tableName * 表名 * @return */ private List<String> getColumnNames(String tableName) { List<String> columnNames = new ArrayList<String>(); // 与数据库的连接 Connection conn = getConnection(); PreparedStatement pStemt = null; String tableSql = SQL + tableName; try { pStemt = conn.prepareStatement(tableSql); // 结果集元数据 ResultSetMetaData rsmd = pStemt.getMetaData(); // 表列数 int size = rsmd.getColumnCount(); for (int i = 0; i < size; i++) { columnNames.add(rsmd.getColumnName(i + 1)); } } catch (SQLException e) { System.err.println("getColumnNames failure"); e.printStackTrace(); } finally { if (pStemt != null) { try { pStemt.close(); } catch (SQLException e) { e.printStackTrace(); System.err.println("getColumnNames close pstem and connection failure"); } } } return columnNames; } /** * 获取表中所有字段类型 * * @param tableName * @return */ private List<String> getColumnTypes(String tableName) { List<String> columnTypes = new ArrayList<String>(); // 与数据库的连接 Connection conn = getConnection(); PreparedStatement pStemt = null; String tableSql = SQL + tableName; try { pStemt = conn.prepareStatement(tableSql); // 结果集元数据 ResultSetMetaData rsmd = pStemt.getMetaData(); // 表列数 int size = rsmd.getColumnCount(); for (int i = 0; i < size; i++) { columnTypes.add(rsmd.getColumnTypeName(i + 1)); } } catch (SQLException e) { e.printStackTrace(); System.err.println("getColumnTypes failure"); } finally { if (pStemt != null) { try { pStemt.close(); } catch (SQLException e) { e.printStackTrace(); System.err.println("getColumnTypes close pstem and connection failure"); } } } return columnTypes; } /** * @description: 生成建表语句 * @param: [tableName] * @return: java.lang.String * @author liupengcheng * @date: 2021/7/9 15:26 */ private String generateCreateTableSql(String tableName) { String sql = String.format("SHOW CREATE TABLE %s", tableName); Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = (PreparedStatement) conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); Calendar rightNow = Calendar.getInstance(); Integer year = rightNow.get(Calendar.YEAR); Integer month = rightNow.get(Calendar.MONTH)+1; // int nextMonth; if(month + 1 > 12){ nextMonth = 1; }else{ nextMonth = month+1; } String newTableName = year+"_"+nextMonth; while (rs.next()) { // 返回建表语句语句,查询结果的第二列是建表语句,第一列是表名 String createTable = rs.getString(2); //替换创建语句为新日期的表名 createTable = createTable.replace(year+"_"+month,newTableName); return createTable; } } catch (Exception e) { e.printStackTrace(); try { if (null != pstmt) { pstmt.close(); } } catch (Exception e2) { e.printStackTrace(); System.err.println("关闭流异常"); } } return null; } /** * 获取表中字段的所有注释 * * @param tableName * @return */ private List<String> getColumnComments(String tableName) { // 与数据库的连接 Connection conn = getConnection(); PreparedStatement pStemt = null; String tableSql = SQL + tableName; List<String> columnComments = new ArrayList<String>();// 列名注释集合 ResultSet rs = null; try { pStemt = conn.prepareStatement(tableSql); rs = pStemt.executeQuery("show full columns from " + tableName); while (rs.next()) { columnComments.add(rs.getString("Comment")); } } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); System.err.println("getColumnComments close ResultSet and connection failure"); } } } return columnComments; } /** * @description: 获取表数据一行的所有值 * @param: [rs, size, columnTypeList] * @return: java.lang.String * @author liupengcheng * @date: 2021/7/9 15:25 */ private String getRowValues(ResultSet rs, int size, List<String> columnTypeList) { try { String rowValues = null; for (int i = 1; i <= size; i++) { String columnValue = null; // 获取字段值 columnValue = getValue(rs, i, columnTypeList.get(i - 1)); // 如果是空值不添加单引号 if (null != columnValue) { columnValue = "'" + columnValue + "'"; } // 拼接字段值 if (null == rowValues) { rowValues = columnValue; } else { rowValues = rowValues + "," + columnValue; } } return rowValues; } catch (Exception e) { e.printStackTrace(); System.out.println("获取表数据一行的所有值异常"); return null; } } /** * @description: 根据类型获取字段值 * @param: [resultSet, index, columnType] * @return: java.lang.String * @author liupengcheng * @date: 2021/7/9 15:55 */ private String getValue(ResultSet resultSet, Integer index, String columnType) { try { if ("int".equals(columnType) || "INT".equals(columnType)) { // 整数 Object intValue = resultSet.getObject(index); if (null == intValue) { return null; } return intValue + ""; } else if ("bigint".equals(columnType) || "BIGINT".equals(columnType)) { // 长整形 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("smallint".equals(columnType) || "SMALLINT".equals(columnType)) { // 整数 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("tinyint".equals(columnType) || "TINYINT".equals(columnType)) { // 整数 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("mediumint".equals(columnType) || "MEDIUMINT".equals(columnType)) { // 长整形 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("integer".equals(columnType) || "INTEGER".equals(columnType)) { // 整数 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("float".equals(columnType) || "FLOAT".equals(columnType)) { // 浮点数 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("double".equals(columnType) || "DOUBLE".equals(columnType)) { // 浮点数 Object value = resultSet.getObject(index); if (null == value) { return null; } return value + ""; } else if ("decimal".equals(columnType) || "DECIMAL".equals(columnType)) { // 浮点数-金额类型 BigDecimal value = resultSet.getBigDecimal(index); if (null == value) { return null; } return value.toString(); } else if ("char".equals(columnType) || "CHAR".equals(columnType)) { // 字符串类型 String value = resultSet.getString(index); return value; } else if ("varchar".equals(columnType) || "VARCHAR".equals(columnType)) { // 字符串类型 String value = resultSet.getString(index); return value; } else if ("tinytext".equals(columnType) || "TINYTEXT".equals(columnType)) { // 字符串类型 String value = resultSet.getString(index); return value; } else if ("text".equals(columnType) || "TEXT".equals(columnType)) { // 字符串类型 String value = resultSet.getString(index); return value; } else if ("mediumtext".equals(columnType) || "MEDIUMTEXT".equals(columnType)) { // 字符串类型 String value = resultSet.getString(index); return value; } else if ("longtext".equals(columnType) || "LONGTEXT".equals(columnType)) { // 字符串类型 String value = resultSet.getString(index); return value; } else if ("year".equals(columnType) || "YEAR".equals(columnType)) { // 时间类型:范围 1901/2155 格式 YYYY String year = resultSet.getString(index); if (null == year) { return null; } // 只需要年的字符即可, return year.substring(0, 4); } else if ("date".equals(columnType) || "DATE".equals(columnType)) { // 时间类型:范围 '1000-01-01'--'9999-12-31' 格式 YYYY-MM-DD return resultSet.getString(index); } else if ("time".equals(columnType) || "TIME".equals(columnType)) { // 时间类型:范围 '-838:59:59'到'838:59:59' 格式 HH:MM:SS return resultSet.getString(index); } else if ("datetime".equals(columnType) || "DATETIME".equals(columnType)) { // 时间类型:范围 '1000-01-01 00:00:00'--'9999-12-31 23:59:59' 格式 YYYY-MM-DD HH:MM:SS return resultSet.getString(index); } else if ("timestamp".equals(columnType) || "TIMESTAMP".equals(columnType)) { // 时间类型:范围 1970-01-01 00:00:00/2037 年某时 格式 YYYYMMDD HHMMSS 混合日期和时间值,时间戳 return resultSet.getString(index); } else { return null; } } catch (Exception e) { e.printStackTrace(); System.err.println("获取数据库类型值异常"); return null; } } public void executeCreateTable(){ try { List<String> tableNames = getTableNames(); log.info("需要创建新表的旧表名为:{}", JSONObject.toJSONString(tableNames)); Calendar rightNow = Calendar.getInstance(); Integer year = rightNow.get(Calendar.YEAR); Integer month = rightNow.get(Calendar.MONTH)+1; // String newTableName; if(month + 1 > 12){ newTableName = year+"_1"; }else{ newTableName = year+"_"+(month+1); } DatabaseMetaData db = conn.getMetaData(); // 从元数据中获取到所有的表名 Statement stat = conn.createStatement(); for (String tableName : tableNames) { String newTable = tableName.replace(year+"_"+month,newTableName); log.info("新表名:{}",newTable); //校验新生成的新表 数据库是否存在 ResultSet rs = db.getTables(null, null, newTable, new String[] { "TABLE" }); if(rs.next() ){ continue; } String createTableSql = generateCreateTableSql(tableName); log.info("建表语句:{}",createTableSql); stat.execute(createTableSql); //建完新表将新表的AUTO_INCREMENT改为1 String updateTableAutoIncrementSql = "alter table "+newTable+" auto_increment = 1;"; stat.execute(updateTableAutoIncrementSql); } // 统一关闭连接 stat.close(); closeConnection(conn); } catch (Exception e) { e.printStackTrace(); } } public void executeCreateTableOfYear() { try { log.info("定时任务执行创建下一年的表"); List<String> tableNames = getTableNames(); log.info("需要创建新表的旧表名为:{}", JSONObject.toJSONString(tableNames)); Calendar rightNow = Calendar.getInstance(); Integer year = rightNow.get(Calendar.YEAR); Integer month = rightNow.get(Calendar.MONTH)+1; DatabaseMetaData db = conn.getMetaData(); // 从元数据中获取到所有的表名 Statement stat = conn.createStatement(); for (String tableName : tableNames) { for(int i =1 ;i<=12;i++){ String newTableName = year+1+"_"+i; String newTable = tableName.replace(year+"_"+month,newTableName); log.info("新表后缀:{}",newTable); //校验新生成的新表 数据库是否存在 ResultSet rs = db.getTables(null, null, newTable, new String[] { "TABLE" }); if(rs.next() ){ continue; } String createTableSql = generateCreateTableSqlOfYear(tableName,newTable); log.info("建表语句:{}",createTableSql); stat.execute(createTableSql); //建完新表将新表的AUTO_INCREMENT改为1 String updateTableAutoIncrementSql = "alter table "+newTable+" auto_increment = 1;"; stat.execute(updateTableAutoIncrementSql); } } // 统一关闭连接 stat.close(); closeConnection(conn); } catch (Exception e) { log.error("executeCreateTableOfYear发生异常:{}",e); } } private String generateCreateTableSqlOfYear(String tableName, String newTableName) { String sql = String.format("SHOW CREATE TABLE %s", tableName); Connection conn = null; PreparedStatement pstmt = null; try { conn = getConnection(); pstmt = (PreparedStatement) conn.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { // 返回建表语句语句,查询结果的第二列是建表语句,第一列是表名 String createTable = rs.getString(2); //替换创建语句为新日期的表名 createTable = createTable.replace(tableName,newTableName); return createTable; } } catch (Exception e) { e.printStackTrace(); try { if (null != pstmt) { pstmt.close(); } } catch (Exception e2) { e.printStackTrace(); System.err.println("关闭流异常"); } } return null; }} |
package com.chinatower.product.sys.core.util;import org.apache.commons.lang3.time.DurationFormatUtils;import org.joda.time.*;import org.joda.time.format.DateTimeFormat;import java.util.Date;import java.util.Locale;public class DateUtil { /** * yyyyMMdd */ public final static String YYYYMMDD = "yyyyMMdd"; /** * yyMMddHHmmss */ public final static String YYMMDDHHMMSS = "yyMMddHHmmss"; /** * yyyy-MM-dd */ public final static String YYYY_MM_DD = "yyyy-MM-dd"; /** * yyyy年MM月dd日 */ public final static String YYYY_MM_DD_ZH = "yyyy年MM月dd日"; /** * yyyy-MM-dd HH:mm:ss */ public final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; /** * yyyy-MM-dd HH:mm */ public final static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; /** * yyyy年MM月dd日 HH:mm */ public final static String YYYY_MM_DD_HH_MM_ZH = "yyyy年MM月dd日 HH:mm"; /** * yyyy年MM月dd日 a hh:mm */ public final static String YYYY_MM_DD_A_HH_MM_ZH = "yyyy年MM月dd日 a hh:mm"; private static int idCount = 0; /** * 取得日期 * * @param date * @param format * @return 日期字符串 */ public static Date getDate(String date, String format) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); return d.toDate(); } /** * 取得日期 * * @param date * @param format * @return 日期字符串 */ public static Date getYMDDate(Date date) { DateTime d = new DateTime(date); return getDate(d.toString(YYYY_MM_DD), YYYY_MM_DD); } /** * 取得日期(字符串) * * @param date * @param format * @return 日期字符串 */ public static String getDateStr(Date date, String format) { DateTime d = new DateTime(date); return d.toString(format); } /** * 取得日期(字符串) * * @param date * @param format * @return 日期字符串 */ public static String getLocalDateStr(Date date, String format) { DateTime d = new DateTime(date); return d.toString(DateTimeFormat.forPattern(format).withLocale(Locale.CHINESE)); } /** * 取得日期(DateTime) * * @param date * @return DateTime */ public static DateTime getDate(Date date) { DateTime d = new DateTime(date); return d; } /** * 取得日期(DateTime) * * @param date * @param format * @return DateTime */ public static DateTime getDateStr(String date, String format) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); return d; } /** * 转换日期格式 * * @param date * @param format * @param targetFormat * @return 新格式日期字符串 */ public static String changeDateFormat(DateTime d, String targetFormat) { return d.toString(targetFormat); } /** * 转换日期格式 * * @param date * @param format * @param targetFormat * @return 新格式日期字符串 */ public static String changeDateFormat(Date date, String targetFormat) { DateTime d = new DateTime(date); return d.toString(targetFormat); } /** * 转换日期格式 * * @param date * @param format * @param targetFormat * @return 新格式日期字符串 */ public static String changeDateFormat(String date, String format, String targetFormat) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); return d.toString(targetFormat); } /** * 日期加减年 * * @param date * @param format * @param i 加的年数 * @return 新格式日期字符串 */ public static String datePlusYearToStr(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusYears(i); return d.toString(format); } /** * 日期加减月 * * @param date * @param format * @param i 加的月数 * @return 新格式日期字符串 */ public static String datePlusMonthsToStr(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusMonths(i); return d.toString(format); } /** * 日期加减日 * * @param date * @param format * @param i 加的天数 * @return 新格式日期字符串 */ public static String datePlusToStr(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusDays(i); return d.toString(format); } /** * 工作日加减日 * * @param date * @param format * @param i 加的天数 * @return 新格式日期字符串 */ public static String datePlusWorkDayToStr(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusDays(i); while (d.getDayOfWeek() > 5) { if (i == 0) { break; } d = d.plusDays(i); } return d.toString(format); } /** * 工作日加减日 * * @param date * @param format * @param i 加的天数 * @return 新格式日期字符串 */ public static Date datePlusWorkDayToDate(Date date, int i) { DateTime d = new DateTime(date); d = d.plusDays(i); while (d.getDayOfWeek() > 5) { if (i == 0) { break; } d = d.plusDays(i); } return d.toDate(); } /** * 日期加减小时 * * @param date * @param format * @param i 加的小时数 * @return 新格式日期字符串 */ public static String datePlusHoursToStr(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusHours(i); return d.toString(format); } /** * 日期加减小时 * * @param date * @param format * @param i 加的小时数 * @return 新格式日期 */ public static Date datePlusHoursToDate(Date date, int i) { DateTime d = new DateTime(date); d = d.plusHours(i); return d.toDate(); } /** * 日期加减分钟 * * @param date * @param format * @param i 加的分钟数 * @return 新格式日期字符串 */ public static String datePlusMinutesToStr(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusMinutes(i); return d.toString(format); } /** * 日期加减日 * * @param date * @param format * @param i 加的天数 * @return 新格式日期字符串 */ public static Date datePlusToDate(String date, String format, int i) { DateTime d = DateTime.parse(date, DateTimeFormat.forPattern(format)); d = d.plusDays(i); return d.toDate(); } /** * 日期加减日 * * @param date * @param format * @param i 加的天数 * @return 新格式日期字符串 */ public static String datePlusToStr(Date date, String format, int i) { DateTime d = new DateTime(date); d = d.plusDays(i); return d.toString(format); } /** * 日期加减日 * * @param date * @param format * @param targetFormat * @return 新格式日期字符串 */ public static Date datePlusToDate(Date date, String format, int i) { DateTime d = new DateTime(date); d = d.plusDays(i); return d.toDate(); } /** * 日期对比 * * @param date1 * @param date2 * @return int 1:大于;0等于;-1小于 */ public static int dateCompare(Date date1, Date date2) { DateTime d1 = new DateTime(date1); DateTime d2 = new DateTime(date2); int i = 0; if (d1.isAfter(d2)) { i = 1; } else if (d1.isBefore(d2)) { i = -1; } else { i = 0; } return i; } /** * 比较两个日期相差天数 * * @param date1 * @param date2 * @return 天数 */ public static int dateCompareDays(Date date1, Date date2) { LocalDate d1 = new LocalDate(date1); LocalDate d2 = new LocalDate(date2); return Days.daysBetween(d1,d2).getDays(); } /** * 比较两个日期相差秒 * * @param date1 * @param date2 * @return 相差秒 */ public static int dateCompareSeconds(Date date1, Date date2) { DateTime d1 = new DateTime(date1); DateTime d2 = new DateTime(date2); Period p = new Period(d1, d2, PeriodType.seconds()); return p.getSeconds(); } /** * 比较两个日期相小时 * * @param date1 * @param date2 * @return 相差小时 */ public static int dateCompareHours(Date date1, Date date2) { DateTime d1 = new DateTime(date1); DateTime d2 = new DateTime(date2); Period p = new Period(d1, d2, PeriodType.hours()); return p.getHours(); } /** * 比较两个日期相差分钟 * * @param date1 * @param date2 * @return 相差分钟 */ public static long dateCompareMinutes(Date date1, Date date2) { DateTime d1 = new DateTime(date1); DateTime d2 = new DateTime(date2); Period p = new Period(d1, d2, PeriodType.minutes()); return p.getMinutes(); } /** * 比较两个日期相差毫秒 * * @param date1 * @param date2 * @return 相差毫秒 */ public static long dateCompareMills(Date date1, Date date2) { return date2.getTime() - date1.getTime(); } /** * 时间范围格式化 * @param mills * @param format * @return */ public static String formatDuration(long mills, String format) { return DurationFormatUtils.formatDuration(mills, format); } /** * 根据时间生产唯一id * @return */ public static synchronized String getDateUUID(){ DateTime date = new DateTime(new Date()); String dateUUID = date.toString("yyyyMMddHHmmssS"); if(idCount > 99) idCount = 0; if(idCount > 9){ dateUUID = dateUUID + idCount; }else{ dateUUID = dateUUID + "0" + idCount; } idCount++; return dateUUID; } public static void main(String[] args){ System.out.println(dateCompareDays(new Date(), getDate("2016-12-10",YYYY_MM_DD ))); }} |
package com.chinatower.product.sys.core.util;import com.google.common.net.MediaType;import org.apache.commons.io.IOUtils;import org.springframework.http.HttpHeaders;import org.springframework.web.servlet.view.AbstractView;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.InputStream;import java.util.Map;public class DownloadView extends AbstractView { /** * 文件类型 */ public static enum FILE_TYPE { DOC(MediaType.MICROSOFT_WORD), DOCX(MediaType.OOXML_DOCUMENT), XLS(MediaType.MICROSOFT_EXCEL), XLSX( MediaType.OOXML_SHEET), PDF(MediaType.PDF), STREAM(MediaType.OCTET_STREAM); private MediaType contentType; private FILE_TYPE(MediaType contentType) { this.contentType = contentType; } public String toString() { return this.contentType.toString(); } } /** * 导出文件 */ public static String EXPORT_FILE = "EXPORT_FILE"; /** * 导出文件名称 */ public static String EXPORT_FILE_NAME = "EXPORT_FILE_NAME"; /** * 导出文件类型 */ public static String EXPORT_FILE_TYPE = "EXPORT_FILE_TYPE"; /** * 导出文件长度 */ public static String EXPORT_FILE_SIZE = "EXPORT_FILE_SIZE"; @Override protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { String contentType = String.valueOf(model.get(EXPORT_FILE_TYPE)); setContentType(contentType); InputStream fileInputStream = (InputStream) model.get(EXPORT_FILE); String originalFileName = (String) model.get(EXPORT_FILE_NAME); response.setContentType(contentType); response.setContentLengthLong(fileInputStream.available()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + WebUtil.getDownloadFileName(originalFileName)); ServletOutputStream out = response.getOutputStream(); IOUtils.copy(fileInputStream, out); out.flush(); IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(out); }} |
package com.chinatower.product.sys.core.util;import lombok.extern.slf4j.Slf4j;import org.apache.http.HttpEntity;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicHeader;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import org.springframework.http.MediaType;/** * @author junze_qin */@Slf4jpublic class HttpUtil { private static final int TIMEOUT = 10 * 1000; /** * */ public static String httpPostWithJSON(String url, String encoderJson) throws Exception { log.info("请求url:{},参数:{}",url,encoderJson); CloseableHttpClient httpClient = HttpClients.createDefault(); //配置超时时间 RequestConfig requestConfig = RequestConfig.custom(). setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT) .setSocketTimeout(TIMEOUT).setRedirectsEnabled(true).build(); HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); httpPost.setHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE); StringEntity stringEntity = new StringEntity(encoderJson, "UTF-8"); stringEntity.setContentType("text/json"); stringEntity .setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)); httpPost.setEntity(stringEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity entity = httpResponse.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); httpClient.close(); return result; }} |
package com.chinatower.product.sys.core.util;import com.chinatower.product.sys.mapper.SmsConfigMapper;import com.chinatower.product.sys.service.SmsAlarmConfigService;import com.chinatower.product.sys.service.SmsConfigService;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;@Component@Slf4j@Order(2)public class InitRedisCache implements CommandLineRunner { @Autowired private SmsConfigService smsConfigService; @Autowired private SmsAlarmConfigService smsAlarmConfigService; @Override public void run(String... args) throws Exception { log.info("[短信网关],[短信组件对接系统信息]加载缓存 开始--------------"); smsConfigService.initAllDataOfRedis(); log.info("[短信网关],[短信组件对接系统信息]加载缓存 结束--------------"); log.info("[短信监控规则配置]加载缓存 开始--------------"); smsAlarmConfigService.initAllDataOfRedis(); log.info("[短信监控规则配置]加载缓存 结束--------------"); }} |
package com.chinatower.product.sys.core.util;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.DisposableBean;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/** * @author caozf */@Componentpublic class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext; private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } public static void clearHolder() { logger.debug("clear SpringContextHolder ApplicationContext:" + applicationContext); applicationContext = null; } @Override public void setApplicationContext(ApplicationContext applicationContext) { logger.debug("Inject applicationContext to SpringContextHolder:{}", applicationContext); if (SpringContextHolder.applicationContext != null) { logger.warn("replace the applicationContext,the old applicationContext is:" + SpringContextHolder.applicationContext); } SpringContextHolder.applicationContext = applicationContext; } @Override public void destroy() throws Exception { SpringContextHolder.clearHolder(); } private static void assertContextInjected() { if (applicationContext == null) { throw new IllegalStateException("applicationContext have not injected, please define it"); } }} |
package com.chinatower.product.sys.core.util;import com.google.common.base.Charsets;import com.google.common.collect.ImmutableMap;import com.google.common.net.HttpHeaders;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import org.springframework.web.util.UriComponents;import org.springframework.web.util.UriComponentsBuilder;import javax.servlet.http.HttpServletRequest;import java.net.URLEncoder;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;public abstract class WebUtil { private static Logger logger = LoggerFactory.getLogger(WebUtil.class); private static final String[] AGENT_INDEX = {"MSIE", "Firefox", "Chrome", "Opera", "Safari"}; private static final Map<String, Pattern> AGENT_PATTERNS = ImmutableMap.of(AGENT_INDEX[0], Pattern.compile("MSIE ([\\d.]+)|Trident/([\\d.]+)"), AGENT_INDEX[1], Pattern.compile("Firefox/(\\d.+)"), AGENT_INDEX[2], Pattern.compile("Chrome/([\\d.]+)"), AGENT_INDEX[3], Pattern.compile("Opera[/\\s]([\\d.]+)"), AGENT_INDEX[4], Pattern.compile("Version/([\\d.]+)")); /** * 取得当前请求 * * @return */ public static HttpServletRequest getCurrentRequest() { return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); } /** * 取得浏览器的下载文件名 * * @param OriginaFileName 原始文件名 */ public static String getDownloadFileName(String OriginaFileName) { String downloadFileName = null; HttpServletRequest request = getCurrentRequest(); try { UserAgent userAgent = getUserAgent(request); // 是否是IE浏览器 if (userAgent != null && AGENT_INDEX[0].equals(userAgent.getName())) { downloadFileName = URLEncoder.encode(OriginaFileName, Charsets.UTF_8.name()); } else { downloadFileName = new String(OriginaFileName.getBytes(Charsets.UTF_8.name()), Charsets.ISO_8859_1.name()); } } catch (Exception e) { logger.error("encode download file name [{}] error: {}", OriginaFileName, e); } return downloadFileName; } /** * 是否ajax请求 * * @param request * @return */ public static boolean isAjaxRquest(HttpServletRequest request) { String requestedWith = request.getHeader(HttpHeaders.X_REQUESTED_WITH); return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false; } /** * 取得请求IP地址 * * @param request * @return */ public static String getClientIpAddr(HttpServletRequest request) { String ip = request.getHeader(HttpHeaders.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(); } return ip; } /** * 解析URI * * @param request * @return */ public static UriComponents parseUri(HttpServletRequest request) { UriComponents uriComponents = null; if (request != null) { uriComponents = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString()).build(); } return uriComponents; } /** * 解析URI * * @param uri * @return */ public static UriComponents parseUri(String uri) { UriComponents uriComponents = null; if (StringUtils.isNotEmpty(uri)) { uriComponents = UriComponentsBuilder.fromHttpUrl(uri).build(); } return uriComponents; } /** * 根据请求字符取得用户代理 * * @param userAgent * @return */ public static UserAgent getUserAgent(String userAgent) { if ((userAgent == null) || (userAgent.isEmpty())) { return null; } for (String agent : AGENT_INDEX) { Pattern pattern = AGENT_PATTERNS.get(agent); Matcher matcher = pattern.matcher(userAgent); if (matcher.find()) { return new UserAgent(agent, matcher.group(1)); } } return null; } /** * 根据请求取得用户代理 * * @param request * @return */ public static UserAgent getUserAgent(HttpServletRequest request) { if (request == null) { return null; } String userAgentHead = request.getHeader(HttpHeaders.USER_AGENT); return getUserAgent(userAgentHead); } public static class UserAgent { private String name = null; private String version = null; public UserAgent(String name, String version) { this.name = name; this.version = version; } public String getName() { return this.name; } public String getVersion() { return this.version; } }} |
package com.strongdata.portal.controller;import com.strongdata.portal.service.HomePageService;import com.strongdata.rill.core.base.util.R;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * 门户首页 * * @author wk * @date 2022-08-02 17:11:27 */@RestController@RequiredArgsConstructor@RequestMapping("/home")@Tag(name = "门户首页")public class HomePageController { private final HomePageService homePageService; /** * 门户首页应用产品按分类查询 * 该接口不需要登录 * @return R */ @Operation(summary = "门户首页应用产品按分类查询", description = "门户首页应用产品按分类查询") @GetMapping("/queryProductList") public R queryProductList() { return R.ok(homePageService.queryProductList()); }} |
package com.strongdata.portal.controller;import com.strongdata.portal.service.LargeScreenService;import com.strongdata.rill.core.base.util.R;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * 门户大屏 * * @author wk * @date 2022-08-02 17:11:27 */@RestController@RequiredArgsConstructor@RequestMapping("/largescreen")@Tag(name = "门户大屏")public class LargeScreenController { private final LargeScreenService largeScreenService; /** * 门户大屏应用产品 * @return R */ @Operation(summary = "门户大屏应用产品", description = "门户大屏应用产品") @GetMapping("/queryProductList") public R queryProductList() { return R.ok(largeScreenService.queryProductList()); }} |
Subsets and Splits