一体化系统优化—公务管理初始化代码

This commit is contained in:
李京通 2025-05-28 09:39:26 +08:00
commit de4e9e514b
640 changed files with 65569 additions and 0 deletions

33
.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

View File

@ -0,0 +1,4 @@
auth_key=5b6fc55e66849a26478d3dd3136c65b6
auth_code=7dd01ab4b79c8b972b04350534bed3cfaa140aae
smsid=SEND00001
spid=111411

60
gather-app/pom.xml Normal file
View File

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.ruoyi</groupId>
<artifactId>PublicAffairs</artifactId>
<version>4.0.0</version>
</parent>
<artifactId>gather-app</artifactId>
<dependencies>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,96 @@
package com.ruoyi.aspect;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.cache.DictCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanValidators;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import javax.validation.Validator;
import java.lang.reflect.Field;
import java.util.List;
@Aspect
@Component
@RequiredArgsConstructor
public class ImportAspect {
protected final Validator validator;
@Around("execution(* com.ruoyi.database.service.*.*import*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取方法的入参
Object[] args = joinPoint.getArgs();
List<?> importList = (List<?>) args[0];
if (CollUtil.isEmpty(importList)) {
throw new ServiceException("导入数据为空");
}
// 获取list表中类的类型
Class<?> clazz = importList.get(0).getClass();
// 错误标记判断是否有错误信息
boolean errorFlag = false;
// 遍历list表中的数据回填字典值
for (Object obj : importList) {
// 记录属性中存在区域编码相关的属性的个数判断如何回填区域编码
int codeCount = 0;
// 获取类中的所有属性
for (Field field : clazz.getDeclaredFields()) {
// 判断属性中是否有Cn结尾的属性
String fieldName = field.getName();
if (StrUtil.endWithIgnoreCase(fieldName, "Cn") && !field.getName().equals("structuredCameraTypeCn")) {
field.setAccessible(true);
// 获取非Cn属性名
String fieldName1 = StrUtil.subBefore(fieldName, "Cn", true);
String dictType = StrUtil.toUnderlineCase(fieldName1);
// 获取字典标签
Object dictLabel = field.get(obj);
int dictValue;
try {
// 获取字典值
dictValue = Integer.parseInt(DictCache.getDictValue(StrUtil.format("{}-{}", dictType, dictLabel)));
} catch (Exception e) {
// 字典值不存在跳过
continue;
}
// 回填字典值
ReflectUtil.setFieldValue(obj, fieldName1, dictValue);
}
// // 判断属性中是否存在区域编码相关的属性
// if (StrUtil.equalsAny(fieldName, "placeCode", "gridCode", "buildingCode", "unitCode", "homeCode")) {
// codeCount++;
// }
}
// 校验数据校验不通过则记录错误信息
try {
BeanValidators.validateWithException(validator, obj);
} catch (Exception e) {
ReflectUtil.setFieldValue(obj, "remark", e.getMessage());
errorFlag = true;
continue;
}
}
if (errorFlag) {
return importList;
}
// 执行目标方法
return joinPoint.proceed();
}
}

View File

