try catch 初始化

This commit is contained in:
20932067@zju.edu.cn 2021-02-20 22:43:40 +08:00
parent 5066c5be8c
commit 242a06b7a6
37 changed files with 1110 additions and 545 deletions

View File

@ -7,6 +7,9 @@ import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
@ -26,6 +29,8 @@ import com.hchyun.common.utils.uuid.IdUtils;
*/
@RestController
public class CaptchaController {
private Logger logger = LoggerFactory.getLogger(CaptchaController.class);
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@ -44,36 +49,41 @@ public class CaptchaController {
*/
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException {
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
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());
}
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
AjaxResult ajax = AjaxResult.success();
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
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());
}
AjaxResult ajax = AjaxResult.success();
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -25,7 +25,7 @@ import com.hchyun.framework.config.ServerConfig;
*/
@RestController
public class CommonController {
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
@Autowired
private ServerConfig serverConfig;
@ -54,7 +54,7 @@ public class CommonController {
FileUtils.deleteFile(filePath);
}
} catch (Exception e) {
log.error("下载文件失败", e);
logger.error("下载文件失败", e);
}
}

View File

@ -1,7 +1,11 @@
package com.hchyun.web.controller.monitor;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -26,38 +30,60 @@ import com.hchyun.system.service.LogininforService;
@RestController
@RequestMapping("/monitor/logininfor")
public class LogininforController extends BaseController {
private Logger logger = LoggerFactory.getLogger(LogininforController.class);
@Autowired
private LogininforService logininforService;
@PreAuthorize("@hchyun.hasPermi('monitor:logininfor:list')")
@GetMapping("/list")
public TableDataInfo list(Logininfor logininfor) {
startPage();
List<Logininfor> list = logininforService.selectLogininforList(logininfor);
return getDataTable(list);
public Serializable list(Logininfor logininfor) {
try {
startPage();
List<Logininfor> list = logininforService.selectLogininforList(logininfor);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('monitor:logininfor:export')")
@GetMapping("/export")
public AjaxResult export(Logininfor logininfor) {
List<Logininfor> list = logininforService.selectLogininforList(logininfor);
ExcelUtil<Logininfor> util = new ExcelUtil<Logininfor>(Logininfor.class);
return util.exportExcel(list, "登录日志");
try {
List<Logininfor> list = logininforService.selectLogininforList(logininfor);
ExcelUtil<Logininfor> util = new ExcelUtil<Logininfor>(Logininfor.class);
return util.exportExcel(list, "登录日志");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@PreAuthorize("@hchyun.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{infoIds}")
public AjaxResult remove(@PathVariable Long[] infoIds) {
return toAjax(logininforService.deleteLogininforByIds(infoIds));
try {
return toAjax(logininforService.deleteLogininforByIds(infoIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@PreAuthorize("@hchyun.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean() {
logininforService.cleanLogininfor();
return AjaxResult.success();
try {
logininforService.cleanLogininfor();
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,7 +1,11 @@
package com.hchyun.web.controller.monitor;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -26,37 +30,59 @@ import com.hchyun.system.service.OperLogService;
@RestController
@RequestMapping("/monitor/operlog")
public class OperlogController extends BaseController {
private Logger logger = LoggerFactory.getLogger(OperlogController.class);
@Autowired
private OperLogService operLogService;
@PreAuthorize("@hchyun.hasPermi('monitor:operlog:list')")
@GetMapping("/list")
public TableDataInfo list(OperLog operLog) {
startPage();
List<OperLog> list = operLogService.selectOperLogList(operLog);
return getDataTable(list);
public Serializable list(OperLog operLog) {
try {
startPage();
List<OperLog> list = operLogService.selectOperLogList(operLog);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('monitor:operlog:export')")
@GetMapping("/export")
public AjaxResult export(OperLog operLog) {
List<OperLog> list = operLogService.selectOperLogList(operLog);
ExcelUtil<OperLog> util = new ExcelUtil<OperLog>(OperLog.class);
return util.exportExcel(list, "操作日志");
try {
List<OperLog> list = operLogService.selectOperLogList(operLog);
ExcelUtil<OperLog> util = new ExcelUtil<OperLog>(OperLog.class);
return util.exportExcel(list, "操作日志");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@PreAuthorize("@hchyun.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/{operIds}")
public AjaxResult remove(@PathVariable Long[] operIds) {
return toAjax(operLogService.deleteOperLogByIds(operIds));
try {
return toAjax(operLogService.deleteOperLogByIds(operIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
@PreAuthorize("@hchyun.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/clean")
public AjaxResult clean() {
operLogService.cleanOperLog();
return AjaxResult.success();
try {
operLogService.cleanOperLog();
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,5 +1,8 @@
package com.hchyun.web.controller.monitor;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -16,11 +19,19 @@ import com.hchyun.framework.web.domain.Server;
@RestController
@RequestMapping("/monitor/server")
public class ServerController extends BaseController {
private Logger logger = LoggerFactory.getLogger(ServerController.class);
@PreAuthorize("@hchyun.hasPermi('monitor:server:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception {
Server server = new Server();
server.copyTo();
return AjaxResult.success(server);
try {
Server server = new Server();
server.copyTo();
return AjaxResult.success(server);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,10 +1,14 @@
package com.hchyun.web.controller.monitor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -32,6 +36,8 @@ import com.hchyun.system.service.UserOnlineService;
@RestController
@RequestMapping("/monitor/online")
public class UserOnlineController extends BaseController {
private Logger logger = LoggerFactory.getLogger(UserOnlineController.class);
@Autowired
private UserOnlineService userOnlineService;
@ -40,30 +46,35 @@ public class UserOnlineController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:online:list')")
@GetMapping("/list")
public TableDataInfo list(String ipaddr, String userName) {
Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
List<UserOnline> userOnlineList = new ArrayList<UserOnline>();
for (String key : keys) {
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
public Serializable list(String ipaddr, String userName) {
try {
Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
List<UserOnline> userOnlineList = new ArrayList<UserOnline>();
for (String key : keys) {
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
}
} else if (StringUtils.isNotEmpty(ipaddr)) {
if (StringUtils.equals(ipaddr, user.getIpaddr())) {
userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
}
} else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) {
if (StringUtils.equals(userName, user.getUsername())) {
userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
}
} else {
userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
}
} else if (StringUtils.isNotEmpty(ipaddr)) {
if (StringUtils.equals(ipaddr, user.getIpaddr())) {
userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
}
} else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) {
if (StringUtils.equals(userName, user.getUsername())) {
userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
}
} else {
userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
}
Collections.reverse(userOnlineList);
userOnlineList.removeAll(Collections.singleton(null));
return getDataTable(userOnlineList);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
Collections.reverse(userOnlineList);
userOnlineList.removeAll(Collections.singleton(null));
return getDataTable(userOnlineList);
}
/**
@ -73,7 +84,12 @@ public class UserOnlineController extends BaseController {
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@DeleteMapping("/{tokenId}")
public AjaxResult forceLogout(@PathVariable String tokenId) {
redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY + tokenId);
return AjaxResult.success();
try {
redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY + tokenId);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -4,6 +4,8 @@ import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -34,6 +36,8 @@ import com.hchyun.system.service.ConfigService;
@RestController
@RequestMapping("/system/config")
public class ConfigController extends BaseController {
private Logger logger = LoggerFactory.getLogger(ConfigController.class);
@Autowired
private ConfigService configService;

View File

@ -1,7 +1,11 @@
package com.hchyun.web.controller.system;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -32,6 +36,8 @@ import com.hchyun.system.service.DictTypeService;
@RestController
@RequestMapping("/system/dict/data")
public class DictDataController extends BaseController {
private Logger logger = LoggerFactory.getLogger(DictDataController.class);
@Autowired
private DictDataService dictDataService;
@ -40,19 +46,29 @@ public class DictDataController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(DictData dictData) {
startPage();
List<DictData> list = dictDataService.selectDictDataList(dictData);
return getDataTable(list);
public Serializable list(DictData dictData) {
try {
startPage();
List<DictData> list = dictDataService.selectDictDataList(dictData);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:dict:export')")
@GetMapping("/export")
public AjaxResult export(DictData dictData) {
List<DictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil<DictData> util = new ExcelUtil<DictData>(DictData.class);
return util.exportExcel(list, "字典数据");
try {
List<DictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil<DictData> util = new ExcelUtil<DictData>(DictData.class);
return util.exportExcel(list, "字典数据");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -61,7 +77,12 @@ public class DictDataController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictCode}")
public AjaxResult getInfo(@PathVariable Long dictCode) {
return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
try {
return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -69,7 +90,12 @@ public class DictDataController extends BaseController {
*/
@GetMapping(value = "/type/{dictType}")
public AjaxResult dictType(@PathVariable String dictType) {
return AjaxResult.success(dictTypeService.selectDictDataByType(dictType));
try {
return AjaxResult.success(dictTypeService.selectDictDataByType(dictType));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -79,8 +105,13 @@ public class DictDataController extends BaseController {
@Log(title = "字典数据", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody DictData dict) {
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.insertDictData(dict));
try {
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.insertDictData(dict));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -90,8 +121,13 @@ public class DictDataController extends BaseController {
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody DictData dict) {
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.updateDictData(dict));
try {
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.updateDictData(dict));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -101,6 +137,11 @@ public class DictDataController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictCodes}")
public AjaxResult remove(@PathVariable Long[] dictCodes) {
return toAjax(dictDataService.deleteDictDataByIds(dictCodes));
try {
return toAjax(dictDataService.deleteDictDataByIds(dictCodes));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,7 +1,11 @@
package com.hchyun.web.controller.system;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -32,24 +36,36 @@ import com.hchyun.system.service.DictTypeService;
@RestController
@RequestMapping("/system/dict/type")
public class DictTypeController extends BaseController {
private Logger logger = LoggerFactory.getLogger(DictTypeController.class);
@Autowired
private DictTypeService dictTypeService;
@PreAuthorize("@hchyun.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(DictType dictType) {
startPage();
List<DictType> list = dictTypeService.selectDictTypeList(dictType);
return getDataTable(list);
public Serializable list(DictType dictType) {
try {
startPage();
List<DictType> list = dictTypeService.selectDictTypeList(dictType);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:dict:export')")
@GetMapping("/export")
public AjaxResult export(DictType dictType) {
List<DictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<DictType> util = new ExcelUtil<DictType>(DictType.class);
return util.exportExcel(list, "字典类型");
try {
List<DictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<DictType> util = new ExcelUtil<DictType>(DictType.class);
return util.exportExcel(list, "字典类型");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -58,7 +74,12 @@ public class DictTypeController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictId}")
public AjaxResult getInfo(@PathVariable Long dictId) {
return AjaxResult.success(dictTypeService.selectDictTypeById(dictId));
try {
return AjaxResult.success(dictTypeService.selectDictTypeById(dictId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -68,11 +89,16 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody DictType dict) {
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
try {
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictTypeService.insertDictType(dict));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictTypeService.insertDictType(dict));
}
/**
@ -82,11 +108,16 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody DictType dict) {
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
try {
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictTypeService.updateDictType(dict));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictTypeService.updateDictType(dict));
}
/**
@ -96,7 +127,12 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictIds}")
public AjaxResult remove(@PathVariable Long[] dictIds) {
return toAjax(dictTypeService.deleteDictTypeByIds(dictIds));
try {
return toAjax(dictTypeService.deleteDictTypeByIds(dictIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -106,8 +142,13 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/clearCache")
public AjaxResult clearCache() {
dictTypeService.clearCache();
return AjaxResult.success();
try {
dictTypeService.clearCache();
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -115,7 +156,12 @@ public class DictTypeController extends BaseController {
*/
@GetMapping("/optionselect")
public AjaxResult optionselect() {
List<DictType> dictTypes = dictTypeService.selectDictTypeAll();
return AjaxResult.success(dictTypes);
try {
List<DictType> dictTypes = dictTypeService.selectDictTypeAll();
return AjaxResult.success(dictTypes);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -3,6 +3,9 @@ package com.hchyun.web.controller.system;
import java.util.List;
import java.util.Set;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@ -27,6 +30,8 @@ import com.hchyun.system.service.MenuService;
*/
@RestController
public class LoginController {
private Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private LoginService loginService;
@ -47,12 +52,17 @@ public class LoginController {
*/
@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;
try {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -62,17 +72,22 @@ public class LoginController {
*/
@GetMapping("getInfo")
public AjaxResult getInfo() {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
User user = loginUser.getUser();
// 角色集合
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;
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
User user = loginUser.getUser();
// 角色集合
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;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -82,10 +97,15 @@ public class LoginController {
*/
@GetMapping("getRouters")
public AjaxResult getRouters() {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// 用户信息
User user = loginUser.getUser();
List<Menu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
return AjaxResult.success(menuService.buildMenus(menus));
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// 用户信息
User user = loginUser.getUser();
List<Menu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
return AjaxResult.success(menuService.buildMenus(menus));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -2,6 +2,9 @@ package com.hchyun.web.controller.system;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -35,6 +38,8 @@ import com.hchyun.system.service.MenuService;
@RestController
@RequestMapping("/system/menu")
public class MenuController extends BaseController {
private Logger logger = LoggerFactory.getLogger(MenuController.class);
@Autowired
private MenuService menuService;
@ -47,10 +52,15 @@ public class MenuController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:menu:list')")
@GetMapping("/list")
public AjaxResult list(Menu menu) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<Menu> menus = menuService.selectMenuList(menu, userId);
return AjaxResult.success(menus);
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<Menu> menus = menuService.selectMenuList(menu, userId);
return AjaxResult.success(menus);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -59,7 +69,12 @@ public class MenuController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:menu:query')")
@GetMapping(value = "/{menuId}")
public AjaxResult getInfo(@PathVariable Long menuId) {
return AjaxResult.success(menuService.selectMenuById(menuId));
try {
return AjaxResult.success(menuService.selectMenuById(menuId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -67,10 +82,15 @@ public class MenuController extends BaseController {
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(Menu menu) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<Menu> menus = menuService.selectMenuList(menu, userId);
return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<Menu> menus = menuService.selectMenuList(menu, userId);
return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -78,12 +98,17 @@ public class MenuController extends BaseController {
*/
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
List<Menu> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
ajax.put("menus", menuService.buildMenuTreeSelect(menus));
return ajax;
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
List<Menu> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
ajax.put("menus", menuService.buildMenuTreeSelect(menus));
return ajax;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -93,14 +118,19 @@ public class MenuController extends BaseController {
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Menu menu) {
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
&& !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
try {
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
&& !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
}
menu.setCreateBy(SecurityUtils.getUserId());
return toAjax(menuService.insertMenu(menu));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
menu.setCreateBy(SecurityUtils.getUserId());
return toAjax(menuService.insertMenu(menu));
}
/**
@ -110,16 +140,21 @@ public class MenuController extends BaseController {
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Menu menu) {
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
&& !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
} else if (menu.getMenuId().equals(menu.getParentId())) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
try {
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
&& !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
} else if (menu.getMenuId().equals(menu.getParentId())) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
}
menu.setUpdateBy(SecurityUtils.getUserId());
return toAjax(menuService.updateMenu(menu));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
menu.setUpdateBy(SecurityUtils.getUserId());
return toAjax(menuService.updateMenu(menu));
}
/**
@ -129,12 +164,17 @@ public class MenuController extends BaseController {
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{menuId}")
public AjaxResult remove(@PathVariable("menuId") Long menuId) {
if (menuService.hasChildByMenuId(menuId)) {
return AjaxResult.error("存在子菜单,不允许删除");
try {
if (menuService.hasChildByMenuId(menuId)) {
return AjaxResult.error("存在子菜单,不允许删除");
}
if (menuService.checkMenuExistRole(menuId)) {
return AjaxResult.error("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
if (menuService.checkMenuExistRole(menuId)) {
return AjaxResult.error("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}
}

View File

@ -1,7 +1,11 @@
package com.hchyun.web.controller.system;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -30,6 +34,8 @@ import com.hchyun.system.service.NoticeService;
@RestController
@RequestMapping("/system/notice")
public class NoticeController extends BaseController {
private Logger logger = LoggerFactory.getLogger(NoticeController.class);
@Autowired
private NoticeService noticeService;
@ -38,10 +44,15 @@ public class NoticeController extends BaseController {
*/
@PreAuthorize("@hchyun.hasPermi('system:notice:list')")
@GetMapping("/list")
public TableDataInfo list(Notice notice) {
startPage();
List<Notice> list = noticeService.selectNoticeList(notice);
return getDataTable(list);
public Serializable list(Notice notice) {
try {
startPage();
List<Notice> list = noticeService.selectNoticeList(notice);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -50,7 +61,12 @@ public class NoticeController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:notice:query')")
@GetMapping(value = "/{noticeId}")
public AjaxResult getInfo(@PathVariable Long noticeId) {
return AjaxResult.success(noticeService.selectNoticeById(noticeId));
try {
return AjaxResult.success(noticeService.selectNoticeById(noticeId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -60,8 +76,13 @@ public class NoticeController extends BaseController {
@Log(title = "通知公告", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Notice notice) {
notice.setCreateBy(SecurityUtils.getUserId());
return toAjax(noticeService.insertNotice(notice));
try {
notice.setCreateBy(SecurityUtils.getUserId());
return toAjax(noticeService.insertNotice(notice));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -71,8 +92,13 @@ public class NoticeController extends BaseController {
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Notice notice) {
notice.setUpdateBy(SecurityUtils.getUserId());
return toAjax(noticeService.updateNotice(notice));
try {
notice.setUpdateBy(SecurityUtils.getUserId());
return toAjax(noticeService.updateNotice(notice));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -82,6 +108,11 @@ public class NoticeController extends BaseController {
@Log(title = "通知公告", businessType = BusinessType.DELETE)
@DeleteMapping("/{noticeIds}")
public AjaxResult remove(@PathVariable Long[] noticeIds) {
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
try {
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,7 +1,11 @@
package com.hchyun.web.controller.system;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -32,6 +36,9 @@ import com.hchyun.system.service.PostService;
@RestController
@RequestMapping("/system/post")
public class PostController extends BaseController {
private Logger logger = LoggerFactory.getLogger(PostController.class);
@Autowired
private PostService postService;
@ -40,19 +47,29 @@ public class PostController extends BaseController {
*/
@PreAuthorize("@hchyun.hasPermi('system:post:list')")
@GetMapping("/list")
public TableDataInfo list(Post post) {
startPage();
List<Post> list = postService.selectPostList(post);
return getDataTable(list);
public Serializable list(Post post) {
try {
startPage();
List<Post> list = postService.selectPostList(post);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:post:export')")
@GetMapping("/export")
public AjaxResult export(Post post) {
List<Post> list = postService.selectPostList(post);
ExcelUtil<Post> util = new ExcelUtil<Post>(Post.class);
return util.exportExcel(list, "岗位数据");
try {
List<Post> list = postService.selectPostList(post);
ExcelUtil<Post> util = new ExcelUtil<Post>(Post.class);
return util.exportExcel(list, "岗位数据");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -61,7 +78,12 @@ public class PostController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:post:query')")
@GetMapping(value = "/{postId}")
public AjaxResult getInfo(@PathVariable Long postId) {
return AjaxResult.success(postService.selectPostById(postId));
try {
return AjaxResult.success(postService.selectPostById(postId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -71,13 +93,18 @@ public class PostController extends BaseController {
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Post post) {
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
try {
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setCreateBy(SecurityUtils.getUserId());
return toAjax(postService.insertPost(post));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
post.setCreateBy(SecurityUtils.getUserId());
return toAjax(postService.insertPost(post));
}
/**
@ -87,13 +114,18 @@ public class PostController extends BaseController {
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Post post) {
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
try {
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setUpdateBy(SecurityUtils.getUserId());
return toAjax(postService.updatePost(post));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
post.setUpdateBy(SecurityUtils.getUserId());
return toAjax(postService.updatePost(post));
}
/**
@ -103,7 +135,12 @@ public class PostController extends BaseController {
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{postIds}")
public AjaxResult remove(@PathVariable Long[] postIds) {
return toAjax(postService.deletePostByIds(postIds));
try {
return toAjax(postService.deletePostByIds(postIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -111,7 +148,12 @@ public class PostController extends BaseController {
*/
@GetMapping("/optionselect")
public AjaxResult optionselect() {
List<Post> posts = postService.selectPostAll();
return AjaxResult.success(posts);
try {
List<Post> posts = postService.selectPostAll();
return AjaxResult.success(posts);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -2,6 +2,9 @@ package com.hchyun.web.controller.system;
import java.io.IOException;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@ -32,6 +35,8 @@ import com.hchyun.system.service.UserService;
@RestController
@RequestMapping("/system/user/profile")
public class ProfileController extends BaseController {
private Logger logger = LoggerFactory.getLogger(ProfileController.class);
@Autowired
private UserService userService;
@ -43,12 +48,17 @@ public class ProfileController extends BaseController {
*/
@GetMapping
public AjaxResult profile() {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
User user = loginUser.getUser();
AjaxResult ajax = AjaxResult.success(user);
ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
return ajax;
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
User user = loginUser.getUser();
AjaxResult ajax = AjaxResult.success(user);
ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
return ajax;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -57,17 +67,22 @@ public class ProfileController extends BaseController {
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult updateProfile(@RequestBody User user) {
if (userService.updateUserProfile(user) > 0) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// 更新缓存用户信息
loginUser.getUser().setNickName(user.getNickName());
loginUser.getUser().setPhonenumber(user.getPhonenumber());
loginUser.getUser().setEmail(user.getEmail());
loginUser.getUser().setSex(user.getSex());
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
try {
if (userService.updateUserProfile(user) > 0) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// 更新缓存用户信息
loginUser.getUser().setNickName(user.getNickName());
loginUser.getUser().setPhonenumber(user.getPhonenumber());
loginUser.getUser().setEmail(user.getEmail());
loginUser.getUser().setSex(user.getSex());
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改个人信息异常,请联系管理员");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.error("修改个人信息异常,请联系管理员");
}
/**
@ -76,22 +91,27 @@ public class ProfileController extends BaseController {
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
String userName = loginUser.getUsername();
String password = loginUser.getPassword();
if (!SecurityUtils.matchesPassword(oldPassword, password)) {
return AjaxResult.error("修改密码失败,旧密码错误");
try {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
String userName = loginUser.getUsername();
String password = loginUser.getPassword();
if (!SecurityUtils.matchesPassword(oldPassword, password)) {
return AjaxResult.error("修改密码失败,旧密码错误");
}
if (SecurityUtils.matchesPassword(newPassword, password)) {
return AjaxResult.error("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
// 更新缓存用户密码
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改密码异常,请联系管理员");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
if (SecurityUtils.matchesPassword(newPassword, password)) {
return AjaxResult.error("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
// 更新缓存用户密码
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改密码异常,请联系管理员");
}
/**
@ -100,18 +120,23 @@ public class ProfileController extends BaseController {
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
String avatar = FileUploadUtils.upload(HchYunConfig.getAvatarPath(), file);
if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", avatar);
// 更新缓存用户头像
loginUser.getUser().setAvatar(avatar);
tokenService.setLoginUser(loginUser);
return ajax;
try {
if (!file.isEmpty()) {
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
String avatar = FileUploadUtils.upload(HchYunConfig.getAvatarPath(), file);
if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", avatar);
// 更新缓存用户头像
loginUser.getUser().setAvatar(avatar);
tokenService.setLoginUser(loginUser);
return ajax;
}
}
return AjaxResult.error("上传图片异常,请联系管理员");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.error("上传图片异常,请联系管理员");
}
}

View File

@ -1,8 +1,11 @@
package com.hchyun.web.controller.system;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -39,6 +42,8 @@ import com.hchyun.system.service.UserService;
@RestController
@RequestMapping("/system/role")
public class RoleController extends BaseController {
private Logger logger = LoggerFactory.getLogger(RoleController.class);
@Autowired
private RoleService roleService;
@ -53,19 +58,29 @@ public class RoleController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(Role role) {
startPage();
List<Role> list = roleService.selectRoleList(role);
return getDataTable(list);
public Serializable list(Role role) {
try {
startPage();
List<Role> list = roleService.selectRoleList(role);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:role:export')")
@GetMapping("/export")
public AjaxResult export(Role role) {
List<Role> list = roleService.selectRoleList(role);
ExcelUtil<Role> util = new ExcelUtil<Role>(Role.class);
return util.exportExcel(list, "角色数据");
try {
List<Role> list = roleService.selectRoleList(role);
ExcelUtil<Role> util = new ExcelUtil<Role>(Role.class);
return util.exportExcel(list, "角色数据");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -74,7 +89,12 @@ public class RoleController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public AjaxResult getInfo(@PathVariable Long roleId) {
return AjaxResult.success(roleService.selectRoleById(roleId));
try {
return AjaxResult.success(roleService.selectRoleById(roleId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -84,13 +104,18 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Role role) {
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
try {
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setCreateBy(SecurityUtils.getUserId());
return toAjax(roleService.insertRole(role));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
role.setCreateBy(SecurityUtils.getUserId());
return toAjax(roleService.insertRole(role));
}
@ -101,25 +126,30 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Role role) {
roleService.checkRoleAllowed(role);
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setUpdateBy(SecurityUtils.getUserId());
if (roleService.updateRole(role) > 0) {
// 更新缓存用户权限
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
tokenService.setLoginUser(loginUser);
try {
roleService.checkRoleAllowed(role);
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
return AjaxResult.success();
role.setUpdateBy(SecurityUtils.getUserId());
if (roleService.updateRole(role) > 0) {
// 更新缓存用户权限
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
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 AjaxResult.success();
}
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
@ -129,8 +159,13 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public AjaxResult dataScope(@RequestBody Role role) {
roleService.checkRoleAllowed(role);
return toAjax(roleService.authDataScope(role));
try {
roleService.checkRoleAllowed(role);
return toAjax(roleService.authDataScope(role));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -140,9 +175,14 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody Role role) {
roleService.checkRoleAllowed(role);
role.setUpdateBy(SecurityUtils.getUserId());
return toAjax(roleService.updateRoleStatus(role));
try {
roleService.checkRoleAllowed(role);
role.setUpdateBy(SecurityUtils.getUserId());
return toAjax(roleService.updateRoleStatus(role));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -152,7 +192,12 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public AjaxResult remove(@PathVariable Long[] roleIds) {
return toAjax(roleService.deleteRoleByIds(roleIds));
try {
return toAjax(roleService.deleteRoleByIds(roleIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -161,10 +206,15 @@ public class RoleController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect(Integer type) {
if (type == 1 || type == 2) {
return AjaxResult.success(roleService.selectRoleAll(type));
} else {
return AjaxResult.error(ReturnConstants.STATE_ERROR);
try {
if (type == 1 || type == 2) {
return AjaxResult.success(roleService.selectRoleAll(type));
} else {
return AjaxResult.error(ReturnConstants.STATE_ERROR);
}
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,8 +1,12 @@
package com.hchyun.web.controller.system;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -41,6 +45,8 @@ import com.hchyun.system.service.UserService;
@RestController
@RequestMapping("/system/user")
public class UserController extends BaseController {
private Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@ -58,37 +64,57 @@ public class UserController extends BaseController {
*/
@PreAuthorize("@hchyun.hasPermi('system:user:list')")
@GetMapping("/list")
public TableDataInfo list(User user) {
startPage();
List<User> list = userService.selectUserList(user);
return getDataTable(list);
public Serializable list(User user) {
try {
startPage();
List<User> list = userService.selectUserList(user);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:user:export')")
@GetMapping("/export")
public AjaxResult export(User user) {
List<User> list = userService.selectUserList(user);
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
return util.exportExcel(list, "用户数据");
try {
List<User> list = userService.selectUserList(user);
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
return util.exportExcel(list, "用户数据");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@PreAuthorize("@hchyun.hasPermi('system:user:import')")
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
List<User> userList = util.importExcel(file.getInputStream());
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long operName = loginUser.getUser().getUserId();
String message = userService.importUser(userList, updateSupport, operName);
return AjaxResult.success(message);
try {
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
List<User> userList = util.importExcel(file.getInputStream());
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long operName = loginUser.getUser().getUserId();
String message = userService.importUser(userList, updateSupport, operName);
return AjaxResult.success(message);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@GetMapping("/importTemplate")
public AjaxResult importTemplate() {
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
return util.importTemplateExcel("用户数据");
try {
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
return util.importTemplateExcel("用户数据");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -97,16 +123,21 @@ public class UserController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:user:query')")
@GetMapping(value = {"/", "/{userId}"})
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
AjaxResult ajax = AjaxResult.success();
List<Role> roles = roleService.selectRoleAll(0);
ajax.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
ajax.put("posts", postService.selectPostAll());
if (StringUtils.isNotNull(userId)) {
ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
try {
AjaxResult ajax = AjaxResult.success();
List<Role> roles = roleService.selectRoleAll(0);
ajax.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
ajax.put("posts", postService.selectPostAll());
if (StringUtils.isNotNull(userId)) {
ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
}
return ajax;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return ajax;
}
/**
@ -116,16 +147,21 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody User user) {
if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
} else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
try {
if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
} else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setCreateBy(SecurityUtils.getUserId());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
user.setCreateBy(SecurityUtils.getUserId());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}
/**
@ -135,14 +171,19 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody User user) {
userService.checkUserAllowed(user);
if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
try {
userService.checkUserAllowed(user);
if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.updateUser(user));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.updateUser(user));
}
/**
@ -152,7 +193,12 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public AjaxResult remove(@PathVariable Long[] userIds) {
return toAjax(userService.deleteUserByIds(userIds));
try {
return toAjax(userService.deleteUserByIds(userIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -162,10 +208,15 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public AjaxResult resetPwd(@RequestBody User user) {
userService.checkUserAllowed(user);
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.resetPwd(user));
try {
userService.checkUserAllowed(user);
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.resetPwd(user));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -175,8 +226,13 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody User user) {
userService.checkUserAllowed(user);
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.updateUserStatus(user));
try {
userService.checkUserAllowed(user);
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.updateUserStatus(user));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -25,7 +25,7 @@ import com.hchyun.common.utils.sql.SqlUtil;
* @author hchyun
*/
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(BaseController.class);
protected final Logger log = LoggerFactory.getLogger(BaseController.class);
/**
* 将前台传递过来的日期格式的字符串自动转化为Date类型

View File

@ -1,6 +1,7 @@
package com.hchyun.generator.controller;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -9,6 +10,8 @@ import javax.servlet.http.HttpServletResponse;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.utils.ServerResult;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
@ -39,6 +42,8 @@ import com.hchyun.generator.service.GenTableService;
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {
private Logger logger = LoggerFactory.getLogger(GenController.class);
@Autowired
private GenTableService genTableService;
@ -50,10 +55,15 @@ public class GenController extends BaseController {
*/
@PreAuthorize("@hchyun.hasPermi('tool:gen:list')")
@GetMapping("/list")
public TableDataInfo genList(GenTable genTable) {
startPage();
List<GenTable> list = genTableService.selectGenTableList(genTable);
return getDataTable(list);
public Serializable genList(GenTable genTable) {
try {
startPage();
List<GenTable> list = genTableService.selectGenTableList(genTable);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -62,14 +72,19 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:query')")
@GetMapping(value = "/{talbleId}")
public AjaxResult getInfo(@PathVariable Long talbleId) {
GenTable table = genTableService.selectGenTableById(talbleId);
List<GenTable> tables = genTableService.selectGenTableAll();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
Map<String, Object> map = new HashMap<String, Object>();
map.put("info", table);
map.put("rows", list);
map.put("tables", tables);
return AjaxResult.success(map);
try {
GenTable table = genTableService.selectGenTableById(talbleId);
List<GenTable> tables = genTableService.selectGenTableAll();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
Map<String, Object> map = new HashMap<String, Object>();
map.put("info", table);
map.put("rows", list);
map.put("tables", tables);
return AjaxResult.success(map);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -77,10 +92,15 @@ public class GenController extends BaseController {
*/
@PreAuthorize("@hchyun.hasPermi('tool:gen:list')")
@GetMapping("/db/list")
public TableDataInfo dataList(GenTable genTable) {
startPage();
List<GenTable> list = genTableService.selectDbTableList(genTable);
return getDataTable(list);
public Serializable dataList(GenTable genTable) {
try {
startPage();
List<GenTable> list = genTableService.selectDbTableList(genTable);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -88,12 +108,17 @@ public class GenController extends BaseController {
*/
@PreAuthorize("@hchyun.hasPermi('tool:gen:list')")
@GetMapping(value = "/column/{talbleId}")
public TableDataInfo columnList(Long tableId) {
TableDataInfo dataInfo = new TableDataInfo();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
dataInfo.setRows(list);
dataInfo.setTotal(list.size());
return dataInfo;
public Serializable columnList(Long tableId) {
try {
TableDataInfo dataInfo = new TableDataInfo();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
dataInfo.setRows(list);
dataInfo.setTotal(list.size());
return dataInfo;
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -103,11 +128,16 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable")
public AjaxResult importTableSave(String tables) {
String[] tableNames = Convert.toStrArray(tables);
// 查询表信息
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
genTableService.importGenTable(tableList);
return AjaxResult.success();
try {
String[] tableNames = Convert.toStrArray(tables);
// 查询表信息
List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
genTableService.importGenTable(tableList);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -118,9 +148,14 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult editSave(@Validated @RequestBody GenTable genTable) {
genTableService.validateEdit(genTable);
genTableService.updateGenTable(genTable);
return AjaxResult.success();
try {
genTableService.validateEdit(genTable);
genTableService.updateGenTable(genTable);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -149,8 +184,13 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:preview')")
@GetMapping("/preview/{tableId}")
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException {
Map<String, String> dataMap = genTableService.previewCode(tableId);
return AjaxResult.success(dataMap);
try {
Map<String, String> dataMap = genTableService.previewCode(tableId);
return AjaxResult.success(dataMap);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -171,11 +211,16 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}")
public AjaxResult genCode(@PathVariable("tableName") String tableName) {
boolean start = genTableService.generatorCode(tableName);
if (start) {
return AjaxResult.success();
} else {
return AjaxResult.error("模板渲染失败!");
try {
boolean start = genTableService.generatorCode(tableName);
if (start) {
return AjaxResult.success();
} else {
return AjaxResult.error("模板渲染失败!");
}
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@ -186,8 +231,13 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@GetMapping("/synchDb/{tableName}")
public AjaxResult synchDb(@PathVariable("tableName") String tableName) {
genTableService.synchDb(tableName);
return AjaxResult.success();
try {
genTableService.synchDb(tableName);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**

View File

@ -53,8 +53,6 @@ public class InterTableController extends HcyBaseController {
@Autowired
private InterTableService interTableService;
@Autowired
private ApiclassService apiclassService;
/**
* 查询接口信息列表

View File

@ -1,8 +1,12 @@
package com.hchyun.quartz.controller;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -21,8 +25,8 @@ import com.hchyun.common.enums.BusinessType;
import com.hchyun.common.exception.job.TaskException;
import com.hchyun.common.utils.SecurityUtils;
import com.hchyun.common.utils.poi.ExcelUtil;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.service.ISysJobService;
import com.hchyun.quartz.entity.Job;
import com.hchyun.quartz.service.JobService;
import com.hchyun.quartz.util.CronUtils;
/**
@ -33,18 +37,25 @@ import com.hchyun.quartz.util.CronUtils;
@RestController
@RequestMapping("/monitor/job")
public class JobController extends BaseController {
private Logger logger = LoggerFactory.getLogger(JobController.class);
@Autowired
private ISysJobService jobService;
private JobService jobService;
/**
* 查询定时任务列表
*/
@PreAuthorize("@hchyun.hasPermi('monitor:job:list')")
@GetMapping("/list")
public TableDataInfo list(SysJob sysJob) {
startPage();
List<SysJob> list = jobService.selectJobList(sysJob);
return getDataTable(list);
public Serializable list(Job job) {
try {
startPage();
List<Job> list = jobService.selectJobList(job);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -53,10 +64,15 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:export')")
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysJob sysJob) {
List<SysJob> list = jobService.selectJobList(sysJob);
ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
return util.exportExcel(list, "定时任务");
public AjaxResult export(Job job) {
try {
List<Job> list = jobService.selectJobList(job);
ExcelUtil<Job> util = new ExcelUtil<Job>(Job.class);
return util.exportExcel(list, "定时任务");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -65,7 +81,12 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:query')")
@GetMapping(value = "/{jobId}")
public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
return AjaxResult.success(jobService.selectJobById(jobId));
try {
return AjaxResult.success(jobService.selectJobById(jobId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -74,12 +95,17 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:add')")
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
if (!CronUtils.isValid(sysJob.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
public AjaxResult add(@RequestBody Job job) throws SchedulerException, TaskException {
try {
if (!CronUtils.isValid(job.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
}
job.setCreateBy(SecurityUtils.getUserId());
return toAjax(jobService.insertJob(job));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
sysJob.setCreateBy(SecurityUtils.getUserId());
return toAjax(jobService.insertJob(sysJob));
}
/**
@ -88,12 +114,17 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:edit')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody SysJob sysJob) throws SchedulerException, TaskException {
if (!CronUtils.isValid(sysJob.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
public AjaxResult edit(@RequestBody Job job) throws SchedulerException, TaskException {
try {
if (!CronUtils.isValid(job.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
}
job.setUpdateBy(SecurityUtils.getUserId());
return toAjax(jobService.updateJob(job));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
sysJob.setUpdateBy(SecurityUtils.getUserId());
return toAjax(jobService.updateJob(sysJob));
}
/**
@ -102,10 +133,15 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:changeStatus')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException {
SysJob newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob));
public AjaxResult changeStatus(@RequestBody Job job) throws SchedulerException {
try {
Job newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -114,9 +150,14 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:changeStatus')")
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/run")
public AjaxResult run(@RequestBody SysJob job) throws SchedulerException {
jobService.run(job);
return AjaxResult.success();
public AjaxResult run(@RequestBody Job job) throws SchedulerException {
try {
jobService.run(job);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -126,7 +167,12 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobIds}")
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
try {
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -1,7 +1,11 @@
package com.hchyun.quartz.controller;
import java.io.Serializable;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -15,8 +19,8 @@ import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.core.page.TableDataInfo;
import com.hchyun.common.enums.BusinessType;
import com.hchyun.common.utils.poi.ExcelUtil;
import com.hchyun.quartz.entity.SysJobLog;
import com.hchyun.quartz.service.ISysJobLogService;
import com.hchyun.quartz.entity.JobLog;
import com.hchyun.quartz.service.JobLogService;
/**
* 调度日志操作处理
@ -26,18 +30,25 @@ import com.hchyun.quartz.service.ISysJobLogService;
@RestController
@RequestMapping("/monitor/jobLog")
public class JobLogController extends BaseController {
private Logger logger = LoggerFactory.getLogger(JobLogController.class);
@Autowired
private ISysJobLogService jobLogService;
private JobLogService jobLogService;
/**
* 查询定时任务调度日志列表
*/
@PreAuthorize("@hchyun.hasPermi('monitor:job:list')")
@GetMapping("/list")
public TableDataInfo list(SysJobLog sysJobLog) {
startPage();
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
return getDataTable(list);
public Serializable list(JobLog jobLog) {
try {
startPage();
List<JobLog> list = jobLogService.selectJobLogList(jobLog);
return getDataTable(list);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -46,10 +57,15 @@ public class JobLogController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:export')")
@Log(title = "任务调度日志", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysJobLog sysJobLog) {
List<SysJobLog> list = jobLogService.selectJobLogList(sysJobLog);
ExcelUtil<SysJobLog> util = new ExcelUtil<SysJobLog>(SysJobLog.class);
return util.exportExcel(list, "调度日志");
public AjaxResult export(JobLog jobLog) {
try {
List<JobLog> list = jobLogService.selectJobLogList(jobLog);
ExcelUtil<JobLog> util = new ExcelUtil<JobLog>(JobLog.class);
return util.exportExcel(list, "调度日志");
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -58,7 +74,12 @@ public class JobLogController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long jobLogId) {
return AjaxResult.success(jobLogService.selectJobLogById(jobLogId));
try {
return AjaxResult.success(jobLogService.selectJobLogById(jobLogId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
@ -69,7 +90,12 @@ public class JobLogController extends BaseController {
@Log(title = "定时任务调度日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobLogIds}")
public AjaxResult remove(@PathVariable Long[] jobLogIds) {
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
try {
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -79,7 +105,12 @@ public class JobLogController extends BaseController {
@Log(title = "调度日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean() {
jobLogService.cleanJobLog();
return AjaxResult.success();
try {
jobLogService.cleanJobLog();
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -2,28 +2,28 @@ package com.hchyun.quartz.dao;
import java.util.List;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.Job;
/**
* 调度任务信息 数据层
*
* @author hchyun
*/
public interface SysJobDao {
public interface JobDao {
/**
* 查询调度任务日志集合
*
* @param job 调度信息
* @return 操作日志集合
*/
public List<SysJob> selectJobList(SysJob job);
public List<Job> selectJobList(Job job);
/**
* 查询所有调度任务
*
* @return 调度任务列表
*/
public List<SysJob> selectJobAll();
public List<Job> selectJobAll();
/**
* 通过调度ID查询调度任务信息
@ -31,7 +31,7 @@ public interface SysJobDao {
* @param jobId 调度ID
* @return 角色对象信息
*/
public SysJob selectJobById(Long jobId);
public Job selectJobById(Long jobId);
/**
* 通过调度ID删除调度任务信息
@ -55,7 +55,7 @@ public interface SysJobDao {
* @param job 调度任务信息
* @return 结果
*/
public int updateJob(SysJob job);
public int updateJob(Job job);
/**
* 新增调度任务信息
@ -63,5 +63,5 @@ public interface SysJobDao {
* @param job 调度任务信息
* @return 结果
*/
public int insertJob(SysJob job);
public int insertJob(Job job);
}

View File

@ -2,28 +2,28 @@ package com.hchyun.quartz.dao;
import java.util.List;
import com.hchyun.quartz.entity.SysJobLog;
import com.hchyun.quartz.entity.JobLog;
/**
* 调度任务日志信息 数据层
*
* @author hchyun
*/
public interface SysJobLogDao {
public interface JobLogDao {
/**
* 获取quartz调度器日志的计划任务
*
* @param jobLog 调度日志信息
* @return 调度任务日志集合
*/
public List<SysJobLog> selectJobLogList(SysJobLog jobLog);
public List<JobLog> selectJobLogList(JobLog jobLog);
/**
* 查询所有调度任务日志
*
* @return 调度任务日志列表
*/
public List<SysJobLog> selectJobLogAll();
public List<JobLog> selectJobLogAll();
/**
* 通过调度任务日志ID查询调度信息
@ -31,7 +31,7 @@ public interface SysJobLogDao {
* @param jobLogId 调度任务日志ID
* @return 调度任务日志对象信息
*/
public SysJobLog selectJobLogById(Long jobLogId);
public JobLog selectJobLogById(Long jobLogId);
/**
* 新增任务日志
@ -39,7 +39,7 @@ public interface SysJobLogDao {
* @param jobLog 调度日志信息
* @return 结果
*/
public int insertJobLog(SysJobLog jobLog);
public int insertJobLog(JobLog jobLog);
/**
* 批量删除调度日志信息

View File

@ -20,7 +20,7 @@ import com.hchyun.quartz.util.CronUtils;
*
* @author hchyun
*/
public class SysJob extends BaseEntity implements Serializable {
public class Job extends BaseEntity implements Serializable {
/**

View File

@ -12,7 +12,7 @@ import com.hchyun.common.core.entity.BaseEntity;
*
* @author hchyun
*/
public class SysJobLog extends BaseEntity {
public class JobLog extends BaseEntity {
/**

View File

@ -2,21 +2,21 @@ package com.hchyun.quartz.service;
import java.util.List;
import com.hchyun.quartz.entity.SysJobLog;
import com.hchyun.quartz.entity.JobLog;
/**
* 定时任务调度日志信息信息 服务层
*
* @author hchyun
*/
public interface ISysJobLogService {
public interface JobLogService {
/**
* 获取quartz调度器日志的计划任务
*
* @param jobLog 调度日志信息
* @return 调度任务日志集合
*/
public List<SysJobLog> selectJobLogList(SysJobLog jobLog);
public List<JobLog> selectJobLogList(JobLog jobLog);
/**
* 通过调度任务日志ID查询调度信息
@ -24,14 +24,14 @@ public interface ISysJobLogService {
* @param jobLogId 调度任务日志ID
* @return 调度任务日志对象信息
*/
public SysJobLog selectJobLogById(Long jobLogId);
public JobLog selectJobLogById(Long jobLogId);
/**
* 新增任务日志
*
* @param jobLog 调度日志信息
*/
public void addJobLog(SysJobLog jobLog);
public void addJobLog(JobLog jobLog);
/**
* 批量删除调度日志信息

View File

@ -4,21 +4,21 @@ import java.util.List;
import org.quartz.SchedulerException;
import com.hchyun.common.exception.job.TaskException;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.Job;
/**
* 定时任务调度信息信息 服务层
*
* @author hchyun
*/
public interface ISysJobService {
public interface JobService {
/**
* 获取quartz调度器的计划任务
*
* @param job 调度信息
* @return 调度任务集合
*/
public List<SysJob> selectJobList(SysJob job);
public List<Job> selectJobList(Job job);
/**
* 通过调度任务ID查询调度信息
@ -26,7 +26,7 @@ public interface ISysJobService {
* @param jobId 调度任务ID
* @return 调度任务对象信息
*/
public SysJob selectJobById(Long jobId);
public Job selectJobById(Long jobId);
/**
* 暂停任务
@ -34,7 +34,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public int pauseJob(SysJob job) throws SchedulerException;
public int pauseJob(Job job) throws SchedulerException;
/**
* 恢复任务
@ -42,7 +42,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public int resumeJob(SysJob job) throws SchedulerException;
public int resumeJob(Job job) throws SchedulerException;
/**
* 删除任务后所对应的trigger也将被删除
@ -50,7 +50,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public int deleteJob(SysJob job) throws SchedulerException;
public int deleteJob(Job job) throws SchedulerException;
/**
* 批量删除调度信息
@ -66,7 +66,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public int changeStatus(SysJob job) throws SchedulerException;
public int changeStatus(Job job) throws SchedulerException;
/**
* 立即运行任务
@ -74,7 +74,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public void run(SysJob job) throws SchedulerException;
public void run(Job job) throws SchedulerException;
/**
* 新增任务
@ -82,7 +82,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public int insertJob(SysJob job) throws SchedulerException, TaskException;
public int insertJob(Job job) throws SchedulerException, TaskException;
/**
* 更新任务
@ -90,7 +90,7 @@ public interface ISysJobService {
* @param job 调度信息
* @return 结果
*/
public int updateJob(SysJob job) throws SchedulerException, TaskException;
public int updateJob(Job job) throws SchedulerException, TaskException;
/**
* 校验cron表达式是否有效

View File

@ -4,9 +4,9 @@ import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.quartz.entity.SysJobLog;
import com.hchyun.quartz.dao.SysJobLogDao;
import com.hchyun.quartz.service.ISysJobLogService;
import com.hchyun.quartz.entity.JobLog;
import com.hchyun.quartz.dao.JobLogDao;
import com.hchyun.quartz.service.JobLogService;
/**
* 定时任务调度日志信息 服务层
@ -14,9 +14,9 @@ import com.hchyun.quartz.service.ISysJobLogService;
* @author hchyun
*/
@Service
public class SysJobLogServiceImpl implements ISysJobLogService {
public class JobLogServiceImpl implements JobLogService {
@Autowired
private SysJobLogDao jobLogMapper;
private JobLogDao jobLogMapper;
/**
* 获取quartz调度器日志的计划任务
@ -25,7 +25,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService {
* @return 调度任务日志集合
*/
@Override
public List<SysJobLog> selectJobLogList(SysJobLog jobLog) {
public List<JobLog> selectJobLogList(JobLog jobLog) {
return jobLogMapper.selectJobLogList(jobLog);
}
@ -36,7 +36,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService {
* @return 调度任务日志对象信息
*/
@Override
public SysJobLog selectJobLogById(Long jobLogId) {
public JobLog selectJobLogById(Long jobLogId) {
return jobLogMapper.selectJobLogById(jobLogId);
}
@ -46,7 +46,7 @@ public class SysJobLogServiceImpl implements ISysJobLogService {
* @param jobLog 调度日志信息
*/
@Override
public void addJobLog(SysJobLog jobLog) {
public void addJobLog(JobLog jobLog) {
jobLogMapper.insertJobLog(jobLog);
}

View File

@ -12,9 +12,9 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hchyun.common.constant.ScheduleConstants;
import com.hchyun.common.exception.job.TaskException;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.dao.SysJobDao;
import com.hchyun.quartz.service.ISysJobService;
import com.hchyun.quartz.entity.Job;
import com.hchyun.quartz.dao.JobDao;
import com.hchyun.quartz.service.JobService;
import com.hchyun.quartz.util.CronUtils;
import com.hchyun.quartz.util.ScheduleUtils;
@ -24,12 +24,12 @@ import com.hchyun.quartz.util.ScheduleUtils;
* @author hchyun
*/
@Service
public class SysJobServiceImpl implements ISysJobService {
public class JobServiceImpl implements JobService {
@Autowired
private Scheduler scheduler;
@Autowired
private SysJobDao jobMapper;
private JobDao jobMapper;
/**
* 项目启动时初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理不能手动修改数据库ID和任务组名否则会导致脏数据
@ -37,8 +37,8 @@ public class SysJobServiceImpl implements ISysJobService {
@PostConstruct
public void init() throws SchedulerException, TaskException {
scheduler.clear();
List<SysJob> jobList = jobMapper.selectJobAll();
for (SysJob job : jobList) {
List<Job> jobList = jobMapper.selectJobAll();
for (Job job : jobList) {
ScheduleUtils.createScheduleJob(scheduler, job);
}
}
@ -50,7 +50,7 @@ public class SysJobServiceImpl implements ISysJobService {
* @return
*/
@Override
public List<SysJob> selectJobList(SysJob job) {
public List<Job> selectJobList(Job job) {
return jobMapper.selectJobList(job);
}
@ -61,7 +61,7 @@ public class SysJobServiceImpl implements ISysJobService {
* @return 调度任务对象信息
*/
@Override
public SysJob selectJobById(Long jobId) {
public Job selectJobById(Long jobId) {
return jobMapper.selectJobById(jobId);
}
@ -72,7 +72,7 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public int pauseJob(SysJob job) throws SchedulerException {
public int pauseJob(Job job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
@ -90,7 +90,7 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public int resumeJob(SysJob job) throws SchedulerException {
public int resumeJob(Job job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
@ -108,7 +108,7 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public int deleteJob(SysJob job) throws SchedulerException {
public int deleteJob(Job job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
int rows = jobMapper.deleteJobById(jobId);
@ -128,7 +128,7 @@ public class SysJobServiceImpl implements ISysJobService {
@Transactional
public void deleteJobByIds(Long[] jobIds) throws SchedulerException {
for (Long jobId : jobIds) {
SysJob job = jobMapper.selectJobById(jobId);
Job job = jobMapper.selectJobById(jobId);
deleteJob(job);
}
}
@ -140,7 +140,7 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public int changeStatus(SysJob job) throws SchedulerException {
public int changeStatus(Job job) throws SchedulerException {
int rows = 0;
String status = job.getStatus();
if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
@ -158,10 +158,10 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public void run(SysJob job) throws SchedulerException {
public void run(Job job) throws SchedulerException {
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
SysJob properties = selectJobById(job.getJobId());
Job properties = selectJobById(job.getJobId());
// 参数
JobDataMap dataMap = new JobDataMap();
dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
@ -175,7 +175,7 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public int insertJob(SysJob job) throws SchedulerException, TaskException {
public int insertJob(Job job) throws SchedulerException, TaskException {
job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
int rows = jobMapper.insertJob(job);
if (rows > 0) {
@ -191,8 +191,8 @@ public class SysJobServiceImpl implements ISysJobService {
*/
@Override
@Transactional
public int updateJob(SysJob job) throws SchedulerException, TaskException {
SysJob properties = selectJobById(job.getJobId());
public int updateJob(Job job) throws SchedulerException, TaskException {
Job properties = selectJobById(job.getJobId());
int rows = jobMapper.updateJob(job);
if (rows > 0) {
updateSchedulerJob(job, properties.getJobGroup());
@ -206,7 +206,7 @@ public class SysJobServiceImpl implements ISysJobService {
* @param job 任务对象
* @param jobGroup 任务组名
*/
public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {
public void updateSchedulerJob(Job job, String jobGroup) throws SchedulerException, TaskException {
Long jobId = job.getJobId();
// 判断是否存在
JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);

View File

@ -2,7 +2,6 @@ package com.hchyun.quartz.util;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
@ -13,16 +12,16 @@ import com.hchyun.common.utils.ExceptionUtil;
import com.hchyun.common.utils.StringUtils;
import com.hchyun.common.utils.bean.BeanUtils;
import com.hchyun.common.utils.spring.SpringUtils;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.SysJobLog;
import com.hchyun.quartz.service.ISysJobLogService;
import com.hchyun.quartz.entity.Job;
import com.hchyun.quartz.entity.JobLog;
import com.hchyun.quartz.service.JobLogService;
/**
* 抽象quartz调用
*
* @author hchyun
*/
public abstract class AbstractQuartzJob implements Job {
public abstract class AbstractQuartzJob implements org.quartz.Job {
private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class);
/**
@ -32,17 +31,17 @@ public abstract class AbstractQuartzJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
SysJob sysJob = new SysJob();
BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
Job job = new Job();
BeanUtils.copyBeanProp(job, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));
try {
before(context, sysJob);
if (sysJob != null) {
doExecute(context, sysJob);
before(context, job);
if (job != null) {
doExecute(context, job);
}
after(context, sysJob, null);
after(context, job, null);
} catch (Exception e) {
log.error("任务执行异常 - ", e);
after(context, sysJob, e);
after(context, job, e);
}
}
@ -50,9 +49,9 @@ public abstract class AbstractQuartzJob implements Job {
* 执行前
*
* @param context 工作执行上下文对象
* @param sysJob 系统计划任务
* @param job 系统计划任务
*/
protected void before(JobExecutionContext context, SysJob sysJob) {
protected void before(JobExecutionContext context, Job job) {
threadLocal.set(new Date());
}
@ -60,38 +59,38 @@ public abstract class AbstractQuartzJob implements Job {
* 执行后
*
* @param context 工作执行上下文对象
* @param sysJob 系统计划任务
* @param job 系统计划任务
*/
protected void after(JobExecutionContext context, SysJob sysJob, Exception e) {
protected void after(JobExecutionContext context, Job job, Exception e) {
Date startTime = threadLocal.get();
threadLocal.remove();
final SysJobLog sysJobLog = new SysJobLog();
sysJobLog.setJobName(sysJob.getJobName());
sysJobLog.setJobGroup(sysJob.getJobGroup());
sysJobLog.setInvokeTarget(sysJob.getInvokeTarget());
sysJobLog.setStartTime(startTime);
sysJobLog.setStopTime(new Date());
long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime();
sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
final JobLog jobLog = new JobLog();
jobLog.setJobName(job.getJobName());
jobLog.setJobGroup(job.getJobGroup());
jobLog.setInvokeTarget(job.getInvokeTarget());
jobLog.setStartTime(startTime);
jobLog.setStopTime(new Date());
long runMs = jobLog.getStopTime().getTime() - jobLog.getStartTime().getTime();
jobLog.setJobMessage(jobLog.getJobName() + " 总共耗时:" + runMs + "毫秒");
if (e != null) {
sysJobLog.setStatus(Constants.FAIL);
jobLog.setStatus(Constants.FAIL);
String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000);
sysJobLog.setExceptionInfo(errorMsg);
jobLog.setExceptionInfo(errorMsg);
} else {
sysJobLog.setStatus(Constants.SUCCESS);
jobLog.setStatus(Constants.SUCCESS);
}
// 写入数据库当中
SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog);
SpringUtils.getBean(JobLogService.class).addJobLog(jobLog);
}
/**
* 执行方法由子类重载
*
* @param context 工作执行上下文对象
* @param sysJob 系统计划任务
* @param job 系统计划任务
* @throws Exception 执行过程中的异常
*/
protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception;
protected abstract void doExecute(JobExecutionContext context, Job job) throws Exception;
}

View File

@ -7,7 +7,7 @@ import java.util.List;
import com.hchyun.common.utils.StringUtils;
import com.hchyun.common.utils.spring.SpringUtils;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.Job;
/**
* 任务执行工具
@ -18,10 +18,10 @@ public class JobInvokeUtil {
/**
* 执行方法
*
* @param sysJob 系统任务
* @param job 系统任务
*/
public static void invokeMethod(SysJob sysJob) throws Exception {
String invokeTarget = sysJob.getInvokeTarget();
public static void invokeMethod(Job job) throws Exception {
String invokeTarget = job.getInvokeTarget();
String beanName = getBeanName(invokeTarget);
String methodName = getMethodName(invokeTarget);
List<Object[]> methodParams = getMethodParams(invokeTarget);

View File

@ -2,7 +2,7 @@ package com.hchyun.quartz.util;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.Job;
/**
* 定时任务处理禁止并发执行
@ -12,7 +12,7 @@ import com.hchyun.quartz.entity.SysJob;
@DisallowConcurrentExecution
public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob {
@Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
JobInvokeUtil.invokeMethod(sysJob);
protected void doExecute(JobExecutionContext context, Job job) throws Exception {
JobInvokeUtil.invokeMethod(job);
}
}

View File

@ -1,7 +1,7 @@
package com.hchyun.quartz.util;
import org.quartz.JobExecutionContext;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.Job;
/**
* 定时任务处理允许并发执行
@ -10,7 +10,7 @@ import com.hchyun.quartz.entity.SysJob;
*/
public class QuartzJobExecution extends AbstractQuartzJob {
@Override
protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception {
JobInvokeUtil.invokeMethod(sysJob);
protected void doExecute(JobExecutionContext context, Job job) throws Exception {
JobInvokeUtil.invokeMethod(job);
}
}

View File

@ -2,7 +2,6 @@ package com.hchyun.quartz.util;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
@ -13,7 +12,7 @@ import org.quartz.TriggerKey;
import com.hchyun.common.constant.ScheduleConstants;
import com.hchyun.common.exception.job.TaskException;
import com.hchyun.common.exception.job.TaskException.Code;
import com.hchyun.quartz.entity.SysJob;
import com.hchyun.quartz.entity.Job;
/**
* 定时任务工具类
@ -24,11 +23,11 @@ public class ScheduleUtils {
/**
* 得到quartz任务类
*
* @param sysJob 执行计划
* @param job 执行计划
* @return 具体执行任务类
*/
private static Class<? extends Job> getQuartzJobClass(SysJob sysJob) {
boolean isConcurrent = "0".equals(sysJob.getConcurrent());
private static Class<? extends org.quartz.Job> getQuartzJobClass(Job job) {
boolean isConcurrent = "0".equals(job.getConcurrent());
return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
}
@ -49,8 +48,8 @@ public class ScheduleUtils {
/**
* 创建定时任务
*/
public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException {
Class<? extends Job> jobClass = getQuartzJobClass(job);
public static void createScheduleJob(Scheduler scheduler, Job job) throws SchedulerException, TaskException {
Class<? extends org.quartz.Job> jobClass = getQuartzJobClass(job);
// 构建job信息
Long jobId = job.getJobId();
String jobGroup = job.getJobGroup();
@ -84,7 +83,7 @@ public class ScheduleUtils {
/**
* 设置定时任务策略
*/
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
public static CronScheduleBuilder handleCronScheduleMisfirePolicy(Job job, CronScheduleBuilder cb)
throws TaskException {
switch (job.getMisfirePolicy()) {
case ScheduleConstants.MISFIRE_DEFAULT:

View File

@ -2,9 +2,9 @@
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hchyun.quartz.dao.SysJobLogDao">
<mapper namespace="com.hchyun.quartz.dao.JobLogDao">
<resultMap type="SysJobLog" id="SysJobLogResult">
<resultMap type="JobLog" id="JobLogResult">
<id property="jobLogId" column="job_log_id" />
<result property="jobName" column="job_name" />
<result property="jobGroup" column="job_group" />
@ -20,7 +20,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
from sys_job_log
</sql>
<select id="selectJobLogList" parameterType="SysJobLog" resultMap="SysJobLogResult">
<select id="selectJobLogList" parameterType="JobLog" resultMap="JobLogResult">
<include refid="selectJobLogVo"/>
<where>
<if test="jobName != null and jobName != ''">
@ -44,11 +44,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</where>
</select>
<select id="selectJobLogAll" resultMap="SysJobLogResult">
<select id="selectJobLogAll" resultMap="JobLogResult">
<include refid="selectJobLogVo"/>
</select>
<select id="selectJobLogById" parameterType="Long" resultMap="SysJobLogResult">
<select id="selectJobLogById" parameterType="Long" resultMap="JobLogResult">
<include refid="selectJobLogVo"/>
where job_log_id = #{jobLogId}
</select>
@ -68,7 +68,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
truncate table sys_job_log
</update>
<insert id="insertJobLog" parameterType="SysJobLog">
<insert id="insertJobLog" parameterType="JobLog">
insert into sys_job_log(
<if test="jobLogId != null and jobLogId != 0">job_log_id,</if>
<if test="jobName != null and jobName != ''">job_name,</if>

View File

@ -2,9 +2,9 @@
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hchyun.quartz.dao.SysJobDao">
<mapper namespace="com.hchyun.quartz.dao.JobDao">
<resultMap type="SysJob" id="SysJobResult">
<resultMap type="Job" id="JobResult">
<id property="jobId" column="job_id" />
<result property="jobName" column="job_name" />
<result property="jobGroup" column="job_group" />
@ -25,7 +25,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
from sys_job
</sql>
<select id="selectJobList" parameterType="SysJob" resultMap="SysJobResult">
<select id="selectJobList" parameterType="Job" resultMap="JobResult">
<include refid="selectJobVo"/>
<where>
<if test="jobName != null and jobName != ''">
@ -43,11 +43,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</where>
</select>
<select id="selectJobAll" resultMap="SysJobResult">
<select id="selectJobAll" resultMap="JobResult">
<include refid="selectJobVo"/>
</select>
<select id="selectJobById" parameterType="Long" resultMap="SysJobResult">
<select id="selectJobById" parameterType="Long" resultMap="JobResult">
<include refid="selectJobVo"/>
where job_id = #{jobId}
</select>
@ -63,7 +63,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</foreach>
</delete>
<update id="updateJob" parameterType="SysJob">
<update id="updateJob" parameterType="Job">
update sys_job
<set>
<if test="jobName != null and jobName != ''">job_name = #{jobName},</if>
@ -80,7 +80,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
where job_id = #{jobId}
</update>
<insert id="insertJob" parameterType="SysJob" useGeneratedKeys="true" keyProperty="jobId">
<insert id="insertJob" parameterType="Job" useGeneratedKeys="true" keyProperty="jobId">
insert into sys_job(
<if test="jobId != null and jobId != 0">job_id,</if>
<if test="jobName != null and jobName != ''">job_name,</if>

View File

@ -1,7 +1,5 @@
package com.hchyun.test.test;
import org.apache.poi.ss.formula.functions.T;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;