try catch 控制器类重置

This commit is contained in:
20932067@zju.edu.cn 2021-02-21 00:18:32 +08:00
parent 242a06b7a6
commit 9f861e2365
39 changed files with 1479 additions and 1404 deletions

View File

@ -140,7 +140,7 @@ import { listMenu as getMenuTreeselect } from "@/api/system/menu";
import basicInfoForm from "./basicInfoForm";
import genInfoForm from "./genInfoForm";
import Sortable from 'sortablejs'
import {listRegular} from "../../../api/system/regular";
import {listRegular} from "../../../api/tool/regular";
export default {
name: "GenEdit",

View File

@ -166,7 +166,7 @@
</template>
<script>
import { listRegular, getRegular, delRegular, addRegular, updateRegular, exportRegular } from "@/api/system/regular";
import { listRegular, getRegular, delRegular, addRegular, updateRegular, exportRegular } from "@/api/tool/regular";
export default {
name: "Regular",

View File

@ -36,8 +36,6 @@ 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;
@ -47,28 +45,18 @@ public class ConfigController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:config:list')")
@GetMapping("/list")
public Serializable list(Config config) {
try {
startPage();
List<Config> list = configService.selectConfigList(config);
return getDataTable(list);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
startPage();
List<Config> list = configService.selectConfigList(config);
return getDataTable(list);
}
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:config:export')")
@GetMapping("/export")
public AjaxResult export(Config config) {
try {
List<Config> list = configService.selectConfigList(config);
ExcelUtil<Config> util = new ExcelUtil<Config>(Config.class);
return util.exportExcel(list, "参数数据");
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
List<Config> list = configService.selectConfigList(config);
ExcelUtil<Config> util = new ExcelUtil<Config>(Config.class);
return util.exportExcel(list, "参数数据");
}
/**
@ -77,12 +65,7 @@ public class ConfigController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:config:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long configId) {
try {
return AjaxResult.success(configService.selectConfigById(configId));
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(configService.selectConfigById(configId));
}
/**
@ -90,12 +73,7 @@ public class ConfigController extends BaseController {
*/
@GetMapping(value = "/configKey/{configKey}")
public AjaxResult getConfigKey(@PathVariable String configKey) {
try {
return AjaxResult.success(configService.selectConfigByKey(configKey));
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(configService.selectConfigByKey(configKey));
}
/**
@ -106,16 +84,11 @@ public class ConfigController extends BaseController {
@PostMapping
@RepeatSubmit
public AjaxResult add(@Validated @RequestBody Config config) {
try {
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setCreateBy(SecurityUtils.getUserId());
return toAjax(configService.insertConfig(config));
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setCreateBy(SecurityUtils.getUserId());
return toAjax(configService.insertConfig(config));
}
/**
@ -125,16 +98,11 @@ public class ConfigController extends BaseController {
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Config config) {
try {
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
return AjaxResult.error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setUpdateBy(SecurityUtils.getUserId());
return toAjax(configService.updateConfig(config));
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
return AjaxResult.error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setUpdateBy(SecurityUtils.getUserId());
return toAjax(configService.updateConfig(config));
}
/**
@ -144,12 +112,7 @@ public class ConfigController extends BaseController {
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{configIds}")
public AjaxResult remove(@PathVariable Long[] configIds) {
try {
return toAjax(configService.deleteConfigByIds(configIds));
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(configService.deleteConfigByIds(configIds));
}
/**
@ -159,12 +122,7 @@ public class ConfigController extends BaseController {
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@DeleteMapping("/clearCache")
public AjaxResult clearCache() {
try {
configService.clearCache();
return AjaxResult.success();
}catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
configService.clearCache();
return AjaxResult.success();
}
}

View File

@ -36,8 +36,6 @@ import com.hchyun.system.service.DeptService;
@RestController
@RequestMapping("/system/dept")
public class DeptController extends BaseController {
private Logger logger = LoggerFactory.getLogger(DeptController.class);
@Autowired
private DeptService deptService;
@ -47,13 +45,9 @@ public class DeptController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dept:list')")
@GetMapping("/list")
public AjaxResult list(Dept dept) {
try {
List<Dept> depts = deptService.selectDeptList(dept);
return AjaxResult.success(depts);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
List<Dept> depts = deptService.selectDeptList(dept);
return AjaxResult.success(depts);
}
/**
@ -62,21 +56,17 @@ public class DeptController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dept:list')")
@GetMapping("/list/exclude/{deptId}")
public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
try {
List<Dept> depts = deptService.selectDeptList(new Dept());
Iterator<Dept> it = depts.iterator();
while (it.hasNext()) {
Dept d = (Dept) it.next();
if (d.getDeptId().intValue() == deptId
|| ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
it.remove();
}
List<Dept> depts = deptService.selectDeptList(new Dept());
Iterator<Dept> it = depts.iterator();
while (it.hasNext()) {
Dept d = (Dept) it.next();
if (d.getDeptId().intValue() == deptId
|| ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
it.remove();
}
return AjaxResult.success(depts);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(depts);
}
/**
@ -85,12 +75,7 @@ public class DeptController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dept:query')")
@GetMapping(value = "/{deptId}")
public AjaxResult getInfo(@PathVariable Long deptId) {
try {
return AjaxResult.success(deptService.selectDeptById(deptId));
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(deptService.selectDeptById(deptId));
}
/**
@ -98,13 +83,8 @@ public class DeptController extends BaseController {
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(Dept dept) {
try {
List<Dept> depts = deptService.selectDeptList(dept);
return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
List<Dept> depts = deptService.selectDeptList(dept);
return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
}
/**
@ -112,16 +92,11 @@ public class DeptController extends BaseController {
*/
@GetMapping(value = "/roleDeptTreeselect/{roleId}")
public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
try {
List<Dept> depts = deptService.selectDeptList(new Dept());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.buildDeptTreeSelect(depts));
return ajax;
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
List<Dept> depts = deptService.selectDeptList(new Dept());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.buildDeptTreeSelect(depts));
return ajax;
}
/**
@ -131,16 +106,11 @@ public class DeptController extends BaseController {
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Dept dept) {
try {
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
dept.setCreateBy(SecurityUtils.getUserId());
return toAjax(deptService.insertDept(dept));
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
dept.setCreateBy(SecurityUtils.getUserId());
return toAjax(deptService.insertDept(dept));
}
/**
@ -150,21 +120,16 @@ public class DeptController extends BaseController {
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Dept dept) {
try {
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
} else if (dept.getParentId().equals(dept.getDeptId())) {
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
} else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
&& deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
return AjaxResult.error("该部门包含未停用的子部门!");
}
dept.setUpdateBy(SecurityUtils.getUserId());
return toAjax(deptService.updateDept(dept));
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
} else if (dept.getParentId().equals(dept.getDeptId())) {
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
} else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
&& deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
return AjaxResult.error("该部门包含未停用的子部门!");
}
dept.setUpdateBy(SecurityUtils.getUserId());
return toAjax(deptService.updateDept(dept));
}
/**
@ -174,17 +139,12 @@ public class DeptController extends BaseController {
@Log(title = "部门管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{deptId}")
public AjaxResult remove(@PathVariable Long deptId) {
try {
if (deptService.hasChildByDeptId(deptId)) {
return AjaxResult.error("存在下级部门,不允许删除");
}
if (deptService.checkDeptExistUser(deptId)) {
return AjaxResult.error("部门存在用户,不允许删除");
}
return toAjax(deptService.deleteDeptById(deptId));
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
if (deptService.hasChildByDeptId(deptId)) {
return AjaxResult.error("存在下级部门,不允许删除");
}
if (deptService.checkDeptExistUser(deptId)) {
return AjaxResult.error("部门存在用户,不允许删除");
}
return toAjax(deptService.deleteDeptById(deptId));
}
}

View File

@ -36,8 +36,6 @@ 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;
@ -47,28 +45,18 @@ public class DictDataController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dict:list')")
@GetMapping("/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);
}
startPage();
List<DictData> list = dictDataService.selectDictDataList(dictData);
return getDataTable(list);
}
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:dict:export')")
@GetMapping("/export")
public AjaxResult export(DictData dictData) {
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);
}
List<DictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil<DictData> util = new ExcelUtil<DictData>(DictData.class);
return util.exportExcel(list, "字典数据");
}
/**
@ -77,12 +65,7 @@ public class DictDataController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictCode}")
public AjaxResult getInfo(@PathVariable Long dictCode) {
try {
return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
}
/**
@ -90,12 +73,7 @@ public class DictDataController extends BaseController {
*/
@GetMapping(value = "/type/{dictType}")
public AjaxResult dictType(@PathVariable String dictType) {
try {
return AjaxResult.success(dictTypeService.selectDictDataByType(dictType));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(dictTypeService.selectDictDataByType(dictType));
}
/**
@ -105,13 +83,8 @@ public class DictDataController extends BaseController {
@Log(title = "字典数据", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody DictData dict) {
try {
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.insertDictData(dict));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.insertDictData(dict));
}
/**
@ -121,13 +94,8 @@ public class DictDataController extends BaseController {
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody DictData dict) {
try {
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.updateDictData(dict));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictDataService.updateDictData(dict));
}
/**
@ -137,11 +105,6 @@ public class DictDataController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictCodes}")
public AjaxResult remove(@PathVariable Long[] dictCodes) {
try {
return toAjax(dictDataService.deleteDictDataByIds(dictCodes));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(dictDataService.deleteDictDataByIds(dictCodes));
}
}

View File

@ -36,36 +36,24 @@ 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 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);
}
startPage();
List<DictType> list = dictTypeService.selectDictTypeList(dictType);
return getDataTable(list);
}
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:dict:export')")
@GetMapping("/export")
public AjaxResult export(DictType dictType) {
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);
}
List<DictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<DictType> util = new ExcelUtil<DictType>(DictType.class);
return util.exportExcel(list, "字典类型");
}
/**
@ -74,12 +62,7 @@ public class DictTypeController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictId}")
public AjaxResult getInfo(@PathVariable Long dictId) {
try {
return AjaxResult.success(dictTypeService.selectDictTypeById(dictId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(dictTypeService.selectDictTypeById(dictId));
}
/**
@ -89,16 +72,11 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody DictType dict) {
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);
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setCreateBy(SecurityUtils.getUserId());
return toAjax(dictTypeService.insertDictType(dict));
}
/**
@ -108,16 +86,11 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody DictType dict) {
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);
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setUpdateBy(SecurityUtils.getUserId());
return toAjax(dictTypeService.updateDictType(dict));
}
/**
@ -127,12 +100,7 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictIds}")
public AjaxResult remove(@PathVariable Long[] dictIds) {
try {
return toAjax(dictTypeService.deleteDictTypeByIds(dictIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(dictTypeService.deleteDictTypeByIds(dictIds));
}
/**
@ -142,13 +110,8 @@ public class DictTypeController extends BaseController {
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/clearCache")
public AjaxResult clearCache() {
try {
dictTypeService.clearCache();
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
dictTypeService.clearCache();
return AjaxResult.success();
}
/**
@ -156,12 +119,7 @@ public class DictTypeController extends BaseController {
*/
@GetMapping("/optionselect")
public AjaxResult optionselect() {
try {
List<DictType> dictTypes = dictTypeService.selectDictTypeAll();
return AjaxResult.success(dictTypes);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
List<DictType> dictTypes = dictTypeService.selectDictTypeAll();
return AjaxResult.success(dictTypes);
}
}

View File

@ -30,8 +30,6 @@ import com.hchyun.system.service.MenuService;
*/
@RestController
public class LoginController {
private Logger logger = LoggerFactory.getLogger(LoginController.class);
@Autowired
private LoginService loginService;
@ -52,17 +50,12 @@ public class LoginController {
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody) {
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);
}
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
/**
@ -72,22 +65,17 @@ public class LoginController {
*/
@GetMapping("getInfo")
public AjaxResult getInfo() {
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);
}
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;
}
/**
@ -97,15 +85,10 @@ public class LoginController {
*/
@GetMapping("getRouters")
public AjaxResult getRouters() {
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);
}
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
// 用户信息
User user = loginUser.getUser();
List<Menu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
return AjaxResult.success(menuService.buildMenus(menus));
}
}