@ -0,0 +1,64 @@
package com.ruoyi.aspect;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
@Aspect
@Component
@RequiredArgsConstructor
public class InsertAspect {
@Around("execution(* com.ruoyi.business.controller.*.*insert*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 获取目标方法的参数
Object[] args = joinPoint.getArgs();
// 遍历参数查找包含 areaAuthCode 字段的对象
for (Object arg : args) {
if (hasAreaAuthCodeField(arg)) {
LoginUser userinfo = SecurityUtils.getLoginUser();
String authCode = userinfo.getUser().getAreaAuthCode();
// 对包含 areaAuthCode 字段的对象进行处理
setAreaAuthCode(arg, authCode);
}
}
// 执行目标方法
return joinPoint.proceed();
}
// 判断对象是否包含 areaAuthCode 字段
private boolean hasAreaAuthCodeField(Object obj) {
Class<?> clazz = obj.getClass();
try {
// 使用反射获取对象的字段
Field areaAuthCodeField = clazz.getDeclaredField("areaAuthCode");
return areaAuthCodeField != null;
} catch (NoSuchFieldException e) {
return false;
}
}
// 设置对象的 areaAuthCode 字段的值
private void setAreaAuthCode(Object obj, String value) {
Class<?> clazz = obj.getClass();
try {
// 使用反射获取对象的字段
Field areaAuthCodeField = clazz.getDeclaredField("areaAuthCode");
// 设置字段为可访问
areaAuthCodeField.setAccessible(true);
// 设置字段的值
areaAuthCodeField.set(obj, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,64 @@
//package com.ruoyi.aspect;
//
//import com.ruoyi.common.core.domain.model.LoginUser;
//import com.ruoyi.common.utils.SecurityUtils;
//import lombok.RequiredArgsConstructor;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.springframework.stereotype.Component;
//
//import java.lang.reflect.Field;
//
//@Aspect
//@Component
//@RequiredArgsConstructor
//public class UpdateAspect {
//
// @Around("execution(* com.ruoyi.business.controller.*.*update*(..))")
// public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// // 获取目标方法的参数
// Object[] args = joinPoint.getArgs();
//
// // 遍历参数查找包含 areaAuthCode 字段的对象
// for (Object arg : args) {
// if (hasAreaAuthCodeField(arg)) {
//
// LoginUser userinfo = SecurityUtils.getLoginUser();
// String authCode = userinfo.getUser().getAreaAuthCode();
// // 对包含 areaAuthCode 字段的对象进行处理
// setAreaAuthCode(arg, authCode);
// }
// }
//
// // 执行目标方法
// return joinPoint.proceed();
// }
//
// // 判断对象是否包含 areaAuthCode 字段
// private boolean hasAreaAuthCodeField(Object obj) {
// Class<?> clazz = obj.getClass();
// try {
// // 使用反射获取对象的字段
// Field areaAuthCodeField = clazz.getDeclaredField("areaAuthCode");
// return areaAuthCodeField != null;
// } catch (NoSuchFieldException e) {
// return false;
// }
// }
//
// // 设置对象的 areaAuthCode 字段的值
// private void setAreaAuthCode(Object obj, String value) {
// Class<?> clazz = obj.getClass();
// try {
// // 使用反射获取对象的字段
// Field areaAuthCodeField = clazz.getDeclaredField("areaAuthCode");
// // 设置字段为可访问
// areaAuthCodeField.setAccessible(true);
// // 设置字段的值
// areaAuthCodeField.set(obj, value);
// } catch (NoSuchFieldException | IllegalAccessException e) {
// e.printStackTrace();
// }
// }
//}

View File

@ -0,0 +1,57 @@
package com.ruoyi.aspect;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.List;
@Aspect
@Component
@RequiredArgsConstructor
public class responseAspect {
// @Around("execution(* com.ruoyi.business.controller.*.list(..))")
// public TableDataInfo<Object> around(ProceedingJoinPoint joinPoint) throws Throwable {
// Object proceed = joinPoint.proceed();
// TableDataInfo<Object> tableDataInfo = (TableDataInfo<Object>) proceed;
// List list = (List) tableDataInfo.getRows();
//
// for (Object o : list) {
// // 获取list表中类的类型
// Class<?> aClass = o.getClass();
//
// // 遍历实体类的字段
// for (Field field : aClass.getDeclaredFields()) {
// String fieldName = field.getName();
// // 判断字段是否为电话号码或身份证号码并对其进行脱敏
// if (StrUtil.containsIgnoreCase(fieldName, "idcard")) {
// field.setAccessible(true);
// String value = String.valueOf(field.get(o));
// try {
// ReflectUtil.setFieldValue(o, fieldName, DesensitizedUtil.idCardNum(value, 4, 4));
// } catch (Exception ignored) {
// }
// }
//
// if (StrUtil.containsIgnoreCase(fieldName, "phone")) {
// field.setAccessible(true);
// String value = String.valueOf(field.get(o));
// try {
// ReflectUtil.setFieldValue(o, fieldName, DesensitizedUtil.mobilePhone(value));
// } catch (Exception ignored) {
// }
// }
// }
// }
// tableDataInfo.setRows(list);
// return tableDataInfo;
// }
}

View File

@ -0,0 +1,84 @@
package com.ruoyi.business.common;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.business.util.StringKit;
import com.ruoyi.business.util.SySMS;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.database.domain.BaseFlowLog;
import com.ruoyi.database.domain.vo.SMSMsgVO;
import com.ruoyi.database.service.BaseFlowLogService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Api(tags = "射阳短信登录验证码")
@RestController
@RequestMapping("/base/SySMSLoginMsg")
@RequiredArgsConstructor
public class SySMSLoginMsg {
private final BaseFlowLogService baseFlowLogService;
private final ISysUserService sysUserService;
private static final String SMS_KEY = "SMS_KEY:";
@GetMapping
@ApiOperation("获取短信登录验证码")
public AjaxResult getMes(@RequestParam(required = false) @ApiParam("手机号") String mobiles) {
SysUser sysUser = sysUserService.selectUserByPhone(mobiles);
if (sysUser == null){
return AjaxResult.error("用户不存在,请联系管理员");
}
RedisCache bean = SpringUtils.getBean(RedisCache.class);
SMSMsgVO msgVO = bean.getCacheObject(SMS_KEY + mobiles);
if (msgVO != null) {
Long oldTime = msgVO.getTime();
Long nowTime = System.currentTimeMillis()/1000;
if((nowTime - oldTime) < 10){
return AjaxResult.error("请勿频繁点击");
}
}
String capcha = getCapcha();
String msg = "【射阳公安局一体化工作平台】用户登录验证码:" + capcha + "";
BaseFlowLog baseFlowLog = SySMS.sendMessage(mobiles, dateToyyyyMMddHHmmss(), msg, "登录验证短信", mobiles, "");
baseFlowLogService.save(baseFlowLog);
SMSMsgVO smsMsgVO = new SMSMsgVO();
smsMsgVO.setMsg(capcha);
smsMsgVO.setPhone(mobiles);
smsMsgVO.setTime(System.currentTimeMillis() / 1000L);
smsMsgVO.setContent(msg);
bean.setCacheObject(SMS_KEY + mobiles,smsMsgVO,10, TimeUnit.MINUTES);
return AjaxResult.success("短信发送成功");
}
public String getCapcha() {
Random random = new Random();
int captcha = random.nextInt(900000) + 100000;
return StringKit.toString(captcha);
}
public String dateToyyyyMMddHHmmss() {
long l = System.currentTimeMillis() - 8L * 3600 * 1000;
Date date = new Date(l);
return DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
}
}

View File

@ -0,0 +1,81 @@
package com.ruoyi.business.common;
import com.ruoyi.business.util.StringKit;
import com.ruoyi.business.util.SwtMessage;
import com.ruoyi.business.util.SwtToken;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.database.domain.BaseFlowLog;
import com.ruoyi.database.domain.vo.SwtMsgVO;
import com.ruoyi.database.service.BaseFlowLogService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Api(tags = "射阳苏网通登录验证码")
@RestController
@RequestMapping("/base/SySwtLoginMsg")
@RequiredArgsConstructor
public class SySwtLoginMsg {
private final BaseFlowLogService baseFlowLogService;
private final ISysUserService sysUserService;
private static final String SWT_KEY = "SWT_KEY:";
@GetMapping
@ApiOperation("获取苏网通登录验证码")
public AjaxResult getMes(@RequestParam(required = false) @ApiParam("警号") String policeNum) {
SysUser sysUser = sysUserService.selectUserByUserName(policeNum);
if (sysUser == null){
return AjaxResult.error("用户不存在,请联系管理员");
}
String mobiles = sysUser.getPhonenumber();
if (mobiles == null){
return AjaxResult.error("用户手机号缺失,请联系管理员");
}
RedisCache bean = SpringUtils.getBean(RedisCache.class);
SwtMsgVO msgVO = bean.getCacheObject(SWT_KEY + policeNum);
if (msgVO != null) {
Long oldTime = msgVO.getTime();
Long nowTime = System.currentTimeMillis()/1000;
if((nowTime - oldTime) < 10){
return AjaxResult.error("请勿频繁点击");
}
}
String capcha = getCapcha();
String msg = "【射阳公安局一体化工作平台】用户登录验证码:" + capcha + "";
String swtAppToken = SwtToken.getSwtAppToken();
String staffIdByPhone = SwtToken.getStaffIdByPhone(mobiles, swtAppToken);
BaseFlowLog baseFlowLog = SwtMessage.sendMessage(swtAppToken, staffIdByPhone, msg, "登录验证苏网通信息", mobiles, "");
baseFlowLogService.save(baseFlowLog);
SwtMsgVO swtMsgVO = new SwtMsgVO();
swtMsgVO.setMsg(capcha);
swtMsgVO.setPhone(policeNum);
swtMsgVO.setTime(System.currentTimeMillis() / 1000L);
swtMsgVO.setContent(msg);
bean.setCacheObject(SWT_KEY + policeNum,swtMsgVO,10, TimeUnit.MINUTES);
return AjaxResult.success("信息发送成功");
}
public String getCapcha() {
Random random = new Random();
int captcha = random.nextInt(900000) + 100000;
return StringKit.toString(captcha);
}
}

View File

@ -0,0 +1,149 @@
package com.ruoyi.business.common;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.business.util.ConfigParam;
import com.ruoyi.business.util.StringKit;
import com.ruoyi.cache.SmsCache;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.database.domain.vo.SmsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* @Auther: cyFeng
* @Date: 2024/4/24 17:57
* @Description:
*/
@Api(tags = "短信验证码")
@RestController
@RequestMapping("/base/sendMes")
public class sendMes {
String auth_code = ConfigParam.auth_code;
String spid = ConfigParam.spid;
String smsid = ConfigParam.smsid;
String auth_key = ConfigParam.auth_key;
String extport = "";
String sendtime = "";
String timestamp = System.currentTimeMillis() + "";
@GetMapping
@ApiOperation("获取短信验证码")
public R getMes(@RequestParam(required = false) @ApiParam("手机号") String mobiles) {
String msgVoStr = SmsCache.get(mobiles);
if (!"".equals(StringKit.toString(msgVoStr))) {
SmsVO msgVO = JSON.parseObject(msgVoStr, SmsVO.class, Feature.IgnoreNotMatch);
Long oldTime = msgVO.getTime();
Long nowTime = System.currentTimeMillis()/1000;
if((nowTime - oldTime) < 60){
return R.fail("请勿频繁点击");
}
}
String message = getMessage(mobiles);
if (!"1".equals(message)) {
return R.fail("短信发送失败");
}
return R.ok("短信发送成功");
}
public String getSHA(String mobiles, String content) {
try {
String str = auth_code + spid + extport + smsid + mobiles + sendtime + URLEncoder.encode(content, "utf-8") + timestamp + auth_key;
MessageDigest digest = MessageDigest
.getInstance("SHA");
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public String getMessage(String mobiles) {
try {
String captcha = getCapcha();
String content ="【浦星科技】本次登录验证码为" + captcha;
String sign = getSHA(mobiles, content);
// System.out.println(content);
String urlString = "https://swdxzdzh.cn:7443/receive/SMSController/sendSms";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(urlString);
Map<String, Object> params = new HashMap<>();
params.put("auth_code", auth_code);
params.put("spid", spid);
params.put("extport", extport);
params.put("smsid", smsid);
params.put("mobiles", mobiles);
params.put("sendtime", sendtime);
params.put("content", content);
params.put("timestamp", timestamp);
params.put("auth_key", auth_key);
params.put("sign", sign);
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(params);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
SmsVO msgVO = new SmsVO();
msgVO.setMsg(captcha);
msgVO.setContent(content);
msgVO.setPhone(mobiles);
msgVO.setTime(System.currentTimeMillis()/1000);
SmsCache.put(msgVO);
return new JSONObject(responseString).getStr("code");
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public String getCapcha() {
Random random = new Random();
int captcha = random.nextInt(900000) + 100000;
return StringKit.toString(captcha);
}
}

View File

@ -0,0 +1,19 @@
package com.ruoyi.business.util;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
public class ConfigParam {
public static String seq = File.separator;
public static String auth_code = StringKit.toString(PropertiesUtil.queryPropertiesByKey("auth_code"));
public static String spid = StringKit.toString(PropertiesUtil.queryPropertiesByKey("spid"));
public static String smsid = StringKit.toString(PropertiesUtil.queryPropertiesByKey("smsid"));
public static String auth_key = StringKit.toString(PropertiesUtil.queryPropertiesByKey("auth_key"));
}

View File

@ -0,0 +1,218 @@
package com.ruoyi.business.util;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Month;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;
/**
* 时间工具类
*
* @author ruoyi
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate()
{
return new Date();
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate()
{
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime()
{
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow()
{
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format)
{
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date)
{
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date)
{
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts)
{
try
{
return new SimpleDateFormat(format).parse(ts);
}
catch (ParseException e)
{
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年// 如2018/08/08
*/
public static final String datePath()
{
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年// 如20180808
*/
public static final String dateTime()
{
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str)
{
if (str == null)
{
return null;
}
try
{
return parseDate(str.toString(), parsePatterns);
}
catch (ParseException e)
{
return null;
}
}
/**
* 获取服务器启动时间
*/
public static Date getServerStartDate()
{
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
* 计算相差天数
*/
public static int differentDaysByMillisecond(Date date1, Date date2)
{
return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
}
/**
* 计算时间差
*
* @param endDate 最后时间
* @param startTime 开始时间
* @return 时间差/小时/分钟
*/
public static String timeDistance(Date endDate, Date startTime)
{
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - startTime.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "" + hour + "小时" + min + "分钟";
}
/**
* 增加 LocalDateTime ==> Date
*/
public static Date toDate(LocalDateTime temporalAccessor)
{
ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
/**
* 增加 LocalDate ==> Date
*/
public static Date toDate(LocalDate temporalAccessor)
{
LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zdt.toInstant());
}
public static List<String> getLastNMonths(int n) {
List<String> res = new LinkedList<>();
for (int i = n - 1; i >= 0; i--) {
// 计算每个月的日期
Month month = DateUtil.offsetMonth(DateUtil.date(), -i).monthEnum();
// 使用偏移后的日期进行格式化
String formattedMonth = DateUtil.offsetMonth(DateUtil.date(), -i)
.toString(DatePattern.NORM_MONTH_PATTERN);
// 将月份和格式化的月份放入映射中
res.add( formattedMonth);
}
return res;
}
public static void main(String[] args) {
int n = 10; // 你想要获取的月份数量
List< String> monthMap = getLastNMonths(n);
// 输出月份和格式化的月份
monthMap.forEach((month) ->
System.out.println(month ));
}
}

View File

@ -0,0 +1,131 @@
package com.ruoyi.business.util;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
public class JsoupUtils {
private static final Logger log = LoggerFactory.getLogger(JsoupUtils.class);
public static String getJsoupDocGet(String url) {
final int MAX_RETRIES = 10;
int retries = 0;
Document doc = null;
try {
URL parsedUrl = new URL(url);
String host = parsedUrl.getHost(); // 获取主机名
while (retries < MAX_RETRIES) {
try {
doc = Jsoup.connect(url)
.ignoreContentType(true)
.ignoreHttpErrors(true)
.timeout(1000 * 30)
.header("Host", host) // 使用正确的主机名
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
.header("Accept-Encoding", "gzip, deflate")
.header("Accept-Language", "zh-CN,zh;q=0.9")
.header("Cache-Control", "max-age=0")
.header("Connection", "keep-alive")
.header("Upgrade-Insecure-Requests", "1")
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36")
.get();
String text = doc.text();
if (text.contains("illegal")) {
return "";
} else {
return text;
}
} catch (Exception e) {
log.info("Failed to retrieve document from URL: " + url + ". Retrying... (" + (retries + 1) + "/" + MAX_RETRIES + ")", e);
retries++;
if (retries >= MAX_RETRIES) {
throw new RuntimeException("Failed to retrieve document after " + MAX_RETRIES + " retries.", e);
}
}
}
} catch (MalformedURLException e) {
log.error("Invalid URL: " + url, e);
return "";
}
return ""; // 理论上不应该到达这里但保持代码的完整性
}
//将文件传入 post请求中
public static String doPostFileRequest(String url, Map<String, String> param, InputStream fis, String fileName) throws Exception {
try {
Connection conn = Jsoup.connect(url);
if (param != null) {
conn.data(param);
}
conn.data("imagefile", fileName, fis);
Connection.Response response = conn.timeout(50000)
.ignoreContentType(true)
.maxBodySize(0)
.followRedirects(true)
.method(Connection.Method.POST).execute();
return response.body();
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* post 请求通用入口
*
* @param url
* @param map
* @return
*/
public static String jsoupPost(String url, Map<String, Object> map, String json) {
String res = "";
try {
Connection con = Jsoup.connect(url);
con.requestBody(json);
con.header("Content-Type", "application/json");
con.ignoreContentType(true);
Document doc = con.timeout(50000).post();
res = doc.text();
} catch (Exception e) {
log.info(StringKit.getTrace(e));
}
return res;
}
public static String jsoupPost(String url, Map<String, Object> map) {
String res = "";
try {
Connection con = Jsoup.connect(url);
if (map != null && map.size() > 0) {
Set<String> sets = map.keySet();
for (String s : sets) {
con.data(s, StringKit.toString(map.get(s)));
}
}
con.ignoreContentType(true);
Document doc =
con.timeout(50000)
.post();
res = doc.text();
} catch (Exception e) {
log.info(StringKit.getTrace(e));
}
return res;
}
}

View File

@ -0,0 +1,51 @@
package com.ruoyi.business.util;
import java.math.BigDecimal;
public class NumKit {
public NumKit() {
}
public static Double checkDouble(String num) {
try {
Double i = Double.valueOf(num);
return i;
} catch (Exception var3) {
}
return 0D;
}
public static Integer checkInt(String num) {
try {
Integer i = Integer.valueOf(num);
return i;
} catch (Exception var3) {
}
return 0;
}
public static Long checkLong(String num) {
try {
Long i = Long.valueOf(num);
return i;
} catch (Exception var3) {
}
return 0L;
}
public static BigDecimal checkBigDecimal(String num) {
try {
BigDecimal bd = new BigDecimal(num);
return bd;
} catch (Exception var3) {
}
return null;
}
}

View File

@ -0,0 +1,43 @@
package com.ruoyi.business.util;
import java.util.*;
/**
* OrderedProperties
*
* @author Unmi
* @date 2012-12-07
*/
public class OrderedProperties extends Properties {
private static final long serialVersionUID = -4627607243846121965L;
private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();
@Override
public Enumeration<Object> keys() {
return Collections.<Object>enumeration(keys);
}
@Override
public Object put(Object key, Object value) {
keys.add(key);
return super.put(key, value);
}
@Override
public Set<Object> keySet() {
return keys;
}
@Override
public Set<String> stringPropertyNames() {
Set<String> set = new LinkedHashSet<String>();
for (Object key : this.keys) {
set.add((String) key);
}
return set;
}
}

View File

@ -0,0 +1,189 @@
package com.ruoyi.business.util;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 读取Properties综合类,默认绑定到classpath下的config.properties文件
*
* @author 朱志杰 QQ:695520848
*/
public class PropertiesUtil {
//配置文件的路径
private String configPath = "config" + File.separator + "application.properties";
public static final String Path = "config" + File.separator + "application.properties";
/**
* 配置文件对象
*/
private Properties props = null;
/**
* 默认构造函数用于sh运行自动找到classpath下的config.properties
*/
public PropertiesUtil() throws IOException {
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties");
props = new Properties();
props.load(in);
//关闭资源
in.close();
}
/**
* 根据key值读取配置的值
* Jun 26, 2010 9:15:43 PM
*
* @param key key值
* @return key 键对应的值
* @throws IOException
* @author 朱志杰
*/
public String readValue(String key) throws IOException {
return props.getProperty(key);
}
/**
* 读取properties的全部信息
* Jun 26, 2010 9:21:01 PM
*
* @throws FileNotFoundException 配置文件没有找到
* @throws IOException 关闭资源文件或者加载配置文件错误
* @author 朱志杰
*/
public Map<String, String> readAllProperties() throws FileNotFoundException, IOException {
//保存所有的键值
Map<String, String> map = new HashMap<String, String>();
Enumeration en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String Property = props.getProperty(key);
map.put(key, Property);
}
return map;
}
/**
* 设置某个key的值,并保存至文件
* Jun 26, 2010 9:15:43 PM
*
* @param key key值
* @return key 键对应的值
* @throws IOException
* @author 朱志杰
*/
public void setValue(String key, String value) throws IOException {
Properties prop = new Properties();
InputStream fis = new FileInputStream(this.configPath);
// 从输入流中读取属性列表键和元素对
prop.load(fis);
// 调用 Hashtable 的方法 put使用 getProperty 方法提供并行性
// 强制要求为属性的键和值使用字符串返回值是 Hashtable 调用 put 的结果
OutputStream fos = new FileOutputStream(this.configPath);
prop.setProperty(key, value);
// 以适合使用 load 方法加载到 Properties 表中的格式
// 将此 Properties 表中的属性列表键和元素对写入输出流
prop.store(fos, "last update");
//关闭文件
fis.close();
fos.close();
}
/**
* 读取配置文件中key的对应值
*
* @param key
* @return
*/
public static String queryPropertiesByKey(String key) {
if ("".equals(StringKit.toString(key))) {
return "";
}
Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(Path));
properties.load(bufferedReader);
String rel = properties.getProperty(key);
bufferedReader.close();
// 获取key对应的value值
return rel;
} catch (IOException e) {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
}
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return "";
}
/**
* 设置配置文件key的value值
*
* @param key
* @param value
*/
public static void setPropertiesByKey(String key, String value) {
File file = new File(Path);
OrderedProperties properties = new OrderedProperties();
try {
properties.load(new FileInputStream(file));
properties.setProperty(key, value);
//true表示追加打开
FileOutputStream oFile = new FileOutputStream(Path);
properties.store(oFile, "The New properties file");
oFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取配置文件中key的对应值
*
* @param key
* @return
*/
public static String queryValue(String key) {
if ("".equals(StringKit.toString(key))) {
return "";
}
Properties properties = new Properties();
BufferedReader bufferedReader = null;
String rel = "";
try {
bufferedReader = new BufferedReader(new FileReader(Path));
properties.load(bufferedReader);
rel = StringKit.toString(properties.getProperty(key));
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return rel;
}
}

View File

@ -0,0 +1,122 @@
package com.ruoyi.business.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringKit {
public StringKit() {
}
public static Boolean isEmpty(Object argObject) {
Boolean tbool = false;
String tString = toString(argObject);
if (tString.equals("")) {
tbool = true;
}
return tbool;
}
public static String toString(Object argObject) {
String tmpstr = "";
try {
if (argObject != null) {
tmpstr = argObject.toString();
if ("null".equals(tmpstr) || "underfind".equals(tmpstr) || "undefined".equals(tmpstr) || "{}".equals(tmpstr)) {
tmpstr = "";
}
}
} catch (Exception var3) {
}
return tmpstr;
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
public static boolean isEng(String str) {
Pattern pattern = Pattern.compile("[a-zA-Z]");
return pattern.matcher(str).matches();
}
public static String getTrace(Throwable t) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer = stringWriter.getBuffer();
return buffer.toString();
}
/**
* 空时 返回NA(有的厂家字段必填我们没有先用NA补充)
*
* @return
*/
public static String responseNa(Object object) {
if (isEmpty(object)) {
return "NA";
}
return String.valueOf(object);
}
/**
* 检查某个字符串出现几次
*
* @return
*/
public static Integer getStrCount(String str, String indexStr) {
//java中判断一个字符出现的次数
//在下面字符串中查找有几个啊
// String str = "啊!我爱你中国!啊,我爱你故乡";
//存放每个字符的数组
String[] strs = new String[str.length()];
//计数该字符出现了多少次
int count = 0;
//先把字符串转换成数组
for (int i = 0; i < strs.length; i++) {
strs[i] = str.substring(i, i + 1);
}
//挨个字符进行查找查找到之后count++
for (int i = 0; i < strs.length; i++) {
if (strs[i].equals(indexStr)) {
count++;
}
}
// System.out.println("一共有"+count+"个啊");
return count;
}
public static Map<String, String> parse(String input) {
Map<String, String> result = new HashMap<>();
// 定义正则表达式
String regex = "(\\w+)=\"([^\"]*)\"";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// 使用正则表达式进行匹配
while (matcher.find()) {
// 提取键值对
String key = matcher.group(1);
String value = matcher.group(2);
result.put(key, value);
}
return result;
}
}

View File

@ -0,0 +1,183 @@
package com.ruoyi.business.util;
import cn.hutool.json.JSONObject;
import com.ruoyi.database.domain.BaseFlowLog;
import lombok.RequiredArgsConstructor;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RequiredArgsConstructor
public class SwtMessage {
protected static final Logger logger = LoggerFactory.getLogger(SwtMessage.class);
// private static final String messageContent = ConfigParam.MessageContent;
private static final String messageUrl = "http://50.16.172.231:80/open/apigw/v1/messages/create";
public static void sendMessage(String appToken,String staffId,String messageContent){
// 目标URL
String url = messageUrl + "?app_token=" + appToken;
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{\"userIdList\": [ \"")
.append(staffId)
.append("\" ],")
.append("\"msgType\": \"text\",")
.append("\"msgData\": {")
.append("\"text\": {")
.append("\"content\": \"")
.append(messageContent)
.append("\"}")
.append("}}");
String json = jsonBuilder.toString();
logger.info("Sending request with JSON: {}", json);
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 创建StringEntity对象将JSON字符串设置为请求体
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 读取响应内容
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("Response: {}", responseString);
}
} catch (Exception e) {
logger.error("Error sending message", e);
}
}
public static BaseFlowLog sendMessage(String appToken,String staffId,String messageContent,String operName,String receiveName,String taskId){
// 目标URL
String url = messageUrl + "?app_token=" + appToken;
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{\"userIdList\": [ \"")
.append(staffId)
.append("\" ],")
.append("\"msgType\": \"text\",")
.append("\"msgData\": {")
.append("\"text\": {")
.append("\"content\": \"")
.append(messageContent)
.append("\"}")
.append("}}");
String json = jsonBuilder.toString();
logger.info("Sending request with JSON: {}", json);
String responseString = "";
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 创建StringEntity对象将JSON字符串设置为请求体
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 读取响应内容
responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("Response: {}", responseString);
}
} catch (Exception e) {
responseString = e.toString();
logger.error("Error sending message", e);
}
//发送日志
BaseFlowLog baseFlowLog = new BaseFlowLog();
baseFlowLog.setOperName(operName);
baseFlowLog.setOperTime(System.currentTimeMillis()/1000L);
baseFlowLog.setReceiveName(receiveName);
baseFlowLog.setSendType(1);
baseFlowLog.setSendContent(messageContent);
baseFlowLog.setSendId(taskId);
JSONObject jsonObject = new JSONObject(responseString);
String errMsg = jsonObject.getStr("errMsg");
if ("ok".equals(errMsg)){
baseFlowLog.setSendStatus(1);
baseFlowLog.setSendResult(1);
baseFlowLog.setErrReason("");
}else {
baseFlowLog.setSendStatus(2);
baseFlowLog.setSendResult(2);
baseFlowLog.setErrReason(errMsg);
}
return baseFlowLog;
}
public static void sendMessageNoLog(String appToken,String staffId,String messageContent){
// 目标URL
String url = messageUrl + "?app_token=" + appToken;
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{\"userIdList\": [ \"")
.append(staffId)
.append("\" ],")
.append("\"msgType\": \"text\",")
.append("\"msgData\": {")
.append("\"text\": {")
.append("\"content\": \"")
.append(messageContent)
.append("\"}")
.append("}}");
String json = jsonBuilder.toString();
logger.info("Sending request with JSON: {}", json);
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 创建StringEntity对象将JSON字符串设置为请求体
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 读取响应内容
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
logger.info("Response: {}", responseString);
}
} catch (Exception e) {
logger.error("Error sending message", e);
}
}
public static void goMsg(String messageContent,String phone){
String swtAppToken = SwtToken.getSwtAppToken();
String staffIdByPhone = SwtToken.getStaffIdByPhone(phone, swtAppToken);
sendMessageNoLog(swtAppToken,staffIdByPhone,messageContent);
}
}

View File

@ -0,0 +1,52 @@
package com.ruoyi.business.util;
import cn.hutool.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SwtToken {
private static final String appid = "1048576-3350528";
private static final String secret = "9922B9D6638BC6F1824D1DA461B1DED0";
private static final String grantType = "client_credential";
private static final String orgId = "1048576";
private static final String idType = "mobile";
private static final String appTokenUrl = "http://50.16.172.231:80/open/apigw/v1/apptoken/create";
private static final String staffIdUrl = "http://50.16.172.231:80/open/apigw/v2/staffs/id_mapping/fetch";
private static final Logger logger = LoggerFactory.getLogger(SwtToken.class);
public static String getSwtAppToken(){
String url = appTokenUrl + "?grant_type=" + grantType + "&appid=" + appid + "&secret=" + secret;
String resText = JsoupUtils.getJsoupDocGet(url);
logger.info("苏网通" + resText);
JSONObject jsonObject = new JSONObject(resText);
JSONObject dataObject = jsonObject.getJSONObject("data");
String appToken = dataObject.getStr("app_token");
return appToken;
}
public static String getStaffIdByPhone(String phone,String appToken){
String url = staffIdUrl + "?app_token=" + appToken +
"&org_id=" + orgId + "&id_type=" + idType + "&id_value=86-" + phone;
String resText = JsoupUtils.getJsoupDocGet(url);
JSONObject jsonObject = new JSONObject(resText);
JSONObject dataObject = jsonObject.getJSONObject("data");
if (dataObject != null) {
String staffId = dataObject.getStr("staffId");
return staffId;
}
return "";
}
}

View File

@ -0,0 +1,133 @@
package com.ruoyi.business.util;
import cn.hutool.json.JSONObject;
import com.ruoyi.database.domain.BaseFlowLog;
import lombok.RequiredArgsConstructor;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
@RequiredArgsConstructor
public class SySMS {
protected static final Logger logger = LoggerFactory.getLogger(SySMS.class);
public static BaseFlowLog sendMessage(String phone, String time, String messageContent,String operName,String receiveName,String taskId){
// 目标URL
String url = "http://50.146.63.43:9605/sendSms/send";
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{")
.append("\"extcode\": \"12\",")
.append("\"destaddr\": \"" + phone + "\",")
.append("\"messagecontent\": \"" + messageContent + "\",")
.append("\"reqdeliveryreport\": \"1\",")
.append("\"msgfmt\": \"0\",")
.append("\"sendmethod\": \"0\",")
.append("\"requesttime\": \"" + time + "\",")
.append("\"applicationid\": \"P000000000000083\"")
.append("}");
String json = jsonBuilder.toString();
logger.info("Sending request with JSON: {}", json);
String responseString = "";
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 创建StringEntity对象将JSON字符串设置为请求体
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 读取响应内容
responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
// logger.info("Response: {}", responseString);
}
} catch (Exception e) {
responseString = e.toString();
// logger.error("Error sending message", e);
}
//发送日志
BaseFlowLog baseFlowLog = new BaseFlowLog();
baseFlowLog.setOperName(operName);
baseFlowLog.setOperTime(System.currentTimeMillis()/1000L);
baseFlowLog.setReceiveName(receiveName);
baseFlowLog.setSendType(2);
baseFlowLog.setSendContent(messageContent);
baseFlowLog.setSendId(taskId);
JSONObject jsonObject = new JSONObject(responseString);
String errMsg = jsonObject.getStr("msg");
if ("操作成功".equals(errMsg)){
baseFlowLog.setSendStatus(1);
baseFlowLog.setSendResult(0);
baseFlowLog.setErrReason("");
baseFlowLog.setSmsId(jsonObject.getStr("data"));
}else {
baseFlowLog.setSendStatus(2);
baseFlowLog.setSendResult(0);
baseFlowLog.setErrReason("接口未调通");
}
return baseFlowLog;
}
public static Map<String,String> sendMesStatus(String smsid) {
// 目标URL
String url = "http://50.146.63.43:9605/sendSms/getSmsStatus";
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.append("{")
.append("\"sismsid\": \"" + smsid + "\"")
.append("}");
String json = jsonBuilder.toString();
// logger.info("Sending request with JSON: {}", json);
String responseString = "";
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 创建StringEntity对象将JSON字符串设置为请求体
StringEntity entity = new StringEntity(json, "UTF-8");
httpPost.setEntity(entity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 读取响应内容
responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
// logger.info("Response: {}", responseString);
}
} catch (Exception e) {
// logger.error("Error sending message", e);
}
Map<String, String> map = new HashMap<>();
JSONObject jsonObject = new JSONObject(responseString);
JSONObject object = jsonObject.getJSONObject("data");
if (object == null){
return map;
}
String sentresult = object.getStr("sentresult");
String smsstatus = object.getStr("smsstatus");
map.put("sentresult",sentresult);
map.put("smsstatus",smsstatus);
return map;
}
}

View File

@ -0,0 +1,24 @@
package com.ruoyi.cache;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ApplyNumCache {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
private static final String APPLY_NUM_KEY = "APPLY_NUM_KEY:";
public static String getApplyNumKey() {
String currentDate = dateFormat.format(new Date());
RedisCache bean = SpringUtils.getBean(RedisCache.class);
bean.setCacheObject(APPLY_NUM_KEY + currentDate,
bean.getCacheObject(APPLY_NUM_KEY + currentDate) == null
? 1 : (Integer)(bean.getCacheObject(APPLY_NUM_KEY + currentDate)) + 1);
return currentDate + String.format("%04d", (Integer)(bean.getCacheObject(APPLY_NUM_KEY + currentDate)));
}
}

View File

@ -0,0 +1,67 @@
//package com.ruoyi.cache;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.github.benmanes.caffeine.cache.Cache;
//import com.github.benmanes.caffeine.cache.Caffeine;
//import com.ruoyi.business.util.StringKit;
//import com.ruoyi.database.domain.SystemAreacodeInfo;
//import com.ruoyi.database.service.SystemAreacodeInfoService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
///**
// * 区域缓存
// *
// * @author 戴鹏涛
// * @since 2023-09-16 11:04
// */
//@Component
//public class AreaCache {
//
// /**
// * key: areaNamevalue: subAreaCode; 北京市110000000000
// */
// private static final Cache<String, String> cache = Caffeine.newBuilder().build();
//
// private static SystemAreacodeInfoService systemAreacodeInfoService;
//
// @Autowired
// AreaCache(SystemAreacodeInfoService systemAreacodeInfoService) {
// AreaCache.systemAreacodeInfoService = systemAreacodeInfoService;
// //初始化
// load();
// }
//
// public static String get(String key) {
// return cache.get(key, s -> {
// try {
// return String.valueOf(systemAreacodeInfoService.getOne(new LambdaQueryWrapper<SystemAreacodeInfo>().eq(SystemAreacodeInfo::getSubAreaCode, key)).getAreaName());
// } catch (Exception e) {
// return "";
// }
// });
// }
//
// /**
// * 缓存刷新
// */
// @Scheduled(cron = "0 0 3 * * ?")
// public static void refresh() {
// load();
// }
//
// private static void load() {
// List<SystemAreacodeInfo> list = systemAreacodeInfoService.list();
// Map<String, String> dictMap = list.stream().collect(Collectors.toMap(SystemAreacodeInfo::getAreaName, e -> String.valueOf(e.getSubAreaCode()), (v1, v2) -> v2));
// Map<String, String> dictMapCode = list.stream().collect(Collectors.toMap(
// e -> e.getSubAreaCode().toString(),
// e -> String.valueOf(e.getAreaName()), (v1, v2) -> v2));
// cache.putAll(dictMap);
// cache.putAll(dictMapCode);
// }
//}

View File

@ -0,0 +1,91 @@
package com.ruoyi.cache;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ruoyi.database.domain.SysDictDataMp;
import com.ruoyi.database.service.SysDictDataMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 字典缓存
*
* @author 戴鹏涛
* @since 2023-09-13 15:40:44
*/
@Component
public class DictCache {
/**
* key: dictType-dictValuevalue: dictLabel; place_category-1居民小区
* key: dictType-dictLabelvalue: dictValue; place_category-居民小区1
*/
private static final Cache<String, String> cache = Caffeine.newBuilder().build();
private static SysDictDataMpService sysDictDataMpService;
@Autowired
DictCache(SysDictDataMpService sysDictDataMpService) {
DictCache.sysDictDataMpService = sysDictDataMpService;
//初始化
DictLabelLoad();
DictValueLoad();
}
public static String getDictLabel(String key) {
return cache.get(key, s -> {
try {
List<String> split = StrUtil.split(key, "-");
String dictType = split.get(0);
String dictValue = split.get(1);
return sysDictDataMpService.getOne(new LambdaQueryWrapper<SysDictDataMp>()
.eq(SysDictDataMp::getDictType, dictType)
.eq(SysDictDataMp::getDictValue, dictValue)).getDictLabel();
} catch (Exception e) {
return "";
}
});
}
public static String getDictValue(String key) {
return cache.get(key, s -> {
try {
List<String> split = StrUtil.split(key, "-");
String dictType = split.get(0);
String dictLabel = split.get(1);
return sysDictDataMpService.getOne(new LambdaQueryWrapper<SysDictDataMp>()
.eq(SysDictDataMp::getDictType, dictType)
.eq(SysDictDataMp::getDictLabel, dictLabel)).getDictValue();
} catch (Exception e) {
return "";
}
});
}
/**
* 缓存刷新
*/
@Scheduled(cron = "0 0 3 * * ?")
public static void refresh() {
DictLabelLoad();
DictValueLoad();
}
private static void DictLabelLoad() {
List<SysDictDataMp> list = sysDictDataMpService.list();
Map<String, String> dictMap = list.stream().collect(Collectors.toMap(e -> StrUtil.format("{}-{}", e.getDictType(), e.getDictValue()), SysDictDataMp::getDictLabel, (v1, v2) -> v2));
cache.putAll(dictMap);
}
private static void DictValueLoad() {
List<SysDictDataMp> list = sysDictDataMpService.list();
Map<String, String> dictMap = list.stream().collect(Collectors.toMap(e -> StrUtil.format("{}-{}", e.getDictType(), e.getDictLabel()), SysDictDataMp::getDictValue, (v1, v2) -> v2));
cache.putAll(dictMap);
}
}

View File

@ -0,0 +1,34 @@
package com.ruoyi.cache;
import com.alibaba.fastjson2.JSON;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ruoyi.database.domain.vo.SmsVO;
import org.springframework.stereotype.Component;
/**
* 验证码缓存
*/
@Component
public class SmsCache {
/**
* key: phone
*/
private static final Cache<String, String> cache = Caffeine.newBuilder().build();
public static void put(SmsVO bean) {
cache.put(bean.getPhone(), JSON.toJSONString(bean));
}
public static String get(String key) {
return cache.get(key, s -> {
try {
return "";
} catch (Exception e) {
return "";
}
});
}
}

View File

@ -0,0 +1,24 @@
package com.ruoyi.cache;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class VarietyNumCache {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
private static final String VARIETY_NUM_KEY = "VARIETY_NUM_KEY:";
public static String getVarietyNumKey() {
String currentDate = dateFormat.format(new Date());
RedisCache bean = SpringUtils.getBean(RedisCache.class);
bean.setCacheObject(VARIETY_NUM_KEY + currentDate,
bean.getCacheObject(VARIETY_NUM_KEY + currentDate) == null
? 1 : (Integer)(bean.getCacheObject(VARIETY_NUM_KEY + currentDate)) + 1);
return currentDate + String.format("%03d", (Integer)(bean.getCacheObject(VARIETY_NUM_KEY + currentDate)));
}
}

View File

@ -0,0 +1,139 @@
package com.ruoyi.database.domain;
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 流程日志记录(BaseFlowLog)实体类
*
* @author makejava
* @since 2024-09-02 15:36:53
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName(value = "base_flow_log")
@ApiModel(value = "BaseFlowLog", description = "流程日志记录")
public class BaseFlowLog extends BaseEntity {
/**
* 主键
*/
@ApiModelProperty("主键")
@Excel(name = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/** 创建者 */
@ApiModelProperty("创建者")
private String createBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("创建时间")
private Date createTime;
/** 更新者 */
@ApiModelProperty("更新者")
private String updateBy;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("更新时间")
private Date updateTime;
/**
* 操作人
*/
@ApiModelProperty("操作人")
@Excel(name = "操作人")
@TableField(condition = SqlCondition.LIKE)
private String operName;
/**
* 发送时间
*/
@ApiModelProperty("发送时间")
@Excel(name = "发送时间")
private Long operTime;
@TableField(exist = false)
private String operTimeCn;
/**
* 接收人
*/
@ApiModelProperty("接收人")
@Excel(name = "接收人")
@TableField(condition = SqlCondition.LIKE)
private String receiveName;
/**
* 发送方式
*/
@ApiModelProperty("发送方式")
@Excel(name = "发送方式")
private Integer sendType;
@TableField(exist = false)
private String sendTypeCn;
/**
* 发送状态
*/
@ApiModelProperty("发送状态")
@Excel(name = "发送状态")
private Integer sendStatus;
@TableField(exist = false)
private String sendStatusCn;
/**
* 发送内容
*/
@ApiModelProperty("发送内容")
@Excel(name = "发送内容")
private String sendContent;
/**
* 发送结果
*/
@ApiModelProperty("发送结果")
@Excel(name = "发送结果")
private Integer sendResult;
@TableField(exist = false)
private String sendResultCn;
/**
* 失败原因
*/
@ApiModelProperty("失败原因")
@Excel(name = "失败原因")
private String errReason;
/**
* 发送编号
*/
@ApiModelProperty("发送编号")
@Excel(name = "发送编号")
private String sendId;
@ApiModelProperty("短信id")
@Excel(name = "短信id")
private String smsId;
@TableField(exist = false)
private String firstTime;
@TableField(exist = false)
private String endTime;
}

View File

@ -0,0 +1,81 @@
package com.ruoyi.database.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 字典数据表(SysDictData)Domain
*
* @author 戴鹏涛
* @since 2023-09-14 12:03:14
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName(value = "sys_dict_data")
@ApiModel(value = "SysDictData", description = "字典数据表")
public class SysDictDataMp extends BaseEntity {
/** 主键 */
@ApiModelProperty("主键")
@TableId(value = "dict_code", type = IdType.AUTO)
private Long dictCode;
/** 字典排序 */
@ApiModelProperty("字典排序")
@Excel(name = "字典排序")
private Integer dictSort;
/** 字典标签 */
@ApiModelProperty("字典标签")
@Excel(name = "字典标签")
private String dictLabel;
/** 字典键值 */
@ApiModelProperty("字典键值")
@Excel(name = "字典键值")
private String dictValue;
/** 字典类型 */
@ApiModelProperty("字典类型")
@Excel(name = "字典类型")
private String dictType;
/** 样式属性(其他样式扩展) */
@ApiModelProperty("样式属性(其他样式扩展)")
@Excel(name = "样式属性(其他样式扩展)")
private String cssClass;
/** 表格回显样式 */
@ApiModelProperty("表格回显样式")
@Excel(name = "表格回显样式")
private String listClass;
/** 是否默认Y是 N否 */
@ApiModelProperty("是否默认Y是 N否")
@Excel(name = "是否默认Y是 N否")
private String isDefault;
/** 状态0正常 1停用 */
@ApiModelProperty("状态0正常 1停用")
@Excel(name = "状态0正常 1停用")
private String status;
/** 备注 */
@ApiModelProperty("备注")
@Excel(name = "备注")
private String remark;
/**
* 逻辑删除
*/
@ApiModelProperty("逻辑删除")
private Integer isDeleted;
}

View File

@ -0,0 +1,95 @@
package com.ruoyi.database.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class VehicleRequest {
@TableId(value = "id",type = IdType.AUTO)
private Long id;
@ApiModelProperty("申请单位")
private Long deptId;
@ApiModelProperty("申请单位名称")
private Long deptName;
@ApiModelProperty("申请人姓名")
private String appName;
@ApiModelProperty("申请人警号")
private String badgeNumber;
@ApiModelProperty("申请人联系方式")
private String appPhone;
@ApiModelProperty("申请日期")
@JsonFormat(pattern = "yyyy年MM月dd日")
private LocalDateTime appDate;
@ApiModelProperty("用车开始时间")
@JsonFormat(pattern = "yyyy年MM月dd日 HH:mm")
private LocalDateTime startTime;
@ApiModelProperty("用车结束时间")
@JsonFormat(pattern = "yyyy年MM月dd日 HH:mm")
private LocalDateTime endTime;
@ApiModelProperty("出县开始时间")
@JsonFormat(pattern = "yyyy年MM月dd日 HH:mm")
private LocalDateTime goTime;
@ApiModelProperty("出县结束时间")
@JsonFormat(pattern = "yyyy年MM月dd日 HH:mm")
private LocalDateTime backTime;
@ApiModelProperty("车牌号")
private String carNumber;
@ApiModelProperty("车型")
private String carType;
@ApiModelProperty("驾驶员id")
private String driverId;
@ApiModelProperty("驾驶员姓名")
private String driverName;
@ApiModelProperty("驾驶证号")
private String permitNumber;
@ApiModelProperty("目的地")
private String destination;
@ApiModelProperty("是否跨省")
private Integer crossProvinces;
@ApiModelProperty("路线规划")
private String routePlanning;
@ApiModelProperty("用车事由")
private String useCarReason;
@ApiModelProperty("携带物品")
private String carry;
@ApiModelProperty("涉密文件密级")
private String level;
@ApiModelProperty("份数")
private Integer number;
@ApiModelProperty("文件编号")
private String fileCode;
@ApiModelProperty("随行人员姓名")
private String entourage;
}

View File

@ -0,0 +1,25 @@
package com.ruoyi.database.domain.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 用户登录对象
*
* @author ruoyi
*/
@Data
public class LoginDto {
/**
* 用户名
*/
@ApiModelProperty("用户名:手机号")
private String username;
/**
* 验证码
*/
@ApiModelProperty("验证码")
private String code;
}

View File

@ -0,0 +1,19 @@
package com.ruoyi.database.domain.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class SMSLoginDto {
@ApiModelProperty("用户名:手机号")
private String phone;
@ApiModelProperty("验证码")
private String code;
@ApiModelProperty("类型 1:苏网通 2:短信")
private Integer type;
}

View File

@ -0,0 +1,12 @@
package com.ruoyi.database.domain.dto;
import lombok.Data;
@Data
public class auditDto {
private Long id;
private Integer state;
}

View File

@ -0,0 +1,32 @@
package com.ruoyi.database.domain.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class FillSheet1VO {
@ApiModelProperty("计划批次")
private String plannedBatchCn;
@ApiModelProperty("申领人")
private String name;
@ApiModelProperty("身份证")
private String idCard;
@ApiModelProperty("所属部门")
private String dept;
@ApiModelProperty("品种名称")
private String varietyName;
@ApiModelProperty("品种单价")
private Double unitPrice;
@ApiModelProperty("申领数")
private Integer num;
@ApiModelProperty("总金额")
private Double amt;
}

View File

@ -0,0 +1,23 @@
package com.ruoyi.database.domain.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class FillSheet2VO {
@ApiModelProperty("计划批次")
private String plannedBatchCn;
@ApiModelProperty("品种名称")
private String varietyName;
@ApiModelProperty("品种单价")
private Double unitPrice;
@ApiModelProperty("申领数")
private Integer num;
@ApiModelProperty("总金额")
private Double amt;
}

View File

@ -0,0 +1,13 @@
package com.ruoyi.database.domain.vo;
import lombok.Data;
@Data
public class InventoryVO {
private Long invId;
private String varietyName;
}

View File

@ -0,0 +1,20 @@
package com.ruoyi.database.domain.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class SMSMsgVO {
@ApiModelProperty("验证码")
private String msg;
@ApiModelProperty("手机号码")
private String phone;
@ApiModelProperty("发送时间")
private Long time;
@ApiModelProperty("短信内容")
private String content;
}

View File

@ -0,0 +1,23 @@
package com.ruoyi.database.domain.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(value = "PhoneMsgVO", description = "手机验证码实体")
public class SmsVO {
@ApiModelProperty("验证码")
private String msg;
@ApiModelProperty("手机号码")
private String phone;
@ApiModelProperty("发送时间")
private Long time;
@ApiModelProperty("短信内容")
private String content;
}

View File

@ -0,0 +1,20 @@
package com.ruoyi.database.domain.vo;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class SwtMsgVO {
@ApiModelProperty("验证码")
private String msg;
@ApiModelProperty("手机号码")
private String phone;
@ApiModelProperty("发送时间")
private Long time;
@ApiModelProperty("短信内容")
private String content;
}

View File

@ -0,0 +1,16 @@
package com.ruoyi.database.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.database.domain.BaseFlowLog;
import org.apache.ibatis.annotations.Mapper;
/**
* 流程日志记录(BaseFlowLog) Mapper 接口
*
* @author makejava
* @since ${date}
*/
@Mapper
public interface BaseFlowLogMapper extends BaseMapper<BaseFlowLog> {
}

View File

@ -0,0 +1,16 @@
package com.ruoyi.database.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.database.domain.SysDictDataMp;
import org.apache.ibatis.annotations.Mapper;
/**
* 字典数据表(SysDictData)Mapper
*
* @author 戴鹏涛
* @since 2023-09-14 12:03:14
*/
@Mapper
public interface SysDictDataMpMapper extends BaseMapper<SysDictDataMp> {
}

View File

@ -0,0 +1,17 @@
package com.ruoyi.database.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.database.domain.BaseFlowLog;
/**
* (流程日志记录)Service
*
* @author makejava
* @since 2024-09-02 15:36:54
*/
public interface BaseFlowLogService extends IService<BaseFlowLog> {
public void selectSMSStatus();
}

View File

@ -0,0 +1,14 @@
package com.ruoyi.database.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ruoyi.database.domain.SysDictDataMp;
/**
* 字典数据表(SysDictData)Service
*
* @author 戴鹏涛
* @since 2023-09-14 12:03:13
*/
public interface SysDictDataMpService extends IService<SysDictDataMp> {
}

View File

@ -0,0 +1,54 @@
package com.ruoyi.database.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.util.SySMS;
import com.ruoyi.database.domain.BaseFlowLog;
import com.ruoyi.database.mapper.BaseFlowLogMapper;
import com.ruoyi.database.service.BaseFlowLogService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* (流程日志记录)ServiceImpl
*
* @author makejava
* @since 2024-09-02 15:36:54
*/
@Service
public class BaseFlowLogServiceImpl extends ServiceImpl<BaseFlowLogMapper, BaseFlowLog> implements BaseFlowLogService {
@Override
public void selectSMSStatus() {
List<BaseFlowLog> list = lambdaQuery().eq(BaseFlowLog::getSendType, 2)
.eq(BaseFlowLog::getSendResult, 0)
.list();
for (BaseFlowLog baseFlowLog : list){
long time = System.currentTimeMillis() / 1000L;
long cTime = 60 * 15L;
if (time - baseFlowLog.getOperTime() > cTime){
baseFlowLog.setSendResult(2);
baseFlowLog.setErrReason("超时未反馈");
updateById(baseFlowLog);
}
String smsId = baseFlowLog.getSmsId();
if (!"".equals(smsId)){
Map<String, String> map = SySMS.sendMesStatus(smsId);
if (map.isEmpty()){
continue;
}
String sentresult = map.get("sentresult");
String smsstatus = map.get("smsstatus");
if ("3002".equals(sentresult)){
baseFlowLog.setSendResult(2);
baseFlowLog.setErrReason(smsstatus);
}else {
baseFlowLog.setSendResult(1);
}
}
updateById(baseFlowLog);
}
}
}

View File

@ -0,0 +1,18 @@
package com.ruoyi.database.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.database.domain.SysDictDataMp;
import com.ruoyi.database.mapper.SysDictDataMpMapper;
import com.ruoyi.database.service.SysDictDataMpService;
import org.springframework.stereotype.Service;
/**
* 字典数据表(SysDictData)ServiceImpl
*
* @author 戴鹏涛
* @since 2023-09-14 12:03:14
*/
@Service
public class SysDictDataMpServiceImpl extends ServiceImpl<SysDictDataMpMapper, SysDictDataMp> implements SysDictDataMpService {
}

View File

@ -0,0 +1,90 @@
package com.ruoyi.interceptor;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.cache.DictCache;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;
/**
* Mybatis字典拦截器
*
* @author 戴鹏涛
* @since 2023-09-14 9:16
*/
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DictionaryInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object result = invocation.proceed();
if (result instanceof List) {
List<?> resultList = (List<?>) result;
// 遍历查询结果集
for (Object obj : resultList) {
// 获取实体类类型
Class<?> entityClass = obj.getClass();
// 遍历实体类的字段
for (Field field : entityClass.getDeclaredFields()) {
// 判断字段是否为Integer类型
if (field.getType().equals(Integer.class)) {
field.setAccessible(true);
//将字段的值进行翻译并回显至对应的Cn字段
String fieldName = field.getName();
Object dictValue = field.get(obj);
String dictType = StrUtil.toUnderlineCase(fieldName);
String dictLabel = DictCache.getDictLabel(StrUtil.format("{}-{}", dictType, dictValue));
try {
ReflectUtil.setFieldValue(obj, fieldName + "Cn", dictLabel);
} catch (Exception ignored) {
}
}
// 判断字段名是否为passTime
if (StrUtil.equals(field.getName(), "passTime")) {
field.setAccessible(true);
Long passTime = (Long) field.get(obj);
try {
ReflectUtil.setFieldValue(obj, field.getName() + "Cn", DateUtil.format(DateUtil.date(passTime * 1000), DatePattern.NORM_DATETIME_PATTERN));
} catch (Exception ignored) {
}
}
if (StrUtil.endWith(field.getName(), "Time") && field.getType().equals(Long.class)) {
field.setAccessible(true);
field.setAccessible(true);
//将字段的值进行翻译并回显至对应的Cn字段
Object value = field.get(obj);
try {
String label = DateUtil.date((Long) value * 1000).toString(DatePattern.NORM_DATETIME_PATTERN);
ReflectUtil.setFieldValue(obj, field.getName() + "Cn", label);
} catch (Exception ignored) {
}
}
}
}
}
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}

226
pom.xml Normal file
View File

@ -0,0 +1,226 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ruoyi</groupId>
<artifactId>PublicAffairs</artifactId>
<version>4.0.0</version>
<name>ruoyi</name>
<description>被装管理</description>
<properties>
<ruoyi.version>4.0.0</ruoyi.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<druid.version>1.2.16</druid.version>
<bitwalker.version>1.21</bitwalker.version>
<swagger.version>3.0.0</swagger.version>
<kaptcha.version>2.3.3</kaptcha.version>
<pagehelper.boot.version>1.4.6</pagehelper.boot.version>
<fastjson.version>2.0.39</fastjson.version>
<oshi.version>6.4.4</oshi.version>
<commons.io.version>2.13.0</commons.io.version>
<commons.collections.version>3.2.2</commons.collections.version>
<poi.version>5.2.3</poi.version>
<velocity.version>2.3</velocity.version>
<jwt.version>0.9.1</jwt.version>
</properties>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.5.15</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>${bitwalker.version}</version>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.boot.version}</version>
</dependency>
<!-- 获取系统信息 -->
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>${oshi.version}</version>
</dependency>
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- velocity代码生成使用模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.version}</version>
</dependency>
<!-- collections工具类 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons.collections.version}</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!-- 验证码 -->
<dependency>
<groupId>pro.fessional</groupId>
<artifactId>kaptcha</artifactId>
<version>${kaptcha.version}</version>
</dependency>
<!-- 定时任务-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-quartz</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 系统模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-system</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId>
<version>${ruoyi.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<modules>
<module>ruoyi-admin</module>
<module>ruoyi-framework</module>
<module>ruoyi-system</module>
<module>ruoyi-quartz</module>
<module>ruoyi-generator</module>
<module>ruoyi-common</module>
<module>gather-app</module>
</modules>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

110
ruoyi-admin/pom.xml Normal file
View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>PublicAffairs</artifactId>
<groupId>com.ruoyi</groupId>
<version>4.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>ruoyi-admin</artifactId>
<description>
web服务入口
</description>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- 防止进入swagger页面报类型转换错误排除3.0.0中的引用手动增加1.6.2版本 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.2</version>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<!-- 定时任务-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-quartz</artifactId>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>ruoyi-generator</artifactId>
</dependency>
<!-- 业务-->
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>gather-app</artifactId>
<version>${ruoyi.version}</version>
</dependency>
<!-- knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.15</version>
<configuration>
<fork>true</fork> <!-- 如果没有该配置devtools不会生效 -->
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>

View File

@ -0,0 +1,30 @@
package com.ruoyi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* 场所管控 启动程序
*
* @author ruoyi
*/
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication
{
public static void main(String[] args)
{
// System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(RuoYiApplication.class, args);
System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" +
" .-------. ____ __ \n" +
" | _ _ \\ \\ \\ / / \n" +
" | ( ' ) | \\ _. / ' \n" +
" |(_ o _) / _( )_ .' \n" +
" | (_,_).' __ ___(_ o _)' \n" +
" | |\\ \\ | || |(_,_)' \n" +
" | | \\ `' /| `-' / \n" +
" | | \\ / \\ / \n" +
" ''-' `'-' `-..-' ");
}
}

View File

@ -0,0 +1,16 @@
package com.ruoyi;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* web容器中进行部署
*
* @author ruoyi
*/
public class RuoYiServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(RuoYiApplication.class);
}
}

View File

@ -0,0 +1,99 @@
package com.ruoyi.web.config;
import cn.hutool.core.date.LocalDateTimeUtil;
import org.springframework.context.annotation.Configuration;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
@Configuration
public class DateUtils extends LocalDateTimeUtil {
public static final String DEFAULT_YEAR_FORMAT = "yyyy";
public static final String DEFAULT_MONTH_FORMAT = "yyyy-MM";
public static final String DEFAULT_MONTH_FORMAT_SLASH = "yyyy/MM";
public static final String DEFAULT_MONTH_FORMAT_EN = "yyyy年MM月";
public static final String DEFAULT_MONTH_FORMAT_COMPACT = "yyyyMM";
public static final String DEFAULT_WEEK_FORMAT = "yyyy-ww";
public static final String DEFAULT_WEEK_FORMAT_EN = "yyyy年ww周";
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
public static final String DEFAULT_DATE_FORMAT_EN = "yyyy年MM月dd日";
public static final String DEFAULT_DATE_FORMAT_COMPACT = "yyyyMMdd";
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DEFAULT_DATE_TIME_COMPACT = "yyyyMMddHHmmss";
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
public static final String DATE_HOUR_FORMAT = "ddHH";
public static final String DAY = "DAY";
public static final String MONTH = "MONTH";
public static final String WEEK = "WEEK";
public static final long MAX_MONTH_DAY = 30L;
public static final long MAX_3_MONTH_DAY = 90L;
public static final long MAX_YEAR_DAY = 365L;
public static final DateTimeFormatter SIGN_DATE_SUFFIX_FORMATTER = DateTimeFormatter.ofPattern(":yyyyMM");
public static final DateTimeFormatter POINTS_BOARD_SUFFIX_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");
public static final String TIME_ZONE_8 = "GMT+8";
public DateUtils() {
}
public static LocalDateTime getUTCTime(LocalDateTime localDateTime) {
ZoneId australia = ZoneId.of("Asia/Shanghai");
ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localDateTime, australia);
ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(ZoneOffset.UTC);
return utcDate.toLocalDateTime();
}
public static LocalDateTime getAsiaTime(LocalDateTime localDateTime) {
ZoneId australia = ZoneId.of("Asia/Shanghai");
ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localDateTime, ZoneOffset.UTC);
ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(australia);
return utcDate.toLocalDateTime();
}
public static LocalDateTime getDayStartTime(LocalDateTime localDateTime) {
return localDateTime == null ? null : localDateTime.toLocalDate().atStartOfDay();
}
public static LocalDateTime getDayEndTime(LocalDateTime localDateTime) {
return localDateTime == null ? null : LocalDateTime.of(localDateTime.toLocalDate(), LocalTime.MAX);
}
public static Date addDays(int i) {
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
c.add(5, i);
return c.getTime();
}
public static LocalDate getMonthBegin(LocalDate date) {
return LocalDate.of(date.getYear(), date.getMonth(), 1);
}
public static LocalDate getMonthEnd(LocalDate date) {
return LocalDate.of(date.getYear(), date.getMonthValue() + 1, 1).minusDays(1L);
}
public static LocalDateTime getMonthBeginTime(LocalDate date) {
return LocalDate.of(date.getYear(), date.getMonth(), 1).atStartOfDay();
}
public static LocalDateTime getMonthEndTime(LocalDate date) {
return LocalDate.of(date.getYear(), date.getMonthValue() + 1, 1).minusDays(1L).atTime(LocalTime.MAX);
}
public static LocalDateTime getWeekBeginTime(LocalDate now) {
return now.minusDays((long)(now.getDayOfWeek().getValue() - 1)).atStartOfDay();
}
public static LocalDateTime getWeekEndTime(LocalDate now) {
return LocalDateTime.of(now.plusDays((long)(8 - now.getDayOfWeek().getValue())), LocalTime.MAX);
}
public static int getCurrentTime() {
return (int)(System.currentTimeMillis() / 1000L);
}
}