View File

@ -38,8 +38,6 @@ 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;
@ -52,15 +50,10 @@ public class MenuController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:menu:list')")
@GetMapping("/list")
public AjaxResult list(Menu menu) {
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);
}
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<Menu> menus = menuService.selectMenuList(menu, userId);
return AjaxResult.success(menus);
}
/**
@ -69,12 +62,7 @@ public class MenuController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:menu:query')")
@GetMapping(value = "/{menuId}")
public AjaxResult getInfo(@PathVariable Long menuId) {
try {
return AjaxResult.success(menuService.selectMenuById(menuId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(menuService.selectMenuById(menuId));
}
/**
@ -82,15 +70,10 @@ public class MenuController extends BaseController {
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(Menu menu) {
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);
}
LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
Long userId = loginUser.getUser().getUserId();
List<Menu> menus = menuService.selectMenuList(menu, userId);
return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
}
/**
@ -98,17 +81,12 @@ public class MenuController extends BaseController {
*/
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
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);
}
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;
}
/**
@ -118,19 +96,14 @@ public class MenuController extends BaseController {
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Menu menu) {
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);
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));
}
/**
@ -140,21 +113,16 @@ public class MenuController extends BaseController {
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Menu menu) {
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);
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));
}
/**
@ -164,17 +132,12 @@ public class MenuController extends BaseController {
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{menuId}")
public AjaxResult remove(@PathVariable("menuId") Long menuId) {
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.hasChildByMenuId(menuId)) {
return AjaxResult.error("存在子菜单,不允许删除");
}
if (menuService.checkMenuExistRole(menuId)) {
return AjaxResult.error("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}
}

View File

@ -34,8 +34,6 @@ 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;
@ -45,14 +43,9 @@ public class NoticeController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:notice:list')")
@GetMapping("/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);
}
}
/**
@ -61,12 +54,7 @@ public class NoticeController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:notice:query')")
@GetMapping(value = "/{noticeId}")
public AjaxResult getInfo(@PathVariable Long noticeId) {
try {
return AjaxResult.success(noticeService.selectNoticeById(noticeId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -76,13 +64,8 @@ public class NoticeController extends BaseController {
@Log(title = "通知公告", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Notice notice) {
try {
notice.setCreateBy(SecurityUtils.getUserId());
return toAjax(noticeService.insertNotice(notice));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -92,13 +75,8 @@ public class NoticeController extends BaseController {
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Notice notice) {
try {
notice.setUpdateBy(SecurityUtils.getUserId());
return toAjax(noticeService.updateNotice(notice));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -108,11 +86,6 @@ public class NoticeController extends BaseController {
@Log(title = "通知公告", businessType = BusinessType.DELETE)
@DeleteMapping("/{noticeIds}")
public AjaxResult remove(@PathVariable Long[] noticeIds) {
try {
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
}

View File

@ -36,9 +36,6 @@ 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;
@ -48,28 +45,18 @@ public class PostController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:post:list')")
@GetMapping("/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);
}
startPage();
List<Post> list = postService.selectPostList(post);
return getDataTable(list);
}
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:post:export')")
@GetMapping("/export")
public AjaxResult export(Post post) {
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);
}
List<Post> list = postService.selectPostList(post);
ExcelUtil<Post> util = new ExcelUtil<Post>(Post.class);
return util.exportExcel(list, "岗位数据");
}
/**
@ -78,12 +65,7 @@ public class PostController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:post:query')")
@GetMapping(value = "/{postId}")
public AjaxResult getInfo(@PathVariable Long postId) {
try {
return AjaxResult.success(postService.selectPostById(postId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(postService.selectPostById(postId));
}
/**
@ -93,18 +75,13 @@ public class PostController extends BaseController {
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Post post) {
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);
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));
}
/**
@ -114,18 +91,13 @@ public class PostController extends BaseController {
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Post post) {
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);
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));
}
/**
@ -135,12 +107,7 @@ public class PostController extends BaseController {
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{postIds}")
public AjaxResult remove(@PathVariable Long[] postIds) {
try {
return toAjax(postService.deletePostByIds(postIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(postService.deletePostByIds(postIds));
}
/**
@ -148,12 +115,7 @@ public class PostController extends BaseController {
*/
@GetMapping("/optionselect")
public AjaxResult optionselect() {
try {
List<Post> posts = postService.selectPostAll();
return AjaxResult.success(posts);
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
List<Post> posts = postService.selectPostAll();
return AjaxResult.success(posts);
}
}

View File