View File

@ -0,0 +1,32 @@
package com.ruoyi.web.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
public class UserContext {
private static final ThreadLocal<Long> TL = new ThreadLocal<>();
/**
* 保存用户信息
* @param userId 用户id
*/
public static void setUser(Long userId){
TL.set(userId);
}
/**
* 获取用户
* @return 用户id
*/
public static Long getUser(){
return TL.get();
}
/**
* 移除用户信息
*/
public static void removeUser(){
TL.remove();
}
}

View File

@ -0,0 +1,99 @@
package com.ruoyi.web.controller.common;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
/**
* 验证码操作处理
*
* @author ruoyi
*/
@Api(tags = "验证码操作处理")
@RestController
public class CaptchaController
{
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
@Autowired
private RedisCache redisCache;
@Autowired
private ISysConfigService configService;
/**
* 生成验证码
*/
@ApiOperation("captchaImage")
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException
{
AjaxResult ajax = AjaxResult.success();
boolean captchaEnabled = configService.selectCaptchaEnabled();
ajax.put("captchaEnabled", captchaEnabled);
if (!captchaEnabled)
{
return ajax;
}
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
String captchaType = RuoYiConfig.getCaptchaType();
if ("math".equals(captchaType))
{
String capText = captchaProducerMath.createText();
capStr = capText.substring(0, capText.lastIndexOf("@"));
code = capText.substring(capText.lastIndexOf("@") + 1);
image = captchaProducerMath.createImage(capStr);
}
else if ("char".equals(captchaType))
{
capStr = code = captchaProducer.createText();
image = captchaProducer.createImage(capStr);
}
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try
{
ImageIO.write(image, "jpg", os);
}
catch (IOException e)
{
return AjaxResult.error(e.getMessage());
}
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}
}

View File

@ -0,0 +1,180 @@
package com.ruoyi.web.controller.common;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
/**
* 通用请求处理
*
* @author ruoyi
*/
@Api(tags = "通用请求处理")
@RestController
@RequestMapping("/common")
public class CommonController {
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
@Autowired
private ServerConfig serverConfig;
private static final String FILE_DELIMETER = ",";
/**
* 通用下载请求
*
* @param fileName 文件名称
* @param delete 是否删除
*/
@GetMapping("/download")
@ApiOperation("通用下载请求")
public void fileDownload(@RequestParam @ApiParam("文件名") String fileName, @ApiParam("是否删除") Boolean delete, HttpServletResponse response, HttpServletRequest request) {
try {
if (!FileUtils.checkAllowDownload(fileName)) {
throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
String filePath = RuoYiConfig.getDownloadPath() + fileName;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
if (delete) {
FileUtils.deleteFile(filePath);
}
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
/**
* 通用上传请求单个
*/
@PostMapping("/upload")
@ApiOperation("通用上传请求(单个)")
public AjaxResult uploadFile( MultipartFile file) throws Exception {
try {
// 上传文件路径
// String filePath = RuoYiConfig.getUploadPathNew() + File.separator ;
// String filePathSend = RuoYiConfig.getUploadPathNewSend() + File.separator ;
// if(!"".equals(StringUtils.isNotBlank(fileType))){
// filePath = filePath + File.separator + fileType;
// filePathSend = filePathSend + File.separator + fileType;
// }
// File fileFolder = new File(filePath);
// if(!fileFolder.exists()){
// fileFolder.mkdirs();
// }
//
// File fileFolderSend = new File(filePathSend);
// if(!fileFolderSend.exists()){
// fileFolderSend.mkdirs();
// }
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
// String fileSendUrl = filePathSend +fileName;
// File fileOld = new File(filePath +File.separator+ fileName);
// File fileSend = new File(filePathSend+File.separator + fileName);
// Files.copy(fileOld.toPath(), fileSend.toPath());//复制文件
// String fileNameSend = FileUploadUtils.uploadNew(filePathSend, file);
// String url = serverConfig.getUrl() + fileName;
// String urlSend = filePathSend+ File.separator + fileSend.getName();
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
// ajax.put("urlSend", urlSend);
ajax.put("fileName", fileName);
// ajax.put("fileNameSend", fileSend.getName());
ajax.put("newFileName", FileUtils.getName(fileName));
// ajax.put("newFileNameSend", FileUtils.getName(fileSend.getName()));
ajax.put("originalFilename", file.getOriginalFilename());
ajax.put("originalFilenameSend", file.getOriginalFilename());
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 通用上传请求多个
*/
@PostMapping("/uploads")
public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
try {
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
List<String> urls = new ArrayList<String>();
List<String> fileNames = new ArrayList<String>();
List<String> newFileNames = new ArrayList<String>();
List<String> originalFilenames = new ArrayList<String>();
for (MultipartFile file : files) {
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
urls.add(url);
fileNames.add(fileName);
newFileNames.add(FileUtils.getName(fileName));
originalFilenames.add(file.getOriginalFilename());
}
AjaxResult ajax = AjaxResult.success();
ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 本地资源通用下载
*/
@GetMapping("/download/resource")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
if (!FileUtils.checkAllowDownload(resource)) {
throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
}
// 本地资源路径
String localPath = RuoYiConfig.getProfile();
// 数据库资源地址
String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
// 下载名称
String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, downloadName);
FileUtils.writeBytes(downloadPath, response.getOutputStream());
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
}

View File

@ -0,0 +1,120 @@
package com.ruoyi.web.controller.monitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysCache;
/**
* 缓存监控
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/cache")
public class CacheController
{
@Autowired
private RedisTemplate<String, String> redisTemplate;
private final static List<SysCache> caches = new ArrayList<SysCache>();
{
caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception
{
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());
Map<String, Object> result = new HashMap<>(3);
result.put("info", info);
result.put("dbSize", dbSize);
List<Map<String, String>> pieList = new ArrayList<>();
commandStats.stringPropertyNames().forEach(key -> {
Map<String, String> data = new HashMap<>(2);
String property = commandStats.getProperty(key);
data.put("name", StringUtils.removeStart(key, "cmdstat_"));
data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
pieList.add(data);
});
result.put("commandStats", pieList);
return AjaxResult.success(result);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getNames")
public AjaxResult cache()
{
return AjaxResult.success(caches);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getKeys/{cacheName}")
public AjaxResult getCacheKeys(@PathVariable String cacheName)
{
Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
return AjaxResult.success(cacheKeys);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getValue/{cacheName}/{cacheKey}")
public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey)
{
String cacheValue = redisTemplate.opsForValue().get(cacheKey);
SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
return AjaxResult.success(sysCache);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheName/{cacheName}")
public AjaxResult clearCacheName(@PathVariable String cacheName)
{
Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheKey/{cacheKey}")
public AjaxResult clearCacheKey(@PathVariable String cacheKey)
{
redisTemplate.delete(cacheKey);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheAll")
public AjaxResult clearCacheAll()
{
Collection<String> cacheKeys = redisTemplate.keys("*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
}

View File

@ -0,0 +1,27 @@
package com.ruoyi.web.controller.monitor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.domain.Server;
/**
* 服务器监控
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/server")
public class ServerController
{
@PreAuthorize("@ss.hasPermi('monitor:server:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception
{
Server server = new Server();
server.copyTo();
return AjaxResult.success(server);
}
}

View File

@ -0,0 +1,82 @@
package com.ruoyi.web.controller.monitor;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPasswordService;
import com.ruoyi.system.domain.SysLogininfor;
import com.ruoyi.system.service.ISysLogininforService;
/**
* 系统访问记录
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/logininfor")
public class SysLogininforController extends BaseController
{
@Autowired
private ISysLogininforService logininforService;
@Autowired
private SysPasswordService passwordService;
@PreAuthorize("@ss.hasPermi('monitor:logininfor:list')")
@GetMapping("/list")
public TableDataInfo list(SysLogininfor logininfor)
{
startPage();
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
return getDataTable(list);
}
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('monitor:logininfor:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysLogininfor logininfor)
{
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class);
util.exportExcel(response, list, "登录日志");
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{infoIds}")
public AjaxResult remove(@PathVariable Long[] infoIds)
{
return toAjax(logininforService.deleteLogininforByIds(infoIds));
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean()
{
logininforService.cleanLogininfor();
return success();
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:unlock')")
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
@GetMapping("/unlock/{userName}")
public AjaxResult unlock(@PathVariable("userName") String userName)
{
passwordService.clearLoginRecordCache(userName);
return success();
}
}

View File

@ -0,0 +1,69 @@
package com.ruoyi.web.controller.monitor;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
/**
* 操作日志记录
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController
{
@Autowired
private ISysOperLogService operLogService;
@PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
@GetMapping("/list")
public TableDataInfo list(SysOperLog operLog)
{
startPage();
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
return getDataTable(list);
}
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('monitor:operlog:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysOperLog operLog)
{
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class);
util.exportExcel(response, list, "操作日志");
}
@Log(title = "操作日志", businessType = BusinessType.DELETE)
@PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/{operIds}")
public AjaxResult remove(@PathVariable Long[] operIds)
{
return toAjax(operLogService.deleteOperLogByIds(operIds));
}
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
@PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/clean")
public AjaxResult clean()
{
operLogService.cleanOperLog();
return success();
}
}

View File

@ -0,0 +1,83 @@
package com.ruoyi.web.controller.monitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ISysUserOnlineService;
/**
* 在线用户监控
*
* @author ruoyi
*/
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController
{
@Autowired
private ISysUserOnlineService userOnlineService;
@Autowired
private RedisCache redisCache;
@PreAuthorize("@ss.hasPermi('monitor:online:list')")
@GetMapping("/list")
public TableDataInfo list(String ipaddr, String userName)
{
Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
for (String key : keys)
{
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName))
{
userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
}
else if (StringUtils.isNotEmpty(ipaddr))
{
userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
}
else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser()))
{
userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
}
else
{
userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
}
}
Collections.reverse(userOnlineList);
userOnlineList.removeAll(Collections.singleton(null));
return getDataTable(userOnlineList);
}
/**
* 强退用户
*/
@PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@DeleteMapping("/{tokenId}")
public AjaxResult forceLogout(@PathVariable String tokenId)
{
redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
return success();
}
}

View File

@ -0,0 +1,133 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
/**
* 参数配置 信息操作处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController
{
@Autowired
private ISysConfigService configService;
/**
* 获取参数配置列表
*/
@PreAuthorize("@ss.hasPermi('system:config:list')")
@GetMapping("/list")
public TableDataInfo list(SysConfig config)
{
startPage();
List<SysConfig> list = configService.selectConfigList(config);
return getDataTable(list);
}
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:config:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysConfig config)
{
List<SysConfig> list = configService.selectConfigList(config);
ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
util.exportExcel(response, list, "参数数据");
}
/**
* 根据参数编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:config:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long configId)
{
return success(configService.selectConfigById(configId));
}
/**
* 根据参数键名查询参数值
*/
@GetMapping(value = "/configKey/{configKey}")
public AjaxResult getConfigKey(@PathVariable String configKey)
{
return success(configService.selectConfigByKey(configKey));
}
/**
* 新增参数配置
*/
@PreAuthorize("@ss.hasPermi('system:config:add')")
@Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysConfig config)
{
if (!configService.checkConfigKeyUnique(config))
{
return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setCreateBy(getUsername());
return toAjax(configService.insertConfig(config));
}
/**
* 修改参数配置
*/
@PreAuthorize("@ss.hasPermi('system:config:edit')")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysConfig config)
{
if (!configService.checkConfigKeyUnique(config))
{
return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setUpdateBy(getUsername());
return toAjax(configService.updateConfig(config));
}
/**
* 删除参数配置
*/
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{configIds}")
public AjaxResult remove(@PathVariable Long[] configIds)
{
configService.deleteConfigByIds(configIds);
return success();
}
/**
* 刷新参数缓存
*/
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache()
{
configService.resetConfigCache();
return success();
}
}

View File

@ -0,0 +1,132 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
/**
* 部门信息
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
@Autowired
private ISysDeptService deptService;
/**
* 获取部门列表
*/
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list")
public AjaxResult list(SysDept dept)
{
List<SysDept> depts = deptService.selectDeptList(dept);
return success(depts);
}
/**
* 查询部门列表排除节点
*/
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list/exclude/{deptId}")
public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
{
List<SysDept> depts = deptService.selectDeptList(new SysDept());
depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
return success(depts);
}
/**
* 根据部门编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:dept:query')")
@GetMapping(value = "/{deptId}")
public AjaxResult getInfo(@PathVariable Long deptId)
{
deptService.checkDeptDataScope(deptId);
return success(deptService.selectDeptById(deptId));
}
/**
* 新增部门
*/
@PreAuthorize("@ss.hasPermi('system:dept:add')")
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDept dept)
{
if (!deptService.checkDeptNameUnique(dept))
{
return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
dept.setCreateBy(getUsername());
return toAjax(deptService.insertDept(dept));
}
/**
* 修改部门
*/
@PreAuthorize("@ss.hasPermi('system:dept:edit')")
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDept dept)
{
Long deptId = dept.getDeptId();
deptService.checkDeptDataScope(deptId);
if (!deptService.checkDeptNameUnique(dept))
{
return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
else if (dept.getParentId().equals(deptId))
{
return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
}
else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
{
return error("该部门包含未停用的子部门!");
}
dept.setUpdateBy(getUsername());
return toAjax(deptService.updateDept(dept));
}
/**
* 删除部门
*/
@PreAuthorize("@ss.hasPermi('system:dept:remove')")
@Log(title = "部门管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{deptId}")
public AjaxResult remove(@PathVariable Long deptId)
{
if (deptService.hasChildByDeptId(deptId))
{
return warn("存在下级部门,不允许删除");
}
if (deptService.checkDeptExistUser(deptId))
{
return warn("部门存在用户,不允许删除");
}
deptService.checkDeptDataScope(deptId);
return toAjax(deptService.deleteDeptById(deptId));
}
}

View File

@ -0,0 +1,131 @@
package com.ruoyi.web.controller.system;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
/**
* 数据字典信息
*
* @author ruoyi
*/
@RestController
@Api(tags = "数据字典信息")
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController
{
@Autowired
private ISysDictDataService dictDataService;
@Autowired
private ISysDictTypeService dictTypeService;
//@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping("/list")
@ApiOperation("字典列表")
public TableDataInfo list(SysDictData dictData)
{
startPage();
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
return getDataTable(list);
}
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
//@PreAuthorize("@ss.hasPermi('system:dict:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysDictData dictData)
{
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
util.exportExcel(response, list, "字典数据");
}
/**
* 查询字典数据详细
*/
//@PreAuthorize("@ss.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictCode}")
@ApiOperation("查询字典数据详细")
public AjaxResult getInfo(@PathVariable Long dictCode)
{
return success(dictDataService.selectDictDataById(dictCode));
}
/**
* 根据字典类型查询字典数据信息
*/
@ApiOperation("根据字典类型查询字典数据信息")
@GetMapping(value = "/type/{dictType}")
public AjaxResult dictType(@PathVariable String dictType)
{
List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
if (StringUtils.isNull(data))
{
data = new ArrayList<SysDictData>();
}
return success(data);
}
/**
* 新增字典类型
*/
@ApiOperation("新增字典类型")
//@PreAuthorize("@ss.hasPermi('system:dict:add')")
@Log(title = "字典数据", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDictData dict)
{
dict.setCreateBy(getUsername());
return toAjax(dictDataService.insertDictData(dict));
}
/**
* 修改保存字典类型
*/
@ApiOperation("修改保存字典类型")
//@PreAuthorize("@ss.hasPermi('system:dict:edit')")
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDictData dict)
{
dict.setUpdateBy(getUsername());
return toAjax(dictDataService.updateDictData(dict));
}
/**
* 删除字典类型
*/
@ApiOperation("删除字典类型")
//@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictCodes}")
public AjaxResult remove(@PathVariable Long[] dictCodes)
{
dictDataService.deleteDictDataByIds(dictCodes);
return success();
}
}

View File

@ -0,0 +1,131 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictTypeService;
/**
* 数据字典信息
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController
{
@Autowired
private ISysDictTypeService dictTypeService;
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(SysDictType dictType)
{
startPage();
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
return getDataTable(list);
}
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:dict:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysDictType dictType)
{
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
util.exportExcel(response, list, "字典类型");
}
/**
* 查询字典类型详细
*/
@PreAuthorize("@ss.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictId}")
public AjaxResult getInfo(@PathVariable Long dictId)
{
return success(dictTypeService.selectDictTypeById(dictId));
}
/**
* 新增字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:add')")
@Log(title = "字典类型", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDictType dict)
{
if (!dictTypeService.checkDictTypeUnique(dict))
{
return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setCreateBy(getUsername());
return toAjax(dictTypeService.insertDictType(dict));
}
/**
* 修改字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:edit')")
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDictType dict)
{
if (!dictTypeService.checkDictTypeUnique(dict))
{
return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setUpdateBy(getUsername());
return toAjax(dictTypeService.updateDictType(dict));
}
/**
* 删除字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictIds}")
public AjaxResult remove(@PathVariable Long[] dictIds)
{
dictTypeService.deleteDictTypeByIds(dictIds);
return success();
}
/**
* 刷新字典缓存
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache()
{
dictTypeService.resetDictCache();
return success();
}
/**
* 获取字典选择框列表
*/
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
return success(dictTypes);
}
}

View File

@ -0,0 +1,29 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
/**
* 首页
*
* @author ruoyi
*/
@RestController
public class SysIndexController
{
/** 系统基础配置 */
@Autowired
private RuoYiConfig ruoyiConfig;
/**
* 访问首页提示语
*/
@RequestMapping("/")
public String index()
{
return StringUtils.format("欢迎使用{}后台管理框架当前版本v{},请通过前端地址访问。", ruoyiConfig.getName(), ruoyiConfig.getVersion());
}
}

View File