@ -35,8 +35,6 @@ 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;
@ -48,17 +46,12 @@ public class ProfileController extends BaseController {
*/
@GetMapping
public AjaxResult profile() {
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);
}
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;
}
/**
@ -67,22 +60,17 @@ public class ProfileController extends BaseController {
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult updateProfile(@RequestBody User user) {
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);
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("修改个人信息异常,请联系管理员");
}
/**
@ -91,27 +79,22 @@ public class ProfileController extends BaseController {
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword) {
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);
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("修改密码异常,请联系管理员");
}
/**
@ -120,23 +103,18 @@ public class ProfileController extends BaseController {
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
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;
}
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

@ -42,8 +42,6 @@ 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;
@ -59,28 +57,18 @@ public class RoleController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:role:list')")
@GetMapping("/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);
}
startPage();
List<Role> list = roleService.selectRoleList(role);
return getDataTable(list);
}
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:role:export')")
@GetMapping("/export")
public AjaxResult export(Role role) {
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);
}
List<Role> list = roleService.selectRoleList(role);
ExcelUtil<Role> util = new ExcelUtil<Role>(Role.class);
return util.exportExcel(list, "角色数据");
}
/**
@ -89,12 +77,7 @@ public class RoleController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public AjaxResult getInfo(@PathVariable Long roleId) {
try {
return AjaxResult.success(roleService.selectRoleById(roleId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(roleService.selectRoleById(roleId));
}
/**
@ -104,18 +87,13 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody Role role) {
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);
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));
}
@ -126,30 +104,25 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody Role role) {
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() + "'失败,角色权限已存在");
}
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);
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);
}
return AjaxResult.success();
}
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
@ -159,13 +132,8 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public AjaxResult dataScope(@RequestBody Role role) {
try {
roleService.checkRoleAllowed(role);
return toAjax(roleService.authDataScope(role));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
roleService.checkRoleAllowed(role);
return toAjax(roleService.authDataScope(role));
}
/**
@ -175,14 +143,9 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody Role 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);
}
roleService.checkRoleAllowed(role);
role.setUpdateBy(SecurityUtils.getUserId());
return toAjax(roleService.updateRoleStatus(role));
}
/**
@ -192,12 +155,7 @@ public class RoleController extends BaseController {
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public AjaxResult remove(@PathVariable Long[] roleIds) {
try {
return toAjax(roleService.deleteRoleByIds(roleIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(roleService.deleteRoleByIds(roleIds));
}
/**
@ -206,15 +164,10 @@ public class RoleController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect(Integer type) {
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);
if (type == 1 || type == 2) {
return AjaxResult.success(roleService.selectRoleAll(type));
} else {
return AjaxResult.error(ReturnConstants.STATE_ERROR);
}
}
}

View File

@ -45,8 +45,6 @@ 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;
@ -65,56 +63,36 @@ public class UserController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:user:list')")
@GetMapping("/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);
}
startPage();
List<User> list = userService.selectUserList(user);
return getDataTable(list);
}
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@hchyun.hasPermi('system:user:export')")
@GetMapping("/export")
public AjaxResult export(User user) {
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);
}
List<User> list = userService.selectUserList(user);
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
return util.exportExcel(list, "用户数据");
}
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@PreAuthorize("@hchyun.hasPermi('system:user:import')")
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
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);
}
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);
}
@GetMapping("/importTemplate")
public AjaxResult importTemplate() {
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);
}
ExcelUtil<User> util = new ExcelUtil<User>(User.class);
return util.importTemplateExcel("用户数据");
}
/**
@ -123,21 +101,16 @@ public class UserController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('system:user:query')")
@GetMapping(value = {"/", "/{userId}"})
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long 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);
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;
}
/**
@ -147,21 +120,16 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody User user) {
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);
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));
}
/**
@ -171,19 +139,14 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody User user) {
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);
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));
}
/**
@ -193,12 +156,7 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public AjaxResult remove(@PathVariable Long[] userIds) {
try {
return toAjax(userService.deleteUserByIds(userIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(userService.deleteUserByIds(userIds));
}
/**
@ -208,15 +166,10 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public AjaxResult resetPwd(@RequestBody User 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);
}
userService.checkUserAllowed(user);
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.resetPwd(user));
}
/**
@ -226,13 +179,8 @@ public class UserController extends BaseController {
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody User 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);
}
userService.checkUserAllowed(user);
user.setUpdateBy(SecurityUtils.getUserId());
return toAjax(userService.updateUserStatus(user));
}
}

View File

@ -8,7 +8,7 @@ hchyun:
copyrightYear: 2020
# 实例演示开关
demoEnabled: true
# 文件路径 示例( Windows配置D:/hchyun/uploadPathLinux配置 /home/hchyun/uploadPath
# 文件路径 示例( Windows配置D:/hchyun/uploadPathLinux配置(宝塔) /www/wwwroot/hchyun/uploadPath
profile: F:/hchyun/uploadPath
# 获取ip地址开关
addressEnabled: false
@ -54,6 +54,8 @@ logging:
level:
com.hchyun: debug
org.springframework: warn
# com.hchyun: error
# org.springframework: error
# Spring配置
spring:

View File

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

View File

@ -56,14 +56,9 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:list')")
@GetMapping("/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);
}
}
/**
@ -72,7 +67,6 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:query')")
@GetMapping(value = "/{talbleId}")
public AjaxResult getInfo(@PathVariable Long talbleId) {
try {
GenTable table = genTableService.selectGenTableById(talbleId);
List<GenTable> tables = genTableService.selectGenTableAll();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(talbleId);
@ -81,10 +75,6 @@ public class GenController extends BaseController {
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);
}
}
/**
@ -93,14 +83,9 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:list')")
@GetMapping("/db/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);
}
}
/**
@ -109,16 +94,11 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:list')")
@GetMapping(value = "/column/{talbleId}")
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);
}
}
/**
@ -128,16 +108,11 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable")
public AjaxResult importTableSave(String tables) {
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);
}
}
/**
@ -148,14 +123,9 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult editSave(@Validated @RequestBody GenTable genTable) {
try {
genTableService.validateEdit(genTable);
genTableService.updateGenTable(genTable);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**
@ -184,13 +154,8 @@ public class GenController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('tool:gen:preview')")
@GetMapping("/preview/{tableId}")
public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException {
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);
}
}
/**
@ -211,17 +176,12 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}")
public AjaxResult genCode(@PathVariable("tableName") String tableName) {
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);
}
}
/**
@ -231,13 +191,8 @@ public class GenController extends BaseController {
@Log(title = "代码生成", businessType = BusinessType.UPDATE)
@GetMapping("/synchDb/{tableName}")
public AjaxResult synchDb(@PathVariable("tableName") String tableName) {
try {
genTableService.synchDb(tableName);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
/**

View File

@ -2,8 +2,6 @@ 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;

View File

@ -1,4 +1,4 @@
package com.hchyun.web.controller.system;
package com.hchyun.generator.controller;
import java.io.Serializable;
import java.util.List;
@ -6,6 +6,9 @@ import java.util.regex.Pattern;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.utils.ServerResult;
import com.hchyun.common.utils.poi.ExcelUtil;
import com.hchyun.generator.entity.Regular;
import com.hchyun.generator.service.RegularService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
@ -22,9 +25,6 @@ import com.hchyun.common.annotation.Log;
import com.hchyun.common.core.controller.HcyBaseController;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.enums.BusinessType;
import com.hchyun.system.entity.Regular;
import com.hchyun.system.service.RegularService;
import com.hchyun.common.utils.poi.ExcelUtil;
/**
* 校验规则Controller
@ -33,7 +33,7 @@ import com.hchyun.common.utils.poi.ExcelUtil;
* @date 2021-01-18
*/
@RestController
@RequestMapping("/system/regular")
@RequestMapping("/tool/regular")
public class RegularController extends HcyBaseController {
protected final Logger logger = LoggerFactory.getLogger(RegularController.class);
@ -46,7 +46,7 @@ public class RegularController extends HcyBaseController {
* @param regular
* @return
*/
@PreAuthorize("@hchyun.hasPermi('system:regular:list')")
@PreAuthorize("@hchyun.hasPermi('tool:regular:list')")
@GetMapping("/list")
public Serializable list(Regular regular) {
try {
@ -69,7 +69,7 @@ public class RegularController extends HcyBaseController {
* @param regular
* @return
*/
@PreAuthorize("@hchyun.hasPermi('system:regular:export')")
@PreAuthorize("@hchyun.hasPermi('tool:regular:export')")
@Log(title = "校验规则", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(Regular regular) {
@ -93,7 +93,7 @@ public class RegularController extends HcyBaseController {
* @param id
* @return
*/
@PreAuthorize("@hchyun.hasPermi('system:regular:query')")
@PreAuthorize("@hchyun.hasPermi('tool:regular:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
try {
@ -115,7 +115,7 @@ public class RegularController extends HcyBaseController {
* @param regular
* @return
*/
@PreAuthorize("@hchyun.hasPermi('system:regular:add')")
@PreAuthorize("@hchyun.hasPermi('tool:regular:add')")
@Log(title = "校验规则", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody Regular regular) {
@ -150,7 +150,7 @@ public class RegularController extends HcyBaseController {
* @param regular
* @return
*/
@PreAuthorize("@hchyun.hasPermi('system:regular:edit')")
@PreAuthorize("@hchyun.hasPermi('tool:regular:edit')")
@Log(title = "校验规则", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody Regular regular) {
@ -185,7 +185,7 @@ public class RegularController extends HcyBaseController {
* @param ids
* @return
*/
@PreAuthorize("@hchyun.hasPermi('system:regular:remove')")
@PreAuthorize("@hchyun.hasPermi('tool:regular:remove')")
@Log(title = "校验规则", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {

View File

@ -1,8 +1,8 @@
package com.hchyun.system.dao;
package com.hchyun.generator.dao;
import java.util.List;
import com.hchyun.system.entity.Regular;
import com.hchyun.generator.entity.Regular;
/**
* 校验规则Dao接口

View File

@ -1,4 +1,4 @@
package com.hchyun.system.entity;
package com.hchyun.generator.entity;
import com.hchyun.common.annotation.Excel;
import com.hchyun.common.core.entity.BaseEntity;

View File

@ -1,7 +1,7 @@
package com.hchyun.system.service;
package com.hchyun.generator.service;
import com.hchyun.common.utils.ServerResult;
import com.hchyun.system.entity.Regular;
import com.hchyun.generator.entity.Regular;
import java.util.List;

View File

@ -3,7 +3,12 @@ package com.hchyun.generator.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.exception.CustomException;
import com.hchyun.generator.service.GenTableColumnService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.common.core.text.Convert;
@ -17,6 +22,8 @@ import com.hchyun.generator.dao.GenTableColumnDao;
*/
@Service
public class GenTableColumnServiceImpl implements GenTableColumnService {
private Logger logger = LoggerFactory.getLogger(GenTableColumnServiceImpl.class);
@Autowired
private GenTableColumnDao genTableColumnDao;
@ -28,7 +35,12 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
*/
@Override
public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) {
return genTableColumnDao.selectGenTableColumnListByTableId(tableId);
try {
return genTableColumnDao.selectGenTableColumnListByTableId(tableId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -39,7 +51,12 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
*/
@Override
public int insertGenTableColumn(GenTableColumn genTableColumn) {
return genTableColumnDao.insertGenTableColumn(genTableColumn);
try {
return genTableColumnDao.insertGenTableColumn(genTableColumn);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -50,9 +67,14 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
*/
@Override
public int updateGenTableColumn(GenTableColumn genTableColumn) {
List<GenTableColumn> genTableColumns = new ArrayList<GenTableColumn>();
genTableColumns.add(genTableColumn);
return genTableColumnDao.updateGenTableColumn(genTableColumns);
try {
List<GenTableColumn> genTableColumns = new ArrayList<GenTableColumn>();
genTableColumns.add(genTableColumn);
return genTableColumnDao.updateGenTableColumn(genTableColumns);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -63,6 +85,11 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
*/
@Override
public int deleteGenTableColumnByIds(String ids) {
return genTableColumnDao.deleteGenTableColumnByIds(Convert.toLongArray(ids));
try {
return genTableColumnDao.deleteGenTableColumnByIds(Convert.toLongArray(ids));
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
}

View File

@ -50,7 +50,7 @@ import org.springframework.transaction.interceptor.TransactionAspectSupport;
*/
@Service
public class GenTableServiceImpl implements GenTableService {
private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);
private static final Logger logger = LoggerFactory.getLogger(GenTableServiceImpl.class);
@Autowired
private GenTableDao genTableDao;
@ -69,9 +69,14 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public GenTable selectGenTableById(Long id) {
GenTable genTable = genTableDao.selectGenTableById(id);
setTableFromOptions(genTable);
return genTable;
try {
GenTable genTable = genTableDao.selectGenTableById(id);
setTableFromOptions(genTable);
return genTable;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -82,7 +87,12 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public List<GenTable> selectGenTableList(GenTable genTable) {
return genTableDao.selectGenTableList(genTable);
try {
return genTableDao.selectGenTableList(genTable);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -93,7 +103,12 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public List<GenTable> selectDbTableList(GenTable genTable) {
return genTableDao.selectDbTableList(genTable);
try {
return genTableDao.selectDbTableList(genTable);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -104,7 +119,12 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public List<GenTable> selectDbTableListByNames(String[] tableNames) {
return genTableDao.selectDbTableListByNames(tableNames);
try {
return genTableDao.selectDbTableListByNames(tableNames);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -114,7 +134,12 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public List<GenTable> selectGenTableAll() {
return genTableDao.selectGenTableAll();
try {
return genTableDao.selectGenTableAll();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -139,7 +164,7 @@ public class GenTableServiceImpl implements GenTableService {
}
}
} catch (CustomException e) {
log.error(e.getMessage());
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.DB_EX);
}
@ -160,7 +185,7 @@ public class GenTableServiceImpl implements GenTableService {
return new ServerResult<>(true);
} catch (RuntimeException e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
log.error(e.getMessage());
logger.error(e.getMessage());
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
@ -201,32 +226,37 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public Map<String, String> previewCode(Long tableId) {
Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息
GenTable table = genTableDao.selectGenTableById(tableId);
if (table.getTplCategory().equals(GenConstants.TPL_SUB)) {
// 设置主子表信息
setSubTable(table);
}
if (table.getTplCategory().equals(GenConstants.TPL_ASS)) {
table.setAssColumns(associatedDao.selectTableColumnByTableId(tableId));
}
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
try {
Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息
GenTable table = genTableDao.selectGenTableById(tableId);
if (table.getTplCategory().equals(GenConstants.TPL_SUB)) {
// 设置主子表信息
setSubTable(table);
}
if (table.getTplCategory().equals(GenConstants.TPL_ASS)) {
table.setAssColumns(associatedDao.selectTableColumnByTableId(tableId));
}
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
dataMap.put(template, sw.toString());
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
dataMap.put(template, sw.toString());
}
return dataMap;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return dataMap;
}
/**
@ -237,11 +267,16 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public byte[] downloadCode(String tableName) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -252,42 +287,47 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public boolean generatorCode(String tableName) {
// 查询表信息
GenTable table = genTableDao.selectGenTableByName(tableName);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息
setPkColumn(table);
try {
// 查询表信息
GenTable table = genTableDao.selectGenTableByName(tableName);
// 设置主子表信息
setSubTable(table);
// 设置主键列信息
setPkColumn(table);
VelocityInitializer.initVelocity();
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
if (!StringUtils.containsAny(template, "table.sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
if (template.equals("vm/sql/table.sql.vm")) {
Boolean start = insertMenuItem(sw);
if (start) {
return false;
}
} else {
try {
String path = getGenPath(table, template);
FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
} catch (IOException e) {
log.error("渲染模板失败,表名:" + table.getTableName());
return false;
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) {
if (!StringUtils.containsAny(template, "table.sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
if (template.equals("vm/sql/table.sql.vm")) {
Boolean start = insertMenuItem(sw);
if (start) {
return false;
}
} else {
try {
String path = getGenPath(table, template);
FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
} catch (IOException e) {
logger.error("渲染模板失败,表名:" + table.getTableName());
return false;
}
}
}
}
return true;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return true;
}
/**
@ -298,26 +338,31 @@ public class GenTableServiceImpl implements GenTableService {
@Override
@Transactional
public void synchDb(String tableName) {
GenTable table = genTableDao.selectGenTableByName(tableName);
List<GenTableColumn> tableColumns = table.getColumns();
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
try {
GenTable table = genTableDao.selectGenTableByName(tableName);
List<GenTableColumn> tableColumns = table.getColumns();
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
List<GenTableColumn> dbTableColumns = genTableColumnDao.selectDbTableColumnsByName(tableName);
if (StringUtils.isEmpty(dbTableColumns)) {
throw new CustomException("同步数据失败,原表结构不存在");
}
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
dbTableColumns.forEach(column -> {
if (!tableColumnNames.contains(column.getColumnName())) {
GenUtils.initColumnField(column, table);
genTableColumnDao.insertGenTableColumn(column);
List<GenTableColumn> dbTableColumns = genTableColumnDao.selectDbTableColumnsByName(tableName);
if (StringUtils.isEmpty(dbTableColumns)) {
throw new CustomException("同步数据失败,原表结构不存在");
}
});
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (StringUtils.isNotEmpty(delColumns)) {
genTableColumnDao.deleteGenTableColumns(delColumns);
dbTableColumns.forEach(column -> {
if (!tableColumnNames.contains(column.getColumnName())) {
GenUtils.initColumnField(column, table);
genTableColumnDao.insertGenTableColumn(column);
}
});
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (StringUtils.isNotEmpty(delColumns)) {
genTableColumnDao.deleteGenTableColumns(delColumns);
}
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
@ -329,17 +374,22 @@ public class GenTableServiceImpl implements GenTableService {
*/
@Override
public byte[] downloadCode(String[] tableNames) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
zip = generatorCode(tableName, zip);
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames) {
zip = generatorCode(tableName, zip);
// generatorCode(tableName, zip);
if (zip == null) {
return null;
if (zip == null) {
return null;
}
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
@Transactional
@ -354,7 +404,7 @@ public class GenTableServiceImpl implements GenTableService {
}
} catch (RuntimeException e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
log.error(e.getMessage());
logger.error(e.getMessage());
return true;
}
}
@ -363,6 +413,12 @@ public class GenTableServiceImpl implements GenTableService {
* todo 查询表信息并生成代码
*/
private ZipOutputStream generatorCode(String tableName, ZipOutputStream zip) {
try {
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
// 查询表信息
GenTable table = genTableDao.selectGenTableByName(tableName);
// 设置主子表信息
@ -399,7 +455,7 @@ public class GenTableServiceImpl implements GenTableService {
zip.flush();
zip.closeEntry();
} catch (IOException e) {
log.error("渲染模板失败,表名:" + table.getTableName(), e);
logger.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
return zip;

View File

@ -1,4 +1,4 @@
package com.hchyun.system.service.impl;
package com.hchyun.generator.service.impl;
import java.util.List;
@ -7,13 +7,13 @@ import com.hchyun.common.utils.DateUtils;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.utils.SecurityUtils;
import com.hchyun.common.utils.ServerResult;
import com.hchyun.generator.dao.RegularDao;
import com.hchyun.generator.entity.Regular;
import com.hchyun.generator.service.RegularService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.system.dao.RegularDao;
import com.hchyun.system.entity.Regular;
import com.hchyun.system.service.RegularService;
/**
* 校验规则Service业务层处理
@ -39,13 +39,13 @@ public class RegularServiceImpl implements RegularService {
try {
Regular regular = regularDao.selectRegularById(id);
if (regular != null) {
return new ServerResult<Regular>(true, regular);
return new ServerResult<>(true, regular);
} else {
return new ServerResult<Regular>(false, ReturnConstants.RESULT_EMPTY);
return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
}
} catch (RuntimeException e) {
logger.error(e.getMessage());
return new ServerResult<Regular>(false, ReturnConstants.DB_EX);
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
@ -60,13 +60,13 @@ public class RegularServiceImpl implements RegularService {
try {
List<Regular> regulars = regularDao.selectRegularList(regular);
if (regulars.size() > 0) {
return new ServerResult<List<Regular>>(true, regulars);
return new ServerResult<>(true, regulars);
} else {
return new ServerResult<List<Regular>>(false, ReturnConstants.RESULT_EMPTY);
return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
}
} catch (RuntimeException e) {
logger.error(e.getMessage());
return new ServerResult<List<Regular>>(false, ReturnConstants.DB_EX);
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
@ -82,10 +82,10 @@ public class RegularServiceImpl implements RegularService {
regular.setCreateTime(DateUtils.getNowDate());
regular.setCreateBy(SecurityUtils.getUserId());
int renewal = regularDao.insertRegular(regular);
return new ServerResult<Integer>(true, renewal);
return new ServerResult<>(true, renewal);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return new ServerResult<Integer>(false, ReturnConstants.DB_EX);
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
@ -101,10 +101,10 @@ public class RegularServiceImpl implements RegularService {
regular.setUpdateTime(DateUtils.getNowDate());
regular.setUpdateBy(SecurityUtils.getUserId());
int renewal = regularDao.updateRegular(regular);
return new ServerResult<Integer>(true, renewal);
return new ServerResult<>(true, renewal);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return new ServerResult<Integer>(false, ReturnConstants.DB_EX);
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
@ -118,10 +118,10 @@ public class RegularServiceImpl implements RegularService {
public ServerResult<Integer> deleteRegularByIds(Long[] ids) {
try {
Integer renewals = regularDao.deleteRegularByIds(ids);
return new ServerResult<Integer>(true, renewals);
return new ServerResult<>(true, renewals);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return new ServerResult<Integer>(false, ReturnConstants.DB_EX);
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
@ -135,10 +135,10 @@ public class RegularServiceImpl implements RegularService {
public ServerResult<Integer> deleteRegularById(Long id) {
try {
Integer renewal = regularDao.deleteRegularById(id);
return new ServerResult<Integer>(true, renewal);
return new ServerResult<>(true, renewal);
} catch (RuntimeException e) {
logger.error(e.getMessage());
return new ServerResult<Integer>(false, ReturnConstants.DB_EX);
return new ServerResult<>(false, ReturnConstants.DB_EX);
}
}
}

View File

@ -145,7 +145,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort, c.is_regular, r.regular
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
LEFT JOIN sys_regular r ON c.is_regular = r.id
LEFT JOIN gen_regular r ON c.is_regular = r.id
where t.table_id = #{tableId} order by c.sort
</select>
<!--todo 获取表信息 生成代码使用-->
@ -157,7 +157,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort, c.is_regular, r.regular
FROM gen_table t
LEFT JOIN gen_table_column c ON t.table_id = c.table_id
LEFT JOIN sys_regular r ON c.is_regular = r.id
LEFT JOIN gen_regular r ON c.is_regular = r.id
where t.table_name = #{tableName} order by c.sort
</select>
<!-- todo 查询数据库行配置信息-->

View File

@ -2,7 +2,7 @@
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hchyun.system.dao.RegularDao">
<mapper namespace="com.hchyun.generator.dao.RegularDao">
<resultMap type="Regular" id="RegularResult">
<result property="id" column="id" />
@ -17,12 +17,13 @@
</resultMap>
<sql id="selectRegularVo">
select id, name, regular, validation, enable, create_by, create_time, update_by, update_time from sys_regular
select id, name, regular, validation, enable, create_by, create_time, update_by, update_time from gen_regular
</sql>
<select id="selectRegularList" parameterType="Regular" resultMap="RegularResult">
<include refid="selectRegularVo"/>
<where>
and id != 1
<if test="name != null and name != ''"> and name like concat('%', #{name}, '%')</if>
<if test="regular != null and regular != ''"> and regular like concat('%', #{regular}, '%')</if>
<if test="validation != null and validation != ''"> and validation like concat('%', #{validation}, '%')</if>
@ -36,7 +37,7 @@
</select>
<insert id="insertRegular" parameterType="Regular" useGeneratedKeys="true" keyProperty="id">
insert into sys_regular
insert into gen_regular
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null and name != ''">name,</if>
<if test="regular != null and regular != ''">regular,</if>
@ -60,7 +61,7 @@
</insert>
<update id="updateRegular" parameterType="Regular">
update sys_regular
update gen_regular
<trim prefix="SET" suffixOverrides=",">
<if test="name != null and name != ''">name = #{name},</if>
<if test="regular != null and regular != ''">regular = #{regular},</if>
@ -75,11 +76,11 @@
</update>
<delete id="deleteRegularById" parameterType="Long">
delete from sys_regular where id = #{id}
delete from gen_regular where id = #{id}
</delete>
<delete id="deleteRegularByIds" parameterType="String">
delete from sys_regular where id in
delete from gen_regular where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>

View File

@ -37,7 +37,6 @@ import com.hchyun.quartz.util.CronUtils;
@RestController
@RequestMapping("/monitor/job")
public class JobController extends BaseController {
private Logger logger = LoggerFactory.getLogger(JobController.class);
@Autowired
private JobService jobService;
@ -48,14 +47,9 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:list')")
@GetMapping("/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);
}
startPage();
List<Job> list = jobService.selectJobList(job);
return getDataTable(list);
}
/**
@ -65,14 +59,9 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.EXPORT)
@GetMapping("/export")
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);
}
List<Job> list = jobService.selectJobList(job);
ExcelUtil<Job> util = new ExcelUtil<Job>(Job.class);
return util.exportExcel(list, "定时任务");
}
/**
@ -81,12 +70,7 @@ public class JobController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:query')")
@GetMapping(value = "/{jobId}")
public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
try {
return AjaxResult.success(jobService.selectJobById(jobId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(jobService.selectJobById(jobId));
}
/**
@ -96,16 +80,11 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.INSERT)
@PostMapping
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);
if (!CronUtils.isValid(job.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
}
job.setCreateBy(SecurityUtils.getUserId());
return toAjax(jobService.insertJob(job));
}
/**
@ -115,16 +94,11 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping
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);
if (!CronUtils.isValid(job.getCronExpression())) {
return AjaxResult.error("cron表达式不正确");
}
job.setUpdateBy(SecurityUtils.getUserId());
return toAjax(jobService.updateJob(job));
}
/**
@ -134,14 +108,9 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
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);
}
Job newJob = jobService.selectJobById(job.getJobId());
newJob.setStatus(job.getStatus());
return toAjax(jobService.changeStatus(newJob));
}
/**
@ -151,13 +120,8 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.UPDATE)
@PutMapping("/run")
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);
}
jobService.run(job);
return AjaxResult.success();
}
/**
@ -167,12 +131,7 @@ public class JobController extends BaseController {
@Log(title = "定时任务", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobIds}")
public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
try {
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
jobService.deleteJobByIds(jobIds);
return AjaxResult.success();
}
}

View File

@ -30,8 +30,6 @@ import com.hchyun.quartz.service.JobLogService;
@RestController
@RequestMapping("/monitor/jobLog")
public class JobLogController extends BaseController {
private Logger logger = LoggerFactory.getLogger(JobLogController.class);
@Autowired
private JobLogService jobLogService;
@ -41,14 +39,9 @@ public class JobLogController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:list')")
@GetMapping("/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);
}
startPage();
List<JobLog> list = jobLogService.selectJobLogList(jobLog);
return getDataTable(list);
}
/**
@ -58,14 +51,9 @@ public class JobLogController extends BaseController {
@Log(title = "任务调度日志", businessType = BusinessType.EXPORT)
@GetMapping("/export")
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);
}
List<JobLog> list = jobLogService.selectJobLogList(jobLog);
ExcelUtil<JobLog> util = new ExcelUtil<JobLog>(JobLog.class);
return util.exportExcel(list, "调度日志");
}
/**
@ -74,12 +62,7 @@ public class JobLogController extends BaseController {
@PreAuthorize("@hchyun.hasPermi('monitor:job:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long jobLogId) {
try {
return AjaxResult.success(jobLogService.selectJobLogById(jobLogId));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return AjaxResult.success(jobLogService.selectJobLogById(jobLogId));
}
@ -90,12 +73,7 @@ public class JobLogController extends BaseController {
@Log(title = "定时任务调度日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{jobLogIds}")
public AjaxResult remove(@PathVariable Long[] jobLogIds) {
try {
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
return toAjax(jobLogService.deleteJobLogByIds(jobLogIds));
}
/**
@ -105,12 +83,7 @@ public class JobLogController extends BaseController {
@Log(title = "调度日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean() {
try {
jobLogService.cleanJobLog();
return AjaxResult.success();
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
jobLogService.cleanJobLog();
return AjaxResult.success();
}
}

View File

@ -3,6 +3,9 @@ package com.hchyun.system.service.impl;
import java.util.List;
import javax.annotation.PostConstruct;
import com.hchyun.common.constant.ReturnConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -15,6 +18,7 @@ import com.hchyun.common.utils.StringUtils;
import com.hchyun.system.dao.DictDataDao;
import com.hchyun.system.dao.DictTypeDao;
import com.hchyun.system.service.DictTypeService;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
/**
* 字典 业务层处理
@ -23,6 +27,8 @@ import com.hchyun.system.service.DictTypeService;
*/
@Service
public class DictTypeServiceImpl implements DictTypeService {
private Logger logger = LoggerFactory.getLogger(DictTypeServiceImpl.class);
@Autowired
private DictTypeDao dictTypeMapper;
@ -34,10 +40,15 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@PostConstruct
public void init() {
List<DictType> dictTypeList = dictTypeMapper.selectDictTypeAll();
for (DictType dictType : dictTypeList) {
List<DictData> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
DictUtils.setDictCache(dictType.getDictType(), dictDatas);
try {
List<DictType> dictTypeList = dictTypeMapper.selectDictTypeAll();
for (DictType dictType : dictTypeList) {
List<DictData> dictDatas = dictDataMapper.selectDictDataByType(dictType.getDictType());
DictUtils.setDictCache(dictType.getDictType(), dictDatas);
}
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
@ -49,7 +60,12 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public List<DictType> selectDictTypeList(DictType dictType) {
return dictTypeMapper.selectDictTypeList(dictType);
try {
return dictTypeMapper.selectDictTypeList(dictType);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -59,7 +75,12 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public List<DictType> selectDictTypeAll() {
return dictTypeMapper.selectDictTypeAll();
try {
return dictTypeMapper.selectDictTypeAll();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -70,16 +91,21 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public List<DictData> selectDictDataByType(String dictType) {
List<DictData> dictDatas = DictUtils.getDictCache(dictType);
if (StringUtils.isNotEmpty(dictDatas)) {
return dictDatas;
try {
List<DictData> dictDatas = DictUtils.getDictCache(dictType);
if (StringUtils.isNotEmpty(dictDatas)) {
return dictDatas;
}
dictDatas = dictDataMapper.selectDictDataByType(dictType);
if (StringUtils.isNotEmpty(dictDatas)) {
DictUtils.setDictCache(dictType, dictDatas);
return dictDatas;
}
return null;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
dictDatas = dictDataMapper.selectDictDataByType(dictType);
if (StringUtils.isNotEmpty(dictDatas)) {
DictUtils.setDictCache(dictType, dictDatas);
return dictDatas;
}
return null;
}
/**
@ -90,7 +116,12 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public DictType selectDictTypeById(Long dictId) {
return dictTypeMapper.selectDictTypeById(dictId);
try {
return dictTypeMapper.selectDictTypeById(dictId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -101,7 +132,12 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public DictType selectDictTypeByType(String dictType) {
return dictTypeMapper.selectDictTypeByType(dictType);
try {
return dictTypeMapper.selectDictTypeByType(dictType);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -112,17 +148,22 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public int deleteDictTypeByIds(Long[] dictIds) {
for (Long dictId : dictIds) {
DictType dictType = selectDictTypeById(dictId);
if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
throw new CustomException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
try {
for (Long dictId : dictIds) {
DictType dictType = selectDictTypeById(dictId);
if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) {
throw new CustomException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
}
}
int count = dictTypeMapper.deleteDictTypeByIds(dictIds);
if (count > 0) {
DictUtils.clearDictCache();
}
return count;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
int count = dictTypeMapper.deleteDictTypeByIds(dictIds);
if (count > 0) {
DictUtils.clearDictCache();
}
return count;
}
/**
@ -130,7 +171,12 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public void clearCache() {
DictUtils.clearDictCache();
try {
DictUtils.clearDictCache();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -141,11 +187,16 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public int insertDictType(DictType dictType) {
int row = dictTypeMapper.insertDictType(dictType);
if (row > 0) {
DictUtils.clearDictCache();
try {
int row = dictTypeMapper.insertDictType(dictType);
if (row > 0) {
DictUtils.clearDictCache();
}
return row;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return row;
}
/**
@ -157,13 +208,19 @@ public class DictTypeServiceImpl implements DictTypeService {
@Override
@Transactional
public int updateDictType(DictType dictType) {
DictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId());
dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
int row = dictTypeMapper.updateDictType(dictType);
if (row > 0) {
DictUtils.clearDictCache();
try {
DictType oldDict = dictTypeMapper.selectDictTypeById(dictType.getDictId());
dictDataMapper.updateDictDataType(oldDict.getDictType(), dictType.getDictType());
int row = dictTypeMapper.updateDictType(dictType);
if (row > 0) {
DictUtils.clearDictCache();
}
return row;
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
return row;
}
/**
@ -174,11 +231,16 @@ public class DictTypeServiceImpl implements DictTypeService {
*/
@Override
public String checkDictTypeUnique(DictType dict) {
Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
DictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
DictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
}

View File

@ -2,6 +2,10 @@ package com.hchyun.system.service.impl;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.system.entity.Logininfor;
@ -15,6 +19,7 @@ import com.hchyun.system.service.LogininforService;
*/
@Service
public class LogininforServiceImpl implements LogininforService {
private Logger logger = LoggerFactory.getLogger(LogininforServiceImpl.class);
@Autowired
private LogininforDao logininforMapper;
@ -26,7 +31,12 @@ public class LogininforServiceImpl implements LogininforService {
*/
@Override
public void insertLogininfor(Logininfor logininfor) {
logininforMapper.insertLogininfor(logininfor);
try {
logininforMapper.insertLogininfor(logininfor);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -37,7 +47,12 @@ public class LogininforServiceImpl implements LogininforService {
*/
@Override
public List<Logininfor> selectLogininforList(Logininfor logininfor) {
return logininforMapper.selectLogininforList(logininfor);
try {
return logininforMapper.selectLogininforList(logininfor);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -48,7 +63,12 @@ public class LogininforServiceImpl implements LogininforService {
*/
@Override
public int deleteLogininforByIds(Long[] infoIds) {
return logininforMapper.deleteLogininforByIds(infoIds);
try {
return logininforMapper.deleteLogininforByIds(infoIds);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -56,6 +76,11 @@ public class LogininforServiceImpl implements LogininforService {
*/
@Override
public void cleanLogininfor() {
logininforMapper.cleanLogininfor();
try {
logininforMapper.cleanLogininfor();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
}

View File

@ -9,6 +9,10 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.common.constant.UserConstants;
@ -32,6 +36,8 @@ import com.hchyun.system.service.MenuService;
*/
@Service
public class MenuServiceImpl implements MenuService {
private Logger logger = LoggerFactory.getLogger(MenuServiceImpl.class);
public static final String PREMISSION_STRING = "perms[\"{0}\"]";
@Autowired
@ -51,7 +57,12 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<Menu> selectMenuList(Long userId) {
return selectMenuList(new Menu(), userId);
try {
return selectMenuList(new Menu(), userId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -62,15 +73,20 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<Menu> selectMenuList(Menu menu, Long userId) {
List<Menu> menuList = null;
// 管理员显示所有菜单信息
if (User.isAdmin(userId)) {
menuList = menuMapper.selectMenuList(menu);
} else {
menu.getParams().put("userId", userId);
menuList = menuMapper.selectMenuListByUserId(menu);
try {
List<Menu> menuList = null;
// 管理员显示所有菜单信息
if (User.isAdmin(userId)) {
menuList = menuMapper.selectMenuList(menu);
} else {
menu.getParams().put("userId", userId);
menuList = menuMapper.selectMenuListByUserId(menu);
}
return menuList;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return menuList;
}
/**
@ -81,14 +97,19 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public Set<String> selectMenuPermsByUserId(Long userId) {
List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (String perm : perms) {
if (StringUtils.isNotEmpty(perm)) {
permsSet.addAll(Arrays.asList(perm.trim().split(",")));
try {
List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (String perm : perms) {
if (StringUtils.isNotEmpty(perm)) {
permsSet.addAll(Arrays.asList(perm.trim().split(",")));
}
}
return permsSet;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return permsSet;
}
/**
@ -99,13 +120,18 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<Menu> selectMenuTreeByUserId(Long userId) {
List<Menu> menus = null;
if (SecurityUtils.isAdmin(userId)) {
menus = menuMapper.selectMenuTreeAll();
} else {
menus = menuMapper.selectMenuTreeByUserId(userId);
try {
List<Menu> menus = null;
if (SecurityUtils.isAdmin(userId)) {
menus = menuMapper.selectMenuTreeAll();
} else {
menus = menuMapper.selectMenuTreeByUserId(userId);
}
return getChildPerms(menus, 0);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return getChildPerms(menus, 0);
}
/**
@ -116,8 +142,13 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<Integer> selectMenuListByRoleId(Long roleId) {
Role role = roleMapper.selectRoleById(roleId);
return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
try {
Role role = roleMapper.selectRoleById(roleId);
return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -128,32 +159,37 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<RouterVo> buildMenus(List<Menu> menus) {
List<RouterVo> routers = new LinkedList<RouterVo>();
for (Menu menu : menus) {
RouterVo router = new RouterVo();
router.setHidden("1".equals(menu.getVisible()));
router.setName(getRouteName(menu));
router.setPath(getRouterPath(menu));
router.setComponent(getComponent(menu));
router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
List<Menu> cMenus = menu.getChildren();
if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
router.setAlwaysShow(true);
router.setRedirect("noRedirect");
router.setChildren(buildMenus(cMenus));
} else if (isMeunFrame(menu)) {
List<RouterVo> childrenList = new ArrayList<RouterVo>();
RouterVo children = new RouterVo();
children.setPath(menu.getPath());
children.setComponent(menu.getComponent());
children.setName(StringUtils.capitalize(menu.getPath()));
children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
childrenList.add(children);
router.setChildren(childrenList);
try {
List<RouterVo> routers = new LinkedList<RouterVo>();
for (Menu menu : menus) {
RouterVo router = new RouterVo();
router.setHidden("1".equals(menu.getVisible()));
router.setName(getRouteName(menu));
router.setPath(getRouterPath(menu));
router.setComponent(getComponent(menu));
router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
List<Menu> cMenus = menu.getChildren();
if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
router.setAlwaysShow(true);
router.setRedirect("noRedirect");
router.setChildren(buildMenus(cMenus));
} else if (isMeunFrame(menu)) {
List<RouterVo> childrenList = new ArrayList<RouterVo>();
RouterVo children = new RouterVo();
children.setPath(menu.getPath());
children.setComponent(menu.getComponent());
children.setName(StringUtils.capitalize(menu.getPath()));
children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache())));
childrenList.add(children);
router.setChildren(childrenList);
}
routers.add(router);
}
routers.add(router);
return routers;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return routers;
}
/**
@ -164,23 +200,28 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<Menu> buildMenuTree(List<Menu> menus) {
List<Menu> returnList = new ArrayList<Menu>();
List<Long> tempList = new ArrayList<Long>();
for (Menu dept : menus) {
tempList.add(dept.getMenuId());
}
for (Iterator<Menu> iterator = menus.iterator(); iterator.hasNext(); ) {
Menu menu = (Menu) iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(menu.getParentId())) {
recursionFn(menus, menu);
returnList.add(menu);
try {
List<Menu> returnList = new ArrayList<Menu>();
List<Long> tempList = new ArrayList<Long>();
for (Menu dept : menus) {
tempList.add(dept.getMenuId());
}
for (Iterator<Menu> iterator = menus.iterator(); iterator.hasNext(); ) {
Menu menu = (Menu) iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(menu.getParentId())) {
recursionFn(menus, menu);
returnList.add(menu);
}
}
if (returnList.isEmpty()) {
returnList = menus;
}
return returnList;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
if (returnList.isEmpty()) {
returnList = menus;
}
return returnList;
}
/**
@ -191,8 +232,13 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public List<TreeSelect> buildMenuTreeSelect(List<Menu> menus) {
List<Menu> menuTrees = buildMenuTree(menus);
return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
try {
List<Menu> menuTrees = buildMenuTree(menus);
return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -203,7 +249,12 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public Menu selectMenuById(Long menuId) {
return menuMapper.selectMenuById(menuId);
try {
return menuMapper.selectMenuById(menuId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -214,8 +265,13 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public boolean hasChildByMenuId(Long menuId) {
int result = menuMapper.hasChildByMenuId(menuId);
return result > 0 ? true : false;
try {
int result = menuMapper.hasChildByMenuId(menuId);
return result > 0 ? true : false;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -226,8 +282,13 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public boolean checkMenuExistRole(Long menuId) {
int result = roleMenuMapper.checkMenuExistRole(menuId);
return result > 0 ? true : false;
try {
int result = roleMenuMapper.checkMenuExistRole(menuId);
return result > 0 ? true : false;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -238,7 +299,12 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public int insertMenu(Menu menu) {
return menuMapper.insertMenu(menu);
try {
return menuMapper.insertMenu(menu);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -249,7 +315,12 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public int updateMenu(Menu menu) {
return menuMapper.updateMenu(menu);
try {
return menuMapper.updateMenu(menu);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -260,7 +331,12 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public int deleteMenuById(Long menuId) {
return menuMapper.deleteMenuById(menuId);
try {
return menuMapper.deleteMenuById(menuId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -271,12 +347,17 @@ public class MenuServiceImpl implements MenuService {
*/
@Override
public String checkMenuNameUnique(Menu menu) {
Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
Menu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
Menu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
if (StringUtils.isNotNull(info) && info.getMenuId().longValue() != menuId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**

View File

@ -2,6 +2,10 @@ package com.hchyun.system.service.impl;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.system.entity.Notice;
@ -15,6 +19,8 @@ import com.hchyun.system.service.NoticeService;
*/
@Service
public class NoticeServiceImpl implements NoticeService {
private Logger logger = LoggerFactory.getLogger(NoticeServiceImpl.class);
@Autowired
private NoticeDao noticeMapper;
@ -26,7 +32,12 @@ public class NoticeServiceImpl implements NoticeService {
*/
@Override
public Notice selectNoticeById(Long noticeId) {
return noticeMapper.selectNoticeById(noticeId);
try {
return noticeMapper.selectNoticeById(noticeId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -37,7 +48,12 @@ public class NoticeServiceImpl implements NoticeService {
*/
@Override
public List<Notice> selectNoticeList(Notice notice) {
return noticeMapper.selectNoticeList(notice);
try {
return noticeMapper.selectNoticeList(notice);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -48,7 +64,12 @@ public class NoticeServiceImpl implements NoticeService {
*/
@Override
public int insertNotice(Notice notice) {
return noticeMapper.insertNotice(notice);
try {
return noticeMapper.insertNotice(notice);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -59,7 +80,12 @@ public class NoticeServiceImpl implements NoticeService {
*/
@Override
public int updateNotice(Notice notice) {
return noticeMapper.updateNotice(notice);
try {
return noticeMapper.updateNotice(notice);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -70,7 +96,12 @@ public class NoticeServiceImpl implements NoticeService {
*/
@Override
public int deleteNoticeById(Long noticeId) {
return noticeMapper.deleteNoticeById(noticeId);
try {
return noticeMapper.deleteNoticeById(noticeId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -81,6 +112,11 @@ public class NoticeServiceImpl implements NoticeService {
*/
@Override
public int deleteNoticeByIds(Long[] noticeIds) {
return noticeMapper.deleteNoticeByIds(noticeIds);
try {
return noticeMapper.deleteNoticeByIds(noticeIds);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
}

View File

@ -2,6 +2,10 @@ package com.hchyun.system.service.impl;
import java.util.List;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hchyun.system.entity.OperLog;
@ -15,6 +19,8 @@ import com.hchyun.system.service.OperLogService;
*/
@Service
public class OperLogServiceImpl implements OperLogService {
private Logger logger = LoggerFactory.getLogger(OperLogServiceImpl.class);
@Autowired
private OperLogDao operLogMapper;
@ -25,7 +31,12 @@ public class OperLogServiceImpl implements OperLogService {
*/
@Override
public void insertOperlog(OperLog operLog) {
operLogMapper.insertOperlog(operLog);
try {
operLogMapper.insertOperlog(operLog);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -36,7 +47,12 @@ public class OperLogServiceImpl implements OperLogService {
*/
@Override
public List<OperLog> selectOperLogList(OperLog operLog) {
return operLogMapper.selectOperLogList(operLog);
try {
return operLogMapper.selectOperLogList(operLog);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -47,7 +63,12 @@ public class OperLogServiceImpl implements OperLogService {
*/
@Override
public int deleteOperLogByIds(Long[] operIds) {
return operLogMapper.deleteOperLogByIds(operIds);
try {
return operLogMapper.deleteOperLogByIds(operIds);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -58,7 +79,12 @@ public class OperLogServiceImpl implements OperLogService {
*/
@Override
public OperLog selectOperLogById(Long operId) {
return operLogMapper.selectOperLogById(operId);
try {
return operLogMapper.selectOperLogById(operId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -66,6 +92,11 @@ public class OperLogServiceImpl implements OperLogService {
*/
@Override
public void cleanOperLog() {
operLogMapper.cleanOperLog();
try {
operLogMapper.cleanOperLog();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
}

View File

@ -2,6 +2,9 @@ package com.hchyun.system.service.impl;
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.stereotype.Service;
import com.hchyun.common.constant.UserConstants;
@ -19,6 +22,8 @@ import com.hchyun.system.service.PostService;
*/
@Service
public class PostServiceImpl implements PostService {
private Logger logger = LoggerFactory.getLogger(PostServiceImpl.class);
@Autowired
private PostDao postMapper;
@ -33,7 +38,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public List<Post> selectPostList(Post post) {
return postMapper.selectPostList(post);
try {
return postMapper.selectPostList(post);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -43,7 +53,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public List<Post> selectPostAll() {
return postMapper.selectPostAll();
try {
return postMapper.selectPostAll();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -54,7 +69,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public Post selectPostById(Long postId) {
return postMapper.selectPostById(postId);
try {
return postMapper.selectPostById(postId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -65,7 +85,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public List<Integer> selectPostListByUserId(Long userId) {
return postMapper.selectPostListByUserId(userId);
try {
return postMapper.selectPostListByUserId(userId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -76,12 +101,17 @@ public class PostServiceImpl implements PostService {
*/
@Override
public String checkPostNameUnique(Post post) {
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
Post info = postMapper.checkPostNameUnique(post.getPostName());
if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
Post info = postMapper.checkPostNameUnique(post.getPostName());
if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -92,12 +122,17 @@ public class PostServiceImpl implements PostService {
*/
@Override
public String checkPostCodeUnique(Post post) {
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
Post info = postMapper.checkPostCodeUnique(post.getPostCode());
if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
Post info = postMapper.checkPostCodeUnique(post.getPostCode());
if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -108,7 +143,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public int countUserPostById(Long postId) {
return userPostMapper.countUserPostById(postId);
try {
return userPostMapper.countUserPostById(postId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -119,7 +159,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public int deletePostById(Long postId) {
return postMapper.deletePostById(postId);
try {
return postMapper.deletePostById(postId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -131,13 +176,18 @@ public class PostServiceImpl implements PostService {
*/
@Override
public int deletePostByIds(Long[] postIds) {
for (Long postId : postIds) {
Post post = selectPostById(postId);
if (countUserPostById(postId) > 0) {
throw new CustomException(String.format("%1$s已分配,不能删除", post.getPostName()));
try {
for (Long postId : postIds) {
Post post = selectPostById(postId);
if (countUserPostById(postId) > 0) {
throw new CustomException(String.format("%1$s已分配,不能删除", post.getPostName()));
}
}
return postMapper.deletePostByIds(postIds);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return postMapper.deletePostByIds(postIds);
}
/**
@ -148,7 +198,12 @@ public class PostServiceImpl implements PostService {
*/
@Override
public int insertPost(Post post) {
return postMapper.insertPost(post);
try {
return postMapper.insertPost(post);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -159,6 +214,11 @@ public class PostServiceImpl implements PostService {
*/
@Override
public int updatePost(Post post) {
return postMapper.updatePost(post);
try {
return postMapper.updatePost(post);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
}

View File

@ -6,6 +6,9 @@ import java.util.HashSet;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -22,6 +25,7 @@ import com.hchyun.system.dao.RoleDao;
import com.hchyun.system.dao.RoleMenuDao;
import com.hchyun.system.dao.UserRoleDao;
import com.hchyun.system.service.RoleService;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
/**
* 角色 业务层处理
@ -30,6 +34,8 @@ import com.hchyun.system.service.RoleService;
*/
@Service
public class RoleServiceImpl implements RoleService {
private Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);
@Autowired
private RoleDao roleMapper;
@ -51,7 +57,12 @@ public class RoleServiceImpl implements RoleService {
@Override
@DataScope(deptAlias = "d")
public List<Role> selectRoleList(Role role) {
return roleMapper.selectRoleList(role);
try {
return roleMapper.selectRoleList(role);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -62,14 +73,19 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public Set<String> selectRolePermissionByUserId(Long userId) {
List<Role> perms = roleMapper.selectRolePermissionByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (Role perm : perms) {
if (StringUtils.isNotNull(perm)) {
permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
try {
List<Role> perms = roleMapper.selectRolePermissionByUserId(userId);
Set<String> permsSet = new HashSet<>();
for (Role perm : perms) {
if (StringUtils.isNotNull(perm)) {
permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
}
}
return permsSet;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return permsSet;
}
/**
@ -80,7 +96,12 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public List<Role> selectRoleAll(Integer type) {
return SpringUtils.getAopProxy(this).selectRoleList(new Role(type));
try {
return SpringUtils.getAopProxy(this).selectRoleList(new Role(type));
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -91,7 +112,12 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public List<Integer> selectRoleListByUserId(Long userId) {
return roleMapper.selectRoleListByUserId(userId);
try {
return roleMapper.selectRoleListByUserId(userId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -102,7 +128,12 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public Role selectRoleById(Long roleId) {
return roleMapper.selectRoleById(roleId);
try {
return roleMapper.selectRoleById(roleId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -113,12 +144,17 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public String checkRoleNameUnique(Role role) {
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
Role info = roleMapper.checkRoleNameUnique(role.getRoleName());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
Role info = roleMapper.checkRoleNameUnique(role.getRoleName());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -129,12 +165,17 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public String checkRoleKeyUnique(Role role) {
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
Role info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
Role info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -144,8 +185,13 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public void checkRoleAllowed(Role role) {
if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
throw new CustomException("不允许操作超级管理员角色");
try {
if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
throw new CustomException("不允许操作超级管理员角色");
}
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
@ -157,7 +203,12 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public int countUserRoleByRoleId(Long roleId) {
return userRoleMapper.countUserRoleByRoleId(roleId);
try {
return userRoleMapper.countUserRoleByRoleId(roleId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -169,9 +220,15 @@ public class RoleServiceImpl implements RoleService {
@Override
@Transactional
public int insertRole(Role role) {
// 新增角色信息
roleMapper.insertRole(role);
return insertRoleMenu(role);
try {
// 新增角色信息
roleMapper.insertRole(role);
return insertRoleMenu(role);
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -183,11 +240,17 @@ public class RoleServiceImpl implements RoleService {
@Override
@Transactional
public int updateRole(Role role) {
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
return insertRoleMenu(role);
try {
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与菜单关联
roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
return insertRoleMenu(role);
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -198,7 +261,12 @@ public class RoleServiceImpl implements RoleService {
*/
@Override
public int updateRoleStatus(Role role) {
return roleMapper.updateRole(role);
try {
return roleMapper.updateRole(role);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -210,12 +278,18 @@ public class RoleServiceImpl implements RoleService {
@Override
@Transactional
public int authDataScope(Role role) {
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与部门关联
roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
// 新增角色和部门信息数据权限
return insertRoleDept(role);
try {
// 修改角色信息
roleMapper.updateRole(role);
// 删除角色与部门关联
roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
// 新增角色和部门信息数据权限
return insertRoleDept(role);
}catch (RuntimeException e){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**

View File

@ -1,5 +1,9 @@
package com.hchyun.system.service.impl;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.hchyun.common.core.entity.model.LoginUser;
import com.hchyun.common.utils.StringUtils;
@ -13,6 +17,8 @@ import com.hchyun.system.service.UserOnlineService;
*/
@Service
public class UserOnlineServiceImpl implements UserOnlineService {
private Logger logger = LoggerFactory.getLogger(UserOnlineServiceImpl.class);
/**
* 通过登录地址查询信息
*
@ -22,10 +28,15 @@ public class UserOnlineServiceImpl implements UserOnlineService {
*/
@Override
public UserOnline selectOnlineByIpaddr(String ipaddr, LoginUser user) {
if (StringUtils.equals(ipaddr, user.getIpaddr())) {
return loginUserToUserOnline(user);
try {
if (StringUtils.equals(ipaddr, user.getIpaddr())) {
return loginUserToUserOnline(user);
}
return null;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return null;
}
/**
@ -37,10 +48,15 @@ public class UserOnlineServiceImpl implements UserOnlineService {
*/
@Override
public UserOnline selectOnlineByUserName(String userName, LoginUser user) {
if (StringUtils.equals(userName, user.getUsername())) {
return loginUserToUserOnline(user);
try {
if (StringUtils.equals(userName, user.getUsername())) {
return loginUserToUserOnline(user);
}
return null;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return null;
}
/**
@ -53,10 +69,15 @@ public class UserOnlineServiceImpl implements UserOnlineService {
*/
@Override
public UserOnline selectOnlineByInfo(String ipaddr, String userName, LoginUser user) {
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
return loginUserToUserOnline(user);
try {
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
return loginUserToUserOnline(user);
}
return null;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return null;
}
/**
@ -67,20 +88,25 @@ public class UserOnlineServiceImpl implements UserOnlineService {
*/
@Override
public UserOnline loginUserToUserOnline(LoginUser user) {
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUser())) {
return null;
try {
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUser())) {
return null;
}
UserOnline userOnline = new UserOnline();
userOnline.setTokenId(user.getToken());
userOnline.setUserName(user.getUsername());
userOnline.setIpaddr(user.getIpaddr());
userOnline.setLoginLocation(user.getLoginLocation());
userOnline.setBrowser(user.getBrowser());
userOnline.setOs(user.getOs());
userOnline.setLoginTime(user.getLoginTime());
if (StringUtils.isNotNull(user.getUser().getDept())) {
userOnline.setDeptName(user.getUser().getDept().getDeptName());
}
return userOnline;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
UserOnline userOnline = new UserOnline();
userOnline.setTokenId(user.getToken());
userOnline.setUserName(user.getUsername());
userOnline.setIpaddr(user.getIpaddr());
userOnline.setLoginLocation(user.getLoginLocation());
userOnline.setBrowser(user.getBrowser());
userOnline.setOs(user.getOs());
userOnline.setLoginTime(user.getLoginTime());
if (StringUtils.isNotNull(user.getUser().getDept())) {
userOnline.setDeptName(user.getUser().getDept().getDeptName());
}
return userOnline;
}
}

View File

@ -3,6 +3,7 @@ package com.hchyun.system.service.impl;
import java.util.ArrayList;
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;
@ -25,6 +26,7 @@ import com.hchyun.system.dao.UserPostDao;
import com.hchyun.system.dao.UserRoleDao;
import com.hchyun.system.service.ConfigService;
import com.hchyun.system.service.UserService;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
/**
* 用户 业务层处理
@ -33,7 +35,7 @@ import com.hchyun.system.service.UserService;
*/
@Service
public class UserServiceImpl implements UserService {
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserDao userMapper;
@ -62,7 +64,12 @@ public class UserServiceImpl implements UserService {
@Override
@DataScope(deptAlias = "d", userAlias = "u")
public List<User> selectUserList(User user) {
return userMapper.selectUserList(user);
try {
return userMapper.selectUserList(user);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -73,7 +80,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public User selectUserByUserName(String userName) {
return userMapper.selectUserByUserName(userName);
try {
return userMapper.selectUserByUserName(userName);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -84,7 +96,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public User selectUserById(Long userId) {
return userMapper.selectUserById(userId);
try {
return userMapper.selectUserById(userId);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -95,15 +112,20 @@ public class UserServiceImpl implements UserService {
*/
@Override
public String selectUserRoleGroup(String userName) {
List<Role> list = roleMapper.selectRolesByUserName(userName);
StringBuffer idsStr = new StringBuffer();
for (Role role : list) {
idsStr.append(role.getRoleName()).append(",");
try {
List<Role> list = roleMapper.selectRolesByUserName(userName);
StringBuffer idsStr = new StringBuffer();
for (Role role : list) {
idsStr.append(role.getRoleName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
/**
@ -114,15 +136,20 @@ public class UserServiceImpl implements UserService {
*/
@Override
public String selectUserPostGroup(String userName) {
List<Post> list = postMapper.selectPostsByUserName(userName);
StringBuffer idsStr = new StringBuffer();
for (Post post : list) {
idsStr.append(post.getPostName()).append(",");
try {
List<Post> list = postMapper.selectPostsByUserName(userName);
StringBuffer idsStr = new StringBuffer();
for (Post post : list) {
idsStr.append(post.getPostName()).append(",");
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
if (StringUtils.isNotEmpty(idsStr.toString())) {
return idsStr.substring(0, idsStr.length() - 1);
}
return idsStr.toString();
}
/**
@ -133,11 +160,16 @@ public class UserServiceImpl implements UserService {
*/
@Override
public String checkUserNameUnique(String userName) {
int count = userMapper.checkUserNameUnique(userName);
if (count > 0) {
return UserConstants.NOT_UNIQUE;
try {
int count = userMapper.checkUserNameUnique(userName);
if (count > 0) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -148,12 +180,17 @@ public class UserServiceImpl implements UserService {
*/
@Override
public String checkPhoneUnique(User user) {
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
User info = userMapper.checkPhoneUnique(user.getPhonenumber());
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
User info = userMapper.checkPhoneUnique(user.getPhonenumber());
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -164,12 +201,17 @@ public class UserServiceImpl implements UserService {
*/
@Override
public String checkEmailUnique(User user) {
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
User info = userMapper.checkEmailUnique(user.getEmail());
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
return UserConstants.NOT_UNIQUE;
try {
Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
User info = userMapper.checkEmailUnique(user.getEmail());
if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
return UserConstants.NOT_UNIQUE;
}
return UserConstants.UNIQUE;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return UserConstants.UNIQUE;
}
/**
@ -179,8 +221,13 @@ public class UserServiceImpl implements UserService {
*/
@Override
public void checkUserAllowed(User user) {
if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
throw new CustomException("不允许操作超级管理员用户");
try {
if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
throw new CustomException("不允许操作超级管理员用户");
}
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
@ -193,13 +240,19 @@ public class UserServiceImpl implements UserService {
@Override
@Transactional
public int insertUser(User user) {
// 新增用户信息
int rows = userMapper.insertUser(user);
// 新增用户岗位关联
insertUserPost(user);
// 新增用户与角色管理
insertUserRole(user);
return rows;
try {
// 新增用户信息
int rows = userMapper.insertUser(user);
// 新增用户岗位关联
insertUserPost(user);
// 新增用户与角色管理
insertUserRole(user);
return rows;
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -211,16 +264,22 @@ public class UserServiceImpl implements UserService {
@Override
@Transactional
public int updateUser(User user) {
Long userId = user.getUserId();
// 删除用户与角色关联
userRoleMapper.deleteUserRoleByUserId(userId);
// 新增用户与角色管理
insertUserRole(user);
// 删除用户与岗位关联
userPostMapper.deleteUserPostByUserId(userId);
// 新增用户与岗位管理
insertUserPost(user);
return userMapper.updateUser(user);
try {
Long userId = user.getUserId();
// 删除用户与角色关联
userRoleMapper.deleteUserRoleByUserId(userId);
// 新增用户与角色管理
insertUserRole(user);
// 删除用户与岗位关联
userPostMapper.deleteUserPostByUserId(userId);
// 新增用户与岗位管理
insertUserPost(user);
return userMapper.updateUser(user);
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -231,7 +290,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public int updateUserStatus(User user) {
return userMapper.updateUser(user);
try {
return userMapper.updateUser(user);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -242,7 +306,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public int updateUserProfile(User user) {
return userMapper.updateUser(user);
try {
return userMapper.updateUser(user);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -254,7 +323,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public boolean updateUserAvatar(String userName, String avatar) {
return userMapper.updateUserAvatar(userName, avatar) > 0;
try {
return userMapper.updateUserAvatar(userName, avatar) > 0;
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -265,7 +339,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public int resetPwd(User user) {
return userMapper.updateUser(user);
try {
return userMapper.updateUser(user);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -277,7 +356,12 @@ public class UserServiceImpl implements UserService {
*/
@Override
public int resetUserPwd(String userName, String password) {
return userMapper.resetUserPwd(userName, password);
try {
return userMapper.resetUserPwd(userName, password);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -331,12 +415,19 @@ public class UserServiceImpl implements UserService {
* @return 结果
*/
@Override
@Transactional
public int deleteUserById(Long userId) {
// 删除用户与角色关联
userRoleMapper.deleteUserRoleByUserId(userId);
// 删除用户与岗位表
userPostMapper.deleteUserPostByUserId(userId);
return userMapper.deleteUserById(userId);
try {
// 删除用户与角色关联
userRoleMapper.deleteUserRoleByUserId(userId);
// 删除用户与岗位表
userPostMapper.deleteUserPostByUserId(userId);
return userMapper.deleteUserById(userId);
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
}
/**
@ -347,10 +438,15 @@ public class UserServiceImpl implements UserService {
*/
@Override
public int deleteUserByIds(Long[] userIds) {
for (Long userId : userIds) {
checkUserAllowed(new User(userId));
try {
for (Long userId : userIds) {
checkUserAllowed(new User(userId));
}
return userMapper.deleteUserByIds(userIds);
}catch (RuntimeException e){
logger.error(e.getMessage());
throw new CustomException(ReturnConstants.OP_ERROR);
}
return userMapper.deleteUserByIds(userIds);
}
/**
@ -362,47 +458,54 @@ public class UserServiceImpl implements UserService {
* @return 结果
*/
@Override
@Transactional
public String importUser(List<User> userList, Boolean isUpdateSupport, Long operName) {
if (StringUtils.isNull(userList) || userList.size() == 0) {
throw new CustomException("导入用户数据不能为空!");
}
int successNum = 0;
int failureNum = 0;
StringBuilder successMsg = new StringBuilder();
StringBuilder failureMsg = new StringBuilder();
String password = configService.selectConfigByKey("sys.user.initPassword");
for (User user : userList) {
try {
// 验证是否存在这个用户
User u = userMapper.selectUserByUserName(user.getUserName());
if (StringUtils.isNull(u)) {
user.setPassword(SecurityUtils.encryptPassword(password));
user.setCreateBy(operName);
this.insertUser(user);
successNum++;
successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
} else if (isUpdateSupport) {
user.setUpdateBy(operName);
this.updateUser(user);
successNum++;
successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
} else {
failureNum++;
failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
}
} catch (Exception e) {
failureNum++;
String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败:";
failureMsg.append(msg + e.getMessage());
log.error(msg, e);
try {
if (StringUtils.isNull(userList) || userList.size() == 0) {
throw new CustomException("导入用户数据不能为空!");
}
int successNum = 0;
int failureNum = 0;
StringBuilder successMsg = new StringBuilder();
StringBuilder failureMsg = new StringBuilder();
String password = configService.selectConfigByKey("sys.user.initPassword");
for (User user : userList) {
try {
// 验证是否存在这个用户
User u = userMapper.selectUserByUserName(user.getUserName());
if (StringUtils.isNull(u)) {
user.setPassword(SecurityUtils.encryptPassword(password));
user.setCreateBy(operName);
this.insertUser(user);
successNum++;
successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
} else if (isUpdateSupport) {
user.setUpdateBy(operName);
this.updateUser(user);
successNum++;
successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
} else {
failureNum++;
failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
}
} catch (Exception e) {
failureNum++;
String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败:";
failureMsg.append(msg + e.getMessage());
logger.error(msg, e);
}
}
if (failureNum > 0) {
failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
throw new CustomException(failureMsg.toString());
} else {
successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
}
return successMsg.toString();
}catch (RuntimeException e){
logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new CustomException(ReturnConstants.OP_ERROR);
}
if (failureNum > 0) {
failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");
throw new CustomException(failureMsg.toString());
} else {
successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:");
}
return successMsg.toString();
}
}

View File

@ -1,86 +0,0 @@
#!/bin/bash
AppName=hchyun-admin.jar
#JVM参数
JVM_OPTS="-Dname=$AppName -Duser.timezone=Asia/Shanghai -Xms512M -Xmx512M -XX:PermSize=256M -XX:MaxPermSize=512M -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC -XX:+UseParallelOldGC"
APP_HOME=`pwd`
LOG_PATH=$APP_HOME/logs/$AppName.log
if [ "$1" = "" ];
then
echo -e "\033[0;31m 未输入操作名 \033[0m \033[0;34m {start|stop|restart|status} \033[0m"
exit 1
fi
if [ "$AppName" = "" ];
then
echo -e "\033[0;31m 未输入应用名 \033[0m"
exit 1
fi
function start()
{
PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
if [ x"$PID" != x"" ]; then
echo "$AppName is running..."
else
nohup java -jar $JVM_OPTS target/$AppName > /dev/null 2>&1 &
echo "Start $AppName success..."
fi
}
function stop()
{
echo "Stop $AppName"
PID=""
query(){
PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`
}
query
if [ x"$PID" != x"" ]; then
kill -TERM $PID
echo "$AppName (pid:$PID) exiting..."
while [ x"$PID" != x"" ]
do
sleep 1
query
done
echo "$AppName exited."
else
echo "$AppName already stopped."
fi
}
function restart()
{
stop
sleep 2
start
}
function status()
{
PID=`ps -ef |grep java|grep $AppName|grep -v grep|wc -l`
if [ $PID != 0 ];then
echo "$AppName is running..."
else
echo "$AppName is not running..."
fi
}
case $1 in
start)
start;;
stop)
stop;;
restart)
restart;;
status)
status;;
*)
esac