@ -0,0 +1,263 @@
package com.ruoyi.web.controller.system;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.ruoyi.business.util.StringKit;
import com.ruoyi.cache.SmsCache;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.database.domain.dto.LoginDto;
import com.ruoyi.database.domain.dto.SMSLoginDto;
import com.ruoyi.database.domain.vo.SMSMsgVO;
import com.ruoyi.database.domain.vo.SmsVO;
import com.ruoyi.database.domain.vo.SwtMsgVO;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* 登录验证
*
* @author ruoyi
*/
@Api(tags = "登录验证")
@RestController
public class SysLoginController {
@Autowired
private SysLoginService loginService;
@Autowired
private ISysMenuService menuService;
@Autowired
private SysPermissionService permissionService;
@Autowired
private ISysUserService sysUserService;
private static final String PATH_PREFIX = "/home/dataaccess/facevideo/";
private static final String USER_PATH_PREFIX = "/home/dataaccess/rwglUserFaceVideo/";
// List of valid image extensions
private static final List<String> IMAGE_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp");
private static final String SMS_KEY = "SMS_KEY:";
private static final String SWT_KEY = "SWT_KEY:";
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@ApiOperation("登录")
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody) {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
@ApiOperation("登录App")
@PostMapping("/loginApp")
public AjaxResult loginApp(@RequestBody LoginBody loginBody) {
AjaxResult ajax = AjaxResult.success();
loginBody.setCode("000000");
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
@ApiOperation("身份信息登录")
@RequestMapping("/loginByName")
public AjaxResult loginByCa(String name, String user) {
try {
// SysUser sysUser = sysUserService.selectUserByUserNum(user);
// if (sysUser == null){
// SysUser sysUser1 = new SysUser();
// sysUser1.setUserName(user);
// sysUser1.setPassword(user);
// sysUser1.setNickName(name);
// int i = sysUserService.insertUser(sysUser1);
// if (i == 1){
// SysUser sysUser2 = sysUserService.selectUserByUserNum(user);
// Long[] longs = {6L};
// sysUserService.insertUserAuth(sysUser2.getUserId(),longs);
// }
// }
AjaxResult ajax = AjaxResult.success();
String token = loginService.loginAppBySms(name, user);
JSONObject resJson = new JSONObject();
resJson.put(Constants.TOKEN, token);
// resJson.put("name", name);
resJson.put("user", name);
ajax.put(Constants.TOKEN, resJson);
return ajax;
} catch (Exception e) {
// logger.info(StringKit.getTrace(e));
}
return AjaxResult.error("系统错误,请联系管理员");
}
@ApiOperation("短信验证码登录")
@PostMapping("/loginBySMS")
public AjaxResult loginBySMS(@RequestBody SMSLoginDto smsLoginDto) {
try {
RedisCache bean = SpringUtils.getBean(RedisCache.class);
Integer type = smsLoginDto.getType();
String code = smsLoginDto.getCode();
String phone = smsLoginDto.getPhone();
AjaxResult ajax = AjaxResult.success();
if (type == 1) {
SysUser sysUser = sysUserService.selectUserByUserName(phone);
if (sysUser == null) {
return AjaxResult.error("用户不存在");
}
SwtMsgVO msgVO = bean.getCacheObject(SWT_KEY + phone);
if (msgVO == null) {
return AjaxResult.error("苏网通消息发送出现异常,请稍后重试");
}
if (msgVO.getMsg().equals(code)) {
String token = loginService.loginAppBySms(sysUser.getUserName(), sysUser.getNickName());
JSONObject resJson = new JSONObject();
resJson.put(Constants.TOKEN, token);
resJson.put("user", sysUser.getUserName());
resJson.put("name", sysUser.getNickName());
ajax.put(Constants.TOKEN, resJson);
return ajax;
}
return AjaxResult.error("验证码错误,请重试");
} else if (type == 2) {
SysUser sysUser = sysUserService.selectUserByPhone(phone);
if (sysUser == null) {
return AjaxResult.error("用户不存在");
}
SMSMsgVO msgVO = bean.getCacheObject(SMS_KEY + phone);
if (msgVO == null) {
return AjaxResult.error("短信发送出现异常,请稍后重试");
}
if (msgVO.getMsg().equals(code)) {
String token = loginService.loginAppBySms(sysUser.getUserName(), sysUser.getNickName());
JSONObject resJson = new JSONObject();
resJson.put(Constants.TOKEN, token);
resJson.put("user", sysUser.getUserName());
resJson.put("name", sysUser.getNickName());
ajax.put(Constants.TOKEN, resJson);
return ajax;
}
return AjaxResult.error("验证码错误,请重试");
} else {
return AjaxResult.error("缺少type");
}
} catch (Exception e) {
// logger.info(StringKit.getTrace(e));
}
return AjaxResult.error("系统错误,请联系管理员");
}
@ApiOperation("登录App-根据验证码")
@PostMapping("/loginAppBySms")
public AjaxResult loginAppBySms(@RequestBody LoginDto loginBody) {
String smsStr = SmsCache.get(loginBody.getUsername());
if ("".equals(StringKit.toString(smsStr))) {
return AjaxResult.error("验证码不存在");
}
SmsVO smsVO = JSON.parseObject(smsStr, SmsVO.class, Feature.IgnoreNotMatch);
//验证超时 30分钟
Long nowTime = System.currentTimeMillis() / 1000;
Long oldTime = smsVO.getTime();
//30分钟有效
if ((nowTime - oldTime) > 30 * 60) {
return AjaxResult.error("验证码已失效,请重新发送");
}
//验证 验证码是否一致
String nowCode = StringKit.toString(loginBody.getCode());
String oldCode = StringKit.toString(smsVO.getMsg());
if (!oldCode.equals(nowCode)) {
return AjaxResult.error("验证码不匹配,请核实后输入");
}
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.loginAppBySms(loginBody.getUsername(), loginBody.getCode());
ajax.put(Constants.TOKEN, token);
return ajax;
}
/**
* 获取用户信息
*
* @return 用户信息
*/
@GetMapping("getInfo")
public AjaxResult getInfo() {
LoginUser loginUser = SecurityUtils.getLoginUser();
Long userId = loginUser.getUserId();
SysUser user = sysUserService.selectUserById(userId);
String areaAuthCode = StringKit.toString(user.getAreaAuthCode());
if (!"".equals(areaAuthCode)) {
if (!"0".equals(areaAuthCode)) {
String result = truncateAndPad(areaAuthCode);
user.setAreaAuthCode(result);
}
}
// 角色集合
Set<String> roles = permissionService.getRolePermission(user);
// 权限集合
Set<String> permissions = permissionService.getMenuPermission(user);
AjaxResult ajax = AjaxResult.success();
ajax.put("user", user);
ajax.put("roles", roles);
ajax.put("permissions", permissions);
return ajax;
}
public static String truncateAndPad(String str) {
if ("0".equals(StringKit.toString(str))) {
return str;
}
// 去掉后面的所有的0
String trimmed = str.replaceAll("0*$", "");
// 如果少于4位补0到4位
if (trimmed.length() < 4) {
trimmed = String.format("%-4s", trimmed).replace(' ', '0');
}
return trimmed;
}
/**
* 获取路由信息
*
* @return 路由信息
*/
@GetMapping("getRouters")
public AjaxResult getRouters() {
Long userId = SecurityUtils.getUserId();
List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
return AjaxResult.success(menuService.buildMenus(menus));
}
}

View File

@ -0,0 +1,119 @@
package com.ruoyi.web.controller.system;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 菜单信息
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
@Autowired
private ISysMenuService menuService;
/**
* 获取菜单列表
*/
@PreAuthorize("@ss.hasPermi('system:menu:list')")
@GetMapping("/list")
public AjaxResult list(SysMenu menu) {
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return success(menus);
}
/**
* 根据菜单编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:menu:query')")
@GetMapping(value = "/{menuId}")
public AjaxResult getInfo(@PathVariable Long menuId) {
return success(menuService.selectMenuById(menuId));
}
/**
* 获取菜单下拉树列表
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(SysMenu menu) {
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return success(menuService.buildMenuTreeSelect(menus));
}
/**
* 加载对应角色菜单列表树
*/
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
List<SysMenu> menus = menuService.selectMenuList(getUserId());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
ajax.put("menus", menuService.buildMenuTreeSelect(menus));
return ajax;
}
/**
* 新增菜单
*/
@PreAuthorize("@ss.hasPermi('system:menu:add')")
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysMenu menu) {
menu.setPerms("");
if (!menuService.checkMenuNameUnique(menu)) {
return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
return error("新增菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
}
menu.setCreateBy(getUsername());
return toAjax(menuService.insertMenu(menu));
}
/**
* 修改菜单
*/
@PreAuthorize("@ss.hasPermi('system:menu:edit')")
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
if (!menuService.checkMenuNameUnique(menu)) {
return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
return error("修改菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
} else if (menu.getMenuId().equals(menu.getParentId())) {
return error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
}
menu.setUpdateBy(getUsername());
return toAjax(menuService.updateMenu(menu));
}
/**
* 删除菜单
*/
@PreAuthorize("@ss.hasPermi('system:menu:remove')")
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{menuId}")
public AjaxResult remove(@PathVariable("menuId") Long menuId) {
if (menuService.hasChildByMenuId(menuId)) {
return warn("存在子菜单,不允许删除");
}
if (menuService.checkMenuExistRole(menuId)) {
return warn("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}
}

View File

@ -0,0 +1,91 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
/**
* 公告 信息操作处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController
{
@Autowired
private ISysNoticeService noticeService;
/**
* 获取通知公告列表
*/
@PreAuthorize("@ss.hasPermi('system:notice:list')")
@GetMapping("/list")
public TableDataInfo list(SysNotice notice)
{
startPage();
List<SysNotice> list = noticeService.selectNoticeList(notice);
return getDataTable(list);
}
/**
* 根据通知公告编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:notice:query')")
@GetMapping(value = "/{noticeId}")
public AjaxResult getInfo(@PathVariable Long noticeId)
{
return success(noticeService.selectNoticeById(noticeId));
}
/**
* 新增通知公告
*/
@PreAuthorize("@ss.hasPermi('system:notice:add')")
@Log(title = "通知公告", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysNotice notice)
{
notice.setCreateBy(getUsername());
return toAjax(noticeService.insertNotice(notice));
}
/**
* 修改通知公告
*/
@PreAuthorize("@ss.hasPermi('system:notice:edit')")
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysNotice notice)
{
notice.setUpdateBy(getUsername());
return toAjax(noticeService.updateNotice(notice));
}
/**
* 删除通知公告
*/
@PreAuthorize("@ss.hasPermi('system:notice:remove')")
@Log(title = "通知公告", businessType = BusinessType.DELETE)
@DeleteMapping("/{noticeIds}")
public AjaxResult remove(@PathVariable Long[] noticeIds)
{
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
}
}

View File

@ -0,0 +1,129 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
/**
* 岗位信息操作处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/post")
public class SysPostController extends BaseController
{
@Autowired
private ISysPostService postService;
/**
* 获取岗位列表
*/
@PreAuthorize("@ss.hasPermi('system:post:list')")
@GetMapping("/list")
public TableDataInfo list(SysPost post)
{
startPage();
List<SysPost> list = postService.selectPostList(post);
return getDataTable(list);
}
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:post:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysPost post)
{
List<SysPost> list = postService.selectPostList(post);
ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
util.exportExcel(response, list, "岗位数据");
}
/**
* 根据岗位编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:post:query')")
@GetMapping(value = "/{postId}")
public AjaxResult getInfo(@PathVariable Long postId)
{
return success(postService.selectPostById(postId));
}
/**
* 新增岗位
*/
@PreAuthorize("@ss.hasPermi('system:post:add')")
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysPost post)
{
if (!postService.checkPostNameUnique(post))
{
return error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
}
else if (!postService.checkPostCodeUnique(post))
{
return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setCreateBy(getUsername());
return toAjax(postService.insertPost(post));
}
/**
* 修改岗位
*/
@PreAuthorize("@ss.hasPermi('system:post:edit')")
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysPost post)
{
if (!postService.checkPostNameUnique(post))
{
return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
}
else if (!postService.checkPostCodeUnique(post))
{
return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setUpdateBy(getUsername());
return toAjax(postService.updatePost(post));
}
/**
* 删除岗位
*/
@PreAuthorize("@ss.hasPermi('system:post:remove')")
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{postIds}")
public AjaxResult remove(@PathVariable Long[] postIds)
{
return toAjax(postService.deletePostByIds(postIds));
}
/**
* 获取岗位选择框列表
*/
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
List<SysPost> posts = postService.selectPostAll();
return success(posts);
}
}

View File

@ -0,0 +1,136 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
/**
* 个人信息 业务处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
@Autowired
private ISysUserService userService;
@Autowired
private TokenService tokenService;
/**
* 个人信息
*/
@GetMapping
public AjaxResult profile()
{
LoginUser loginUser = getLoginUser();
SysUser user = loginUser.getUser();
AjaxResult ajax = AjaxResult.success(user);
ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
return ajax;
}
/**
* 修改用户
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult updateProfile(@RequestBody SysUser user)
{
LoginUser loginUser = getLoginUser();
SysUser currentUser = loginUser.getUser();
currentUser.setNickName(user.getNickName());
currentUser.setEmail(user.getEmail());
currentUser.setPhonenumber(user.getPhonenumber());
currentUser.setSex(user.getSex());
if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser))
{
return error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser))
{
return error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
if (userService.updateUserProfile(currentUser) > 0)
{
// 更新缓存用户信息
tokenService.setLoginUser(loginUser);
return success();
}
return error("修改个人信息异常,请联系管理员");
}
/**
* 重置密码
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword)
{
LoginUser loginUser = getLoginUser();
String userName = loginUser.getUsername();
String password = loginUser.getPassword();
if (!SecurityUtils.matchesPassword(oldPassword, password))
{
return error("修改密码失败,旧密码错误");
}
if (SecurityUtils.matchesPassword(newPassword, password))
{
return error("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
{
// 更新缓存用户密码
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.setLoginUser(loginUser);
return success();
}
return error("修改密码异常,请联系管理员");
}
/**
* 头像上传
*/
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
{
if (!file.isEmpty())
{
LoginUser loginUser = getLoginUser();
String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
{
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", avatar);
// 更新缓存用户头像
loginUser.getUser().setAvatar(avatar);
tokenService.setLoginUser(loginUser);
return ajax;
}
}
return error("上传图片异常,请联系管理员");
}
}

View File

@ -0,0 +1,38 @@
package com.ruoyi.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;
/**
* 注册验证
*
* @author ruoyi
*/
@RestController
public class SysRegisterController extends BaseController
{
@Autowired
private SysRegisterService registerService;
@Autowired
private ISysConfigService configService;
@PostMapping("/register")
public AjaxResult register(@RequestBody RegisterBody user)
{
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
{
return error("当前系统没有开启注册功能!");
}
String msg = registerService.register(user);
return StringUtils.isEmpty(msg) ? success() : error(msg);
}
}

View File

@ -0,0 +1,262 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
/**
* 角色信息
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
@Autowired
private ISysRoleService roleService;
@Autowired
private TokenService tokenService;
@Autowired
private SysPermissionService permissionService;
@Autowired
private ISysUserService userService;
@Autowired
private ISysDeptService deptService;
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role)
{
startPage();
List<SysRole> list = roleService.selectRoleList(role);
return getDataTable(list);
}
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysRole role)
{
List<SysRole> list = roleService.selectRoleList(role);
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
util.exportExcel(response, list, "角色数据");
}
/**
* 根据角色编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public AjaxResult getInfo(@PathVariable Long roleId)
{
roleService.checkRoleDataScope(roleId);
return success(roleService.selectRoleById(roleId));
}
/**
* 新增角色
*/
@PreAuthorize("@ss.hasPermi('system:role:add')")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysRole role)
{
if (!roleService.checkRoleNameUnique(role))
{
return error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (!roleService.checkRoleKeyUnique(role))
{
return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setCreateBy(getUsername());
return toAjax(roleService.insertRole(role));
}
/**
* 修改保存角色
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
if (!roleService.checkRoleNameUnique(role))
{
return error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (!roleService.checkRoleKeyUnique(role))
{
return error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setUpdateBy(getUsername());
if (roleService.updateRole(role) > 0)
{
// 更新缓存用户权限
LoginUser loginUser = getLoginUser();
if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
{
loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
tokenService.setLoginUser(loginUser);
}
return success();
}
return error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
* 修改保存数据权限
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public AjaxResult dataScope(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
return toAjax(roleService.authDataScope(role));
}
/**
* 状态修改
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
role.setUpdateBy(getUsername());
return toAjax(roleService.updateRoleStatus(role));
}
/**
* 删除角色
*/
@PreAuthorize("@ss.hasPermi('system:role:remove')")
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public AjaxResult remove(@PathVariable Long[] roleIds)
{
return toAjax(roleService.deleteRoleByIds(roleIds));
}
/**
* 获取角色选择框列表
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect()
{
return success(roleService.selectRoleAll());
}
/**
* 查询已分配用户角色列表
*/
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/allocatedList")
public TableDataInfo allocatedList(SysUser user)
{
startPage();
List<SysUser> list = userService.selectAllocatedList(user);
return getDataTable(list);
}
/**
* 查询未分配用户角色列表
*/
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/unallocatedList")
public TableDataInfo unallocatedList(SysUser user)
{
startPage();
List<SysUser> list = userService.selectUnallocatedList(user);
return getDataTable(list);
}
/**
* 取消授权用户
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancel")
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
{
return toAjax(roleService.deleteAuthUser(userRole));
}
/**
* 批量取消授权用户
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancelAll")
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
{
return toAjax(roleService.deleteAuthUsers(roleId, userIds));
}
/**
* 批量选择用户授权
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/selectAll")
public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
{
roleService.checkRoleDataScope(roleId);
return toAjax(roleService.insertAuthUsers(roleId, userIds));
}
/**
* 获取对应角色部门树列表
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/deptTree/{roleId}")
public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
{
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.selectDeptTreeList(new SysDept()));
return ajax;
}
}

View File

@ -0,0 +1,290 @@
package com.ruoyi.web.controller.system;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.ruoyi.common.core.domain.TreeSelect;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
/**
* 用户信息
*
* @author ruoyi
*/
@Api(tags = "用户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
@Autowired
private ISysUserService userService;
@Autowired
private ISysRoleService roleService;
@Autowired
private ISysDeptService deptService;
@Autowired
private ISysPostService postService;
/**
* 获取用户列表
*/
// @PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/list")
@ApiOperation("获取用户列表")
public TableDataInfo list(SysUser user)
{
startPage();
List<SysUser> list = userService.selectUserList(user);
return getDataTable(list);
}
@GetMapping("/userList")
@ApiOperation("查询用户列表")
public TableDataInfo userList(SysUser user) {
List<SysUser> list = userService.userList(user);
return getDataTable(list);
}
@GetMapping("/list/base")
@ApiModelProperty("基本信息列表")
public TableDataInfo listBase(SysUser user)
{
startPage();
SysUser user1 = getLoginUser().getUser();
Long roleId = user1.getRoleId();
if (roleId != 1 && roleId != 4){
user.setDeptId(user1.getDeptId());
}
List<SysUser> list = userService.selectUserList(user);
return getDataTable(list);
}
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:user:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysUser user)
{
List<SysUser> list = userService.selectUserList(user);
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.exportExcel(response, list, "用户数据");
}
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@PreAuthorize("@ss.hasPermi('system:user:import')")
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
List<SysUser> userList = util.importExcel(file.getInputStream());
String operName = getUsername();
String message = userService.importUser(userList, updateSupport, operName);
return success(message);
}
@PostMapping("/importTemplate")
public void importTemplate(HttpServletResponse response)
{
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.importTemplateExcel(response, "用户数据");
}
/**
* 根据用户编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping(value = { "/", "/{userId}" })
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
{
userService.checkUserDataScope(userId);
AjaxResult ajax = AjaxResult.success();
List<SysRole> roles = roleService.selectRoleAll();
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
ajax.put("posts", postService.selectPostAll());
if (StringUtils.isNotNull(userId))
{
SysUser sysUser = userService.selectUserById(userId);
ajax.put(AjaxResult.DATA_TAG, sysUser);
ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
}
return ajax;
}
/**
* 新增用户
*/
@PreAuthorize("@ss.hasPermi('system:user:add')")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysUser user)
{
if (!userService.checkUserNameUnique(user))
{
return error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
}
else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
{
return error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
}
else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
{
return error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setCreateBy(getUsername());
if (user.getDeptId()==138000){
user.setUserTypeCn("3");
}else if (user.getDeptId()==159000|| user.getDeptId()==160000|| user.getDeptId()==161000|| user.getDeptId()==162000|| user.getDeptId()==163000|| user.getDeptId()==164000|| user.getDeptId()==165000|| user.getDeptId()==166000|| user.getDeptId()==167000|| user.getDeptId()==168000|| user.getDeptId()==169000){
user.setUserTypeCn("2");
}else {
user.setUserTypeCn("4");
}
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}
/**
* 修改用户
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysUser user)
{
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
if (!userService.checkUserNameUnique(user))
{
return error("修改用户'" + user.getUserName() + "'失败,登录账号已存在");
}
else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
{
return error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
{
return error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUpdateBy(getUsername());
return toAjax(userService.updateUser(user));
}
/**
* 删除用户
*/
@PreAuthorize("@ss.hasPermi('system:user:remove')")
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public AjaxResult remove(@PathVariable Long[] userIds)
{
if (ArrayUtils.contains(userIds, getUserId()))
{
return error("当前用户不能删除");
}
return toAjax(userService.deleteUserByIds(userIds));
}
/**
* 重置密码
*/
@PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public AjaxResult resetPwd(@RequestBody SysUser user)
{
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(getUsername());
return toAjax(userService.resetPwd(user));
}
/**
* 状态修改
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysUser user)
{
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setUpdateBy(getUsername());
return toAjax(userService.updateUserStatus(user));
}
/**
* 根据用户编号获取授权角色
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping("/authRole/{userId}")
public AjaxResult authRole(@PathVariable("userId") Long userId)
{
AjaxResult ajax = AjaxResult.success();
SysUser user = userService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
ajax.put("user", user);
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
return ajax;
}
/**
* 用户授权角色
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.GRANT)
@PutMapping("/authRole")
public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
{
userService.checkUserDataScope(userId);
userService.insertUserAuth(userId, roleIds);
return success();
}
/**
* 获取部门树列表
*/
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/deptTree")
public AjaxResult deptTree(SysDept dept)
{
return success(deptService.selectDeptTreeList(dept));
}
}

View File

@ -0,0 +1,183 @@
//package com.ruoyi.web.controller.tool;
//
//import java.util.ArrayList;
//import java.util.LinkedHashMap;
//import java.util.List;
//import java.util.Map;
//import org.springframework.web.bind.annotation.DeleteMapping;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.PutMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//import com.ruoyi.common.core.controller.BaseController;
//import com.ruoyi.common.core.domain.R;
//import com.ruoyi.common.utils.StringUtils;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiImplicitParam;
//import io.swagger.annotations.ApiImplicitParams;
//import io.swagger.annotations.ApiModel;
//import io.swagger.annotations.ApiModelProperty;
//import io.swagger.annotations.ApiOperation;
//
///**
// * swagger 用户测试方法
// *
// * @author ruoyi
// */
//@Api("用户信息管理")
//@RestController
//@RequestMapping("/test/user")
//public class TestController extends BaseController
//{
// private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();
// {
// users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
// users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
// }
//
// @ApiOperation("获取用户列表")
// @GetMapping("/list")
// public R<List<UserEntity>> userList()
// {
// List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
// return R.ok(userList);
// }
//
// @ApiOperation("获取用户详细")
// @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
// @GetMapping("/{userId}")
// public R<UserEntity> getUser(@PathVariable Integer userId)
// {
// if (!users.isEmpty() && users.containsKey(userId))
// {
// return R.ok(users.get(userId));
// }
// else
// {
// return R.fail("用户不存在");
// }
// }
//
// @ApiOperation("新增用户")
// @ApiImplicitParams({
// @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
// @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
// @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
// @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
// })
// @PostMapping("/save")
// public R<String> save(UserEntity user)
// {
// if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
// {
// return R.fail("用户ID不能为空");
// }
// users.put(user.getUserId(), user);
// return R.ok();
// }
//
// @ApiOperation("更新用户")
// @PutMapping("/update")
// public R<String> update(@RequestBody UserEntity user)
// {
// if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
// {
// return R.fail("用户ID不能为空");
// }
// if (users.isEmpty() || !users.containsKey(user.getUserId()))
// {
// return R.fail("用户不存在");
// }
// users.remove(user.getUserId());
// users.put(user.getUserId(), user);
// return R.ok();
// }
//
// @ApiOperation("删除用户信息")
// @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
// @DeleteMapping("/{userId}")
// public R<String> delete(@PathVariable Integer userId)
// {
// if (!users.isEmpty() && users.containsKey(userId))
// {
// users.remove(userId);
// return R.ok();
// }
// else
// {
// return R.fail("用户不存在");
// }
// }
//}
//
//@ApiModel(value = "UserEntity", description = "用户实体")
//class UserEntity
//{
// @ApiModelProperty("用户ID")
// private Integer userId;
//
// @ApiModelProperty("用户名称")
// private String username;
//
// @ApiModelProperty("用户密码")
// private String password;
//
// @ApiModelProperty("用户手机")
// private String mobile;
//
// public UserEntity()
// {
//
// }
//
// public UserEntity(Integer userId, String username, String password, String mobile)
// {
// this.userId = userId;
// this.username = username;
// this.password = password;
// this.mobile = mobile;
// }
//
// public Integer getUserId()
// {
// return userId;
// }
//
// public void setUserId(Integer userId)
// {
// this.userId = userId;
// }
//
// public String getUsername()
// {
// return username;
// }
//
// public void setUsername(String username)
// {
// this.username = username;
// }
//
// public String getPassword()
// {
// return password;
// }
//
// public void setPassword(String password)
// {
// this.password = password;
// }
//
// public String getMobile()
// {
// return mobile;
// }
//
// public void setMobile(String mobile)
// {
// this.mobile = mobile;
// }
//}

View File

@ -0,0 +1,125 @@
package com.ruoyi.web.core.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.ruoyi.common.config.RuoYiConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
/**
* Swagger2的接口配置
*
* @author ruoyi
*/
@Configuration
public class SwaggerConfig
{
/** 系统基础配置 */
@Autowired
private RuoYiConfig ruoyiConfig;
/** 是否开启swagger */
@Value("${swagger.enabled}")
private boolean enabled;
/** 设置请求的统一前缀 */
@Value("${swagger.pathMapping}")
private String pathMapping;
/**
* 创建API
*/
@Bean
public Docket createRestApi()
{
return new Docket(DocumentationType.OAS_30)
// 是否启用Swagger
.enable(enabled)
// 用来创建该API的基本信息展示在文档的页面中自定义展示的信息
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
// .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
/* 设置安全模式swagger可以设置访问token */
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping(pathMapping);
}
/**
* 安全模式这里指定token通过Authorization头请求头传递
*/
private List<SecurityScheme> securitySchemes()
{
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
return apiKeyList;
}
/**
* 安全上下文
*/
private List<SecurityContext> securityContexts()
{
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(o -> o.requestMappingPattern().matches("/.*"))
.build());
return securityContexts;
}
/**
* 默认的安全上引用
*/
private List<SecurityReference> defaultAuth()
{
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo()
{
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题若依管理系统_接口文档")
// 描述
.description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
// 作者信息
.contact(new Contact(ruoyiConfig.getName(), null, null))
// 版本
.version("版本号:" + ruoyiConfig.getVersion())
.build();
}
}

View File

@ -0,0 +1 @@
restart.include.json=/com.alibaba.fastjson.*.jar

View File

@ -0,0 +1,61 @@
# 数据源配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://50.146.63.166:55306/PublicAffairs?useUnicode=true&allowMultiQueries=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: '!QAZ1qaz'
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: false
url:
username:
password:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 50
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置连接超时时间
connectTimeout: 30000
# 配置网络超时时间
socketTimeout: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: false
# 设置白名单,不填则允许所有访问
allow:
url-pattern: /druid/*
# 控制台管理用户名和密码
login-username: ruoyi
login-password: 123456
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true

View File

@ -0,0 +1,138 @@
# 项目相关配置
ruoyi:
# 名称
name: RuoYi
# 版本
version: 3.8.6
# 版权年份
copyrightYear: 2023
# 实例演示开关
demoEnabled: true
# 文件路径 示例( Windows配置D:/ruoyi/uploadPathLinux配置 /home/ruoyi/uploadPath
profile: /home/dataaccess
# 获取ip地址开关
addressEnabled: false
# 验证码类型 math 数字计算 char 字符验证
captchaType: math
# 开发环境配置
server:
# 服务器的HTTP端口默认为8080
port: 9898
servlet:
# 应用的访问路径
context-path: /PublicAffairs/
tomcat:
# tomcat的URI编码
uri-encoding: UTF-8
# 连接数满后的排队数默认为100
accept-count: 1000
threads:
# tomcat最大线程数默认为200
max: 800
# Tomcat启动初始化的线程数默认值10
min-spare: 100
# 日志配置
logging:
level:
com.ruoyi: debug
org.springframework: warn
# 用户配置
user:
password:
# 密码最大错误次数
maxRetryCount: 100
# 密码锁定时间默认10分钟
lockTime: 1
# Spring配置
spring:
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
profiles:
active: druid
# 文件上传
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
# 设置总上传的文件大小
max-request-size: 20MB
# 服务模块
devtools:
restart:
# 热部署开关
enabled: true
# redis 配置
redis:
# 地址
# host: 127.0.0.1
host: 50.146.63.43
# 端口默认为6379
# port: 26379
port: 26379
# 数据库索引
database: 6
# 密码
password: livegbs@2019
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 50
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# token配置
token:
# 令牌自定义标识
header: Authorization
# 令牌密钥
secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期默认30分钟
expireTime: 180
# MyBatis Plus配置
mybatis-plus:
# 搜索指定包别名
typeAliasesPackage: com.ruoyi.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
globalConfig:
dbConfig:
logic-delete-field: is_deleted
logic-not-delete-value: 0
logic-delete-value: 1
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
# Swagger配置
swagger:
# 是否开启swagger
enabled: true
# 请求前缀
pathMapping: /
# 防止XSS攻击
xss:
# 过滤开关
enabled: true
# 排除链接(多个用逗号分隔)
excludes: /system/notice
# 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/*

View File

@ -0,0 +1,24 @@
Application Version: ${ruoyi.version}
Spring Boot Version: ${spring-boot.version}
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// 佛祖保佑 永不宕机 永无BUG //
////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,38 @@
#错误消息
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=用户不存在/密码错误
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号已被删除
user.blocked=用户已封禁,请联系管理员
role.blocked=角色已封禁,请联系管理员
login.blocked=很遗憾访问IP已被列入系统黑名单
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成且必须以非数字开头
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]

View File

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="/home/project/bzgl/logs" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史 60天 -->
<maxHistory>60</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.ruoyi" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J" />
<!-- 使用驼峰命名法转换字段 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
</settings>
<plugins>
<!-- 添加拦截器 -->
<!-- 字典拦截器 -->
<plugin interceptor="com.ruoyi.interceptor.DictionaryInterceptor"/>
</plugins>
</configuration>

165
ruoyi-common/pom.xml Normal file
View File

@ -0,0 +1,165 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>PublicAffairs</artifactId>
<groupId>com.ruoyi</groupId>
<version>4.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ruoyi-common</artifactId>
<description>
common通用工具
</description>
<dependencies>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- spring security 安全认证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- 自定义验证注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- JSON工具类 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- 动态数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<!-- yml解析器 -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<!-- Jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- mybatis-plus 增强CRUD -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- Lombok能以简单的注解形式来简化java代码提高开发效率-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- hutool工具包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
<!--caffeine本地缓存-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,19 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 匿名访问不鉴权注解
*
* @author ruoyi
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Anonymous
{
}

View File

@ -0,0 +1,33 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据权限过滤注解
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope
{
/**
* 部门表的别名
*/
public String deptAlias() default "";
/**
* 用户表的别名
*/
public String userAlias() default "";
/**
* 权限字符用于多个角色匹配符合要求的权限默认根据权限注解@ss获取多个权限用逗号分隔开来
*/
public String permission() default "";
}

View File

@ -0,0 +1,28 @@
package com.ruoyi.common.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;
import com.ruoyi.common.enums.DataSourceType;
/**
* 自定义多数据源切换注解
*
* 优先级先方法后类如果方法覆盖了类上的数据源类型以方法的为准否则以类上的为准
*
* @author ruoyi
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource
{
/**
* 切换数据源名称
*/
public DataSourceType value() default DataSourceType.MASTER;
}

View File

@ -0,0 +1,187 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import com.ruoyi.common.utils.poi.ExcelHandlerAdapter;
/**
* 自定义导出Excel数据注解
*
* @author ruoyi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel
{
/**
* 导出时在excel中排序
*/
public int sort() default Integer.MAX_VALUE;
/**
* 导出到Excel中的名字.
*/
public String name() default "";
/**
* 日期格式, : yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* 如果是字典类型请设置字典的type值 (: sys_user_sex)
*/
public String dictType() default "";
/**
* 读取内容转表达式 (: 0=,1=,2=未知)
*/
public String readConverterExp() default "";
/**
* 分隔符读取字符串组内容
*/
public String separator() default ",";
/**
* BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化)
*/
public int scale() default -1;
/**
* BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN
*/
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
/**
* 导出时在excel中每个列的高度
*/
public double height() default 14;
/**
* 导出时在excel中每个列的宽度
*/
public double width() default 16;
/**
* 文字后缀,% 90 变成90%
*/
public String suffix() default "";
/**
* 当值为空时,字段的默认值
*/
public String defaultValue() default "";
/**
* 提示信息
*/
public String prompt() default "";
/**
* 设置只能选择不能输入的列内容.
*/
public String[] combo() default {};
/**
* 是否需要纵向合并单元格,应对需求:含有list集合单元格)
*/
public boolean needMerge() default false;
/**
* 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
*/
public boolean isExport() default true;
/**
* 另一个类中的属性名称,支持多级获取,以小数点隔开
*/
public String targetAttr() default "";
/**
* 是否自动统计数据,在最后追加一行统计数据总和
*/
public boolean isStatistics() default false;
/**
* 导出类型0数字 1字符串 2图片
*/
public ColumnType cellType() default ColumnType.STRING;
/**
* 导出列头背景颜色
*/
public IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT;
/**
* 导出列头字体颜色
*/
public IndexedColors headerColor() default IndexedColors.WHITE;
/**
* 导出单元格背景颜色
*/
public IndexedColors backgroundColor() default IndexedColors.WHITE;
/**
* 导出单元格字体颜色
*/
public IndexedColors color() default IndexedColors.BLACK;
/**
* 导出字段对齐方式
*/
public HorizontalAlignment align() default HorizontalAlignment.CENTER;
/**
* 自定义数据处理器
*/
public Class<?> handler() default ExcelHandlerAdapter.class;
/**
* 自定义数据处理器参数
*/
public String[] args() default {};
/**
* 字段类型0导出导入1仅导出2仅导入
*/
Type type() default Type.ALL;
public enum Type
{
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
public enum ColumnType
{
NUMERIC(0), STRING(1), IMAGE(2);
private final int value;
ColumnType(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
}

View File

@ -0,0 +1,18 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel注解集
*
* @author ruoyi
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels
{
public Excel[] value();
}

View File

@ -0,0 +1,51 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OperatorType;
/**
* 自定义操作日志记录注解
*
* @author ruoyi
*
*/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
public boolean isSaveResponseData() default true;
/**
* 排除指定的请求参数
*/
public String[] excludeParamNames() default {};
}

View File

@ -0,0 +1,40 @@
package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.enums.LimitType;
/**
* 限流注解
*
* @author ruoyi
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter
{
/**
* 限流key
*/
public String key() default CacheConstants.RATE_LIMIT_KEY;
/**
* 限流时间,单位秒
*/
public int time() default 60;
/**
* 限流次数
*/
public int count() default 100;
/**
* 限流类型
*/
public LimitType limitType() default LimitType.DEFAULT;
}

View File

@ -0,0 +1,31 @@
package com.ruoyi.common.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 ruoyi
*
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit
{
/**
* 间隔时间(ms)小于此时间视为重复提交
*/
public int interval() default 5000;
/**
* 提示消息
*/
public String message() default "不允许重复提交,请稍候再试";
}

View File

@ -0,0 +1,162 @@
package com.ruoyi.common.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 读取项目相关配置
*
* @author ruoyi
*/
@Component
@ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig {
/**
* 项目名称
*/
private String name;
/**
* 版本
*/
private String version;
/**
* 版权年份
*/
private String copyrightYear;
/**
* 实例演示开关
*/
private boolean demoEnabled;
/**
* 上传路径
*/
private static String profile;
/**
* 上传路径 send
*/
@Value("${ruoyi.profilesend}")
private static String profilesend;
/**
* 获取地址开关
*/
private static boolean addressEnabled;
/**
* 验证码类型
*/
private static String captchaType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCopyrightYear() {
return copyrightYear;
}
public void setCopyrightYear(String copyrightYear) {
this.copyrightYear = copyrightYear;
}
public boolean isDemoEnabled() {
return demoEnabled;
}
public void setDemoEnabled(boolean demoEnabled) {
this.demoEnabled = demoEnabled;
}
public static String getProfile() {
return profile;
}
public void setProfile(String profile) {
RuoYiConfig.profile = profile;
}
public static boolean isAddressEnabled() {
return addressEnabled;
}
public void setAddressEnabled(boolean addressEnabled) {
RuoYiConfig.addressEnabled = addressEnabled;
}
public static String getCaptchaType() {
return captchaType;
}
public void setCaptchaType(String captchaType) {
RuoYiConfig.captchaType = captchaType;
}
/**
* 获取导入上传路径
*/
public static String getImportPath() {
return getProfile() + "/import";
}
/**
* 获取头像上传路径
*/
public static String getAvatarPath() {
return getProfile() + "/avatar";
}
/**
* 获取下载路径
*/
public static String getDownloadPath() {
return getProfile() + "/download/";
}
/**
* 获取上传路径
*/
public static String getUploadPath() {
return getProfile() + "/upload";
}
/**
* 获取上传路径
*/
public static String getUploadPathNew() {
return getProfile();
}
public static String getProfilesend() {
return profilesend;
}
public void setProfilesend(String profilesend) {
RuoYiConfig.profilesend = profilesend;
}
/**
* 获取上传路径
*/
public static String getUploadPathNewSend() {
return getProfile();
}
}

View File

@ -0,0 +1,44 @@
package com.ruoyi.common.constant;
/**
* 缓存的key 常量
*
* @author ruoyi
*/
public class CacheConstants
{
/**
* 登录用户 redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
/**
* 验证码 redis key
*/
public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
/**
* 参数管理 cache key
*/
public static final String SYS_CONFIG_KEY = "sys_config:";
/**
* 字典管理 cache key
*/
public static final String SYS_DICT_KEY = "sys_dict:";
/**
* 防重提交 redis key
*/
public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";
/**
* 限流 redis key
*/
public static final String RATE_LIMIT_KEY = "rate_limit:";
/**
* 登录账户密码错误次数 redis key
*/
public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt:";
}

View File

@ -0,0 +1,147 @@
package com.ruoyi.common.constant;
import io.jsonwebtoken.Claims;
/**
* 通用常量信息
*
* @author ruoyi
*/
public class Constants
{
/**
* UTF-8 字符集
*/
public static final String UTF8 = "UTF-8";
/**
* GBK 字符集
*/
public static final String GBK = "GBK";
/**
* www主域
*/
public static final String WWW = "www.";
/**
* http请求
*/
public static final String HTTP = "http://";
/**
* https请求
*/
public static final String HTTPS = "https://";
/**
* 通用成功标识
*/
public static final String SUCCESS = "0";
/**
* 通用失败标识
*/
public static final String FAIL = "1";
/**
* 登录成功
*/
public static final String LOGIN_SUCCESS = "Success";
/**
* 注销
*/
public static final String LOGOUT = "Logout";
/**
* 注册
*/
public static final String REGISTER = "Register";
/**
* 登录失败
*/
public static final String LOGIN_FAIL = "Error";
/**
* 验证码有效期分钟
*/
public static final Integer CAPTCHA_EXPIRATION = 2;
/**
* 令牌
*/
public static final String TOKEN = "token";
/**
* 令牌前缀
*/
public static final String TOKEN_PREFIX = "Bearer ";
/**
* 令牌前缀
*/
public static final String LOGIN_USER_KEY = "login_user_key";
/**
* 用户ID
*/
public static final String JWT_USERID = "userid";
/**
* 用户名称
*/
public static final String JWT_USERNAME = Claims.SUBJECT;
/**
* 用户头像
*/
public static final String JWT_AVATAR = "avatar";
/**
* 创建时间
*/
public static final String JWT_CREATED = "created";
/**
* 用户权限
*/
public static final String JWT_AUTHORITIES = "authorities";
/**
* 资源映射路径 前缀
*/
public static final String RESOURCE_PREFIX = "/profile";
/**
* RMI 远程方法调用
*/
public static final String LOOKUP_RMI = "rmi:";
/**
* LDAP 远程方法调用
*/
public static final String LOOKUP_LDAP = "ldap:";
/**
* LDAPS 远程方法调用
*/
public static final String LOOKUP_LDAPS = "ldaps:";
/**
* 自动识别json对象白名单配置仅允许解析的包名范围越小越安全
*/
public static final String[] JSON_WHITELIST_STR = { "org.springframework", "com.ruoyi" };
/**
* 定时任务白名单配置仅允许访问的包名如其他需要可以自行添加
*/
public static final String[] JOB_WHITELIST_STR = { "com.ruoyi" };
/**
* 定时任务违规的字符
*/
public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.ruoyi.common.utils.file", "com.ruoyi.common.config" };
}

View File

@ -0,0 +1,117 @@
package com.ruoyi.common.constant;
/**
* 代码生成通用常量
*
* @author ruoyi
*/
public class GenConstants
{
/** 单表(增删改查) */
public static final String TPL_CRUD = "crud";
/** 树表(增删改查) */
public static final String TPL_TREE = "tree";
/** 主子表(增删改查) */
public static final String TPL_SUB = "sub";
/** 树编码字段 */
public static final String TREE_CODE = "treeCode";
/** 树父编码字段 */
public static final String TREE_PARENT_CODE = "treeParentCode";
/** 树名称字段 */
public static final String TREE_NAME = "treeName";
/** 上级菜单ID字段 */
public static final String PARENT_MENU_ID = "parentMenuId";
/** 上级菜单名称字段 */
public static final String PARENT_MENU_NAME = "parentMenuName";
/** 数据库字符串类型 */
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" };
/** 数据库文本类型 */
public static final String[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" };
/** 数据库时间类型 */
public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" };
/** 数据库数字类型 */
public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer",
"bit", "bigint", "float", "double", "decimal" };
/** 页面不需要编辑字段 */
public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
/** 页面不需要显示的列表字段 */
public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time" };
/** 页面不需要查询字段 */
public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark" };
/** Entity基类字段 */
public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" };
/** Tree基类字段 */
public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors", "children" };
/** 文本框 */
public static final String HTML_INPUT = "input";
/** 文本域 */
public static final String HTML_TEXTAREA = "textarea";
/** 下拉框 */
public static final String HTML_SELECT = "select";
/** 单选框 */
public static final String HTML_RADIO = "radio";
/** 复选框 */
public static final String HTML_CHECKBOX = "checkbox";
/** 日期控件 */
public static final String HTML_DATETIME = "datetime";
/** 图片上传控件 */
public static final String HTML_IMAGE_UPLOAD = "imageUpload";
/** 文件上传控件 */
public static final String HTML_FILE_UPLOAD = "fileUpload";
/** 富文本控件 */
public static final String HTML_EDITOR = "editor";
/** 字符串类型 */
public static final String TYPE_STRING = "String";
/** 整型 */
public static final String TYPE_INTEGER = "Integer";
/** 长整型 */
public static final String TYPE_LONG = "Long";
/** 浮点型 */
public static final String TYPE_DOUBLE = "Double";
/** 高精度计算类型 */
public static final String TYPE_BIGDECIMAL = "BigDecimal";
/** 时间类型 */
public static final String TYPE_DATE = "Date";
/** 模糊查询 */
public static final String QUERY_LIKE = "LIKE";
/** 相等查询 */
public static final String QUERY_EQ = "EQ";
/** 需要 */
public static final String REQUIRE = "1";
}

View File

@ -0,0 +1,94 @@
package com.ruoyi.common.constant;
/**
* 返回状态码
*
* @author ruoyi
*/
public class HttpStatus
{
/**
* 操作成功
*/
public static final int SUCCESS = 200;
/**
* 对象创建成功
*/
public static final int CREATED = 201;
/**
* 请求已经被接受
*/
public static final int ACCEPTED = 202;
/**
* 操作已经执行成功但是没有返回数据
*/
public static final int NO_CONTENT = 204;
/**
* 资源已被移除
*/
public static final int MOVED_PERM = 301;
/**
* 重定向
*/
public static final int SEE_OTHER = 303;
/**
* 资源没有被修改
*/
public static final int NOT_MODIFIED = 304;
/**
* 参数列表错误缺少格式不匹配
*/
public static final int BAD_REQUEST = 400;
/**
* 未授权
*/
public static final int UNAUTHORIZED = 401;
/**
* 访问受限授权过期
*/
public static final int FORBIDDEN = 403;
/**
* 资源服务未找到
*/
public static final int NOT_FOUND = 404;
/**
* 不允许的http方法
*/
public static final int BAD_METHOD = 405;
/**
* 资源冲突或者资源被锁
*/
public static final int CONFLICT = 409;
/**
* 不支持的数据媒体类型
*/
public static final int UNSUPPORTED_TYPE = 415;
/**
* 系统内部错误
*/
public static final int ERROR = 500;
/**
* 接口未实现
*/
public static final int NOT_IMPLEMENTED = 501;
/**
* 系统警告消息
*/
public static final int WARN = 601;
}

View File

@ -0,0 +1,50 @@
package com.ruoyi.common.constant;
/**
* 任务调度通用常量
*
* @author ruoyi
*/
public class ScheduleConstants
{
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/** 执行目标key */
public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/** 默认 */
public static final String MISFIRE_DEFAULT = "0";
/** 立即触发执行 */
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/** 触发一次执行 */
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/** 不触发立即执行 */
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status
{
/**
* 正常
*/
NORMAL("0"),
/**
* 暂停
*/
PAUSE("1");
private String value;
private Status(String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
}

View File

@ -0,0 +1,78 @@
package com.ruoyi.common.constant;
/**
* 用户常量信息
*
* @author ruoyi
*/
public class UserConstants
{
/**
* 平台内系统用户的唯一标志
*/
public static final String SYS_USER = "SYS_USER";
/** 正常状态 */
public static final String NORMAL = "0";
/** 异常状态 */
public static final String EXCEPTION = "1";
/** 用户封禁状态 */
public static final String USER_DISABLE = "1";
/** 角色封禁状态 */
public static final String ROLE_DISABLE = "1";
/** 部门正常状态 */
public static final String DEPT_NORMAL = "0";
/** 部门停用状态 */
public static final String DEPT_DISABLE = "1";
/** 字典正常状态 */
public static final String DICT_NORMAL = "0";
/** 是否为系统默认(是) */
public static final String YES = "Y";
/** 是否菜单外链(是) */
public static final String YES_FRAME = "0";
/** 是否菜单外链(否) */
public static final String NO_FRAME = "1";
/** 菜单类型(目录) */
public static final String TYPE_DIR = "M";
/** 菜单类型(菜单) */
public static final String TYPE_MENU = "C";
/** 菜单类型(按钮) */
public static final String TYPE_BUTTON = "F";
/** Layout组件标识 */
public final static String LAYOUT = "Layout";
/** ParentView组件标识 */
public final static String PARENT_VIEW = "ParentView";
/** InnerLink组件标识 */
public final static String INNER_LINK = "InnerLink";
/** 校验是否唯一的返回标识 */
public final static boolean UNIQUE = true;
public final static boolean NOT_UNIQUE = false;
/**
* 用户名长度限制
*/
public static final int USERNAME_MIN_LENGTH = 2;
public static final int USERNAME_MAX_LENGTH = 20;
/**
* 密码长度限制
*/
public static final int PASSWORD_MIN_LENGTH = 5;
public static final int PASSWORD_MAX_LENGTH = 20;
}

View File

@ -0,0 +1,217 @@
package com.ruoyi.common.core.controller;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
/**
* web层通用数据处理
*
* @author ruoyi
*/
public class BaseController
{
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 将前台传递过来的日期格式的字符串自动转化为Date类型
*/
@InitBinder
public void initBinder(WebDataBinder binder)
{
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport()
{
@Override
public void setAsText(String text)
{
setValue(DateUtils.parseDate(text));
}
});
}
/**
* 设置请求分页数据
*/
protected void startPage()
{
PageUtils.startPage();
}
/**
* 设置请求排序数据
*/
protected void startOrderBy()
{
PageDomain pageDomain = TableSupport.buildPageRequest();
if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))
{
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
PageHelper.orderBy(orderBy);
}
}
/**
* 清理分页的线程变量
*/
protected void clearPage()
{
PageUtils.clearPage();
}
/**
* 响应请求分页数据
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected TableDataInfo getDataTable(List<?> list)
{
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS);
rspData.setMsg("查询成功");
rspData.setRows(list);
rspData.setTotal(new PageInfo(list).getTotal());
return rspData;
}
protected TableDataInfo getDataTableEnhance(List<?> list,Long size)
{
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS);
rspData.setMsg("查询成功");
rspData.setRows(list);
rspData.setTotal(size);
return rspData;
}
/**
* 返回成功
*/
public AjaxResult success()
{
return AjaxResult.success();
}
/**
* 返回失败消息
*/
public AjaxResult error()
{
return AjaxResult.error();
}
/**
* 返回成功消息
*/
public AjaxResult success(String message)
{
return AjaxResult.success(message);
}
/**
* 返回成功消息
*/
public AjaxResult success(Object data)
{
return AjaxResult.success(data);
}
/**
* 返回失败消息
*/
public AjaxResult error(String message)
{
return AjaxResult.error(message);
}
/**
* 返回警告消息
*/
public AjaxResult warn(String message)
{
return AjaxResult.warn(message);
}
/**
* 响应返回结果
*
* @param rows 影响行数
* @return 操作结果
*/
protected AjaxResult toAjax(int rows)
{
return rows > 0 ? AjaxResult.success() : AjaxResult.error();
}
/**
* 响应返回结果
*
* @param result 结果
* @return 操作结果
*/
protected AjaxResult toAjax(boolean result)
{
return result ? success() : error();
}
/**
* 页面跳转
*/
public String redirect(String url)
{
return StringUtils.format("redirect:{}", url);
}
/**
* 获取用户缓存信息
*/
public LoginUser getLoginUser()
{
return SecurityUtils.getLoginUser();
}
/**
* 获取登录用户id
*/
public Long getUserId()
{
return getLoginUser().getUserId();
}
/**
* 获取登录部门id
*/
public Long getDeptId()
{
return getLoginUser().getDeptId();
}
/**
* 获取登录用户名
*/
public String getUsername()
{
return getLoginUser().getUsername();
}
public String getNickname()
{
return getLoginUser().getUser().getNickName();
}
}

View File

@ -0,0 +1,216 @@
package com.ruoyi.common.core.domain;
import java.util.HashMap;
import java.util.Objects;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
/**
* 操作消息提醒
*
* @author ruoyi
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象使其表示一个空消息
*/
public AjaxResult()
{
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public AjaxResult(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult warn(String msg)
{
return AjaxResult.warn(msg, null);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult warn(String msg, Object data)
{
return new AjaxResult(HttpStatus.WARN, msg, data);
}
/**
* 返回错误消息
*
* @return 错误消息
*/
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 错误消息
*/
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 错误消息
*/
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(HttpStatus.ERROR, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 错误消息
*/
public static AjaxResult error(int code, String msg)
{
return new AjaxResult(code, msg, null);
}
/**
* 是否为成功消息
*
* @return 结果
*/
public boolean isSuccess()
{
return Objects.equals(HttpStatus.SUCCESS, this.get(CODE_TAG));
}
/**
* 是否为警告消息
*
* @return 结果
*/
public boolean isWarn()
{
return Objects.equals(HttpStatus.WARN, this.get(CODE_TAG));
}
/**
* 是否为错误消息
*
* @return 结果
*/
public boolean isError()
{
return Objects.equals(HttpStatus.ERROR, this.get(CODE_TAG));
}
/**
* 方便链式调用
*
* @param key
* @param value
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
}

View File

@ -0,0 +1,135 @@
package com.ruoyi.common.core.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
/**
* Entity基类
*
* @author ruoyi
*/
public class BaseEntity implements Serializable
{
private static final long serialVersionUID = 1L;
/** 搜索值 */
@JsonIgnore
@TableField(exist = false)
@ApiModelProperty(hidden = true)
private String searchValue;
/** 创建者 */
@ApiModelProperty("创建者")
@TableField(exist = false)
private String createBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty("创建时间")
@TableField(exist = false)
private Date createTime;
/** 更新者 */
@ApiModelProperty("更新者")
@TableField(exist = false)
private String updateBy;
/** 更新时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(exist = false)
@ApiModelProperty("更新时间")
private Date updateTime;
/** 备注 */
@TableField(exist = false)
@ApiModelProperty(hidden = true)
private String remark;
/** 请求参数 */
@TableField(exist = false)
@ApiModelProperty(hidden = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, Object> params;
public String getSearchValue()
{
return searchValue;
}
public void setSearchValue(String searchValue)
{
this.searchValue = searchValue;
}
public String getCreateBy()
{
return createBy;
}
public void setCreateBy(String createBy)
{
this.createBy = createBy;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public String getUpdateBy()
{
return updateBy;
}
public void setUpdateBy(String updateBy)
{
this.updateBy = updateBy;
}
public Date getUpdateTime()
{
return updateTime;
}
public void setUpdateTime(Date updateTime)
{
this.updateTime = updateTime;
}
public String getRemark()
{
return remark;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public Map<String, Object> getParams()
{
if (params == null)
{
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params)
{
this.params = params;
}
}

View File

@ -0,0 +1,73 @@
package com.ruoyi.common.core.domain;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
/**
* Entity基类
*
* @author ruoyi
*/
public class BaseEntityMini implements Serializable
{
private static final long serialVersionUID = 1L;
/** 搜索值 */
@JsonIgnore
@TableField(exist = false)
@ApiModelProperty(hidden = true)
private String searchValue;
/** 备注 */
@TableField(exist = false)
@ApiModelProperty(hidden = true)
private String remark;
/** 请求参数 */
@TableField(exist = false)
@ApiModelProperty(hidden = true)
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, Object> params;
public String getSearchValue()
{
return searchValue;
}
public void setSearchValue(String searchValue)
{
this.searchValue = searchValue;
}
public String getRemark()
{
return remark;
}
public void setRemark(String remark)
{
this.remark = remark;
}
public Map<String, Object> getParams()
{
if (params == null)
{
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params)
{
this.params = params;
}
}

View File

@ -0,0 +1,115 @@
package com.ruoyi.common.core.domain;
import java.io.Serializable;
import com.ruoyi.common.constant.HttpStatus;
/**
* 响应信息主体
*
* @author ruoyi
*/
public class R<T> implements Serializable
{
private static final long serialVersionUID = 1L;
/** 成功 */
public static final int SUCCESS = HttpStatus.SUCCESS;
/** 失败 */
public static final int FAIL = HttpStatus.ERROR;
private int code;
private String msg;
private T data;
public static <T> R<T> ok()
{
return restResult(null, SUCCESS, "操作成功");
}
public static <T> R<T> ok(T data)
{
return restResult(data, SUCCESS, "操作成功");
}
public static <T> R<T> ok(T data, String msg)
{
return restResult(data, SUCCESS, msg);
}
public static <T> R<T> fail()
{
return restResult(null, FAIL, "操作失败");
}
public static <T> R<T> fail(String msg)
{
return restResult(null, FAIL, msg);
}
public static <T> R<T> fail(T data)
{
return restResult(data, FAIL, "操作失败");
}
public static <T> R<T> fail(T data, String msg)
{
return restResult(data, FAIL, msg);
}
public static <T> R<T> fail(int code, String msg)
{
return restResult(null, code, msg);
}
private static <T> R<T> restResult(T data, int code, String msg)
{
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public T getData()
{
return data;
}
public void setData(T data)
{
this.data = data;
}
public static <T> Boolean isError(R<T> ret)
{
return !isSuccess(ret);
}
public static <T> Boolean isSuccess(R<T> ret)
{
return R.SUCCESS == ret.getCode();
}
}

Some files were not shown because too many files have changed in this diff Show More