♻️ Refactoring code.refactor R

This commit is contained in:
lishangbu 2019-07-17 22:25:09 +08:00
parent 63706e9eb0
commit 561d464456
16 changed files with 95 additions and 94 deletions

View File

@ -69,29 +69,19 @@ public class PigTokenEndpoint {
@DeleteMapping("/logout")
public R<Boolean> logout(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
if (StrUtil.isBlank(authHeader)) {
return R.<Boolean>builder()
.code(CommonConstants.SUCCESS)
.data(Boolean.FALSE)
.msg("退出失败token 为空").build();
return R.failed("退出失败token 为空");
}
String tokenValue = authHeader.replace(OAuth2AccessToken.BEARER_TYPE, StrUtil.EMPTY).trim();
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
return R.<Boolean>builder()
.code(CommonConstants.SUCCESS)
.data(Boolean.FALSE)
.msg("退出失败token 无效").build();
return R.failed("退出失败token 无效");
}
tokenStore.removeAccessToken(accessToken);
OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
tokenStore.removeRefreshToken(refreshToken);
return R.<Boolean>builder()
.code(CommonConstants.SUCCESS)
.data(Boolean.TRUE)
.build();
return R.ok();
}
/**
@ -105,7 +95,7 @@ public class PigTokenEndpoint {
if (StrUtil.isBlank(from)) {
return null;
}
return new R<>(redisTemplate.delete(PROJECT_OAUTH_ACCESS + token));
return R.ok(redisTemplate.delete(PROJECT_OAUTH_ACCESS + token));
}
@ -169,7 +159,7 @@ public class PigTokenEndpoint {
Page result = new Page(MapUtil.getInt(params, CURRENT), MapUtil.getInt(params, SIZE));
result.setRecords(list);
result.setTotal(Long.valueOf(redisTemplate.keys(PROJECT_OAUTH_ACCESS + "*").size()));
return new R(result);
return R.ok(result);
}

View File

@ -46,7 +46,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public R exception(Exception e) {
log.error("全局异常信息 ex={}", e.getMessage(), e);
return new R<>(e);
return R.failed(e);
}
/**
@ -59,10 +59,8 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R bodyValidExceptionHandler(MethodArgumentNotValidException exception) {
List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
R result = new R();
result.setMsg(fieldErrors.get(0).getDefaultMessage());
log.warn(fieldErrors.get(0).getDefaultMessage());
return result;
return R.failed(fieldErrors.get(0).getDefaultMessage());
}
}

View File

@ -29,44 +29,60 @@ import java.io.Serializable;
* @param <T>
* @author lengleng
*/
@Builder
@ToString
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
@Getter
@Setter
private int code = CommonConstants.SUCCESS;
private int code;
@Getter
@Setter
private String msg = "success";
private String msg;
@Getter
@Setter
private T data;
public R() {
super();
public static <T> R<T> ok() {
return restResult(null, CommonConstants.SUCCESS, null);
}
public R(T data) {
super();
this.data = data;
public static <T> R<T> ok(T data) {
return restResult(data, CommonConstants.SUCCESS, null);
}
public R(T data, String msg) {
super();
this.data = data;
this.msg = msg;
public static <T> R<T> ok(T data, String msg) {
return restResult(data, CommonConstants.SUCCESS, msg);
}
public R(Throwable e) {
super();
this.msg = e.getMessage();
this.code = CommonConstants.FAIL;
public static <T> R<T> failed() {
return restResult(null, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(String msg) {
return restResult(null, CommonConstants.FAIL, msg);
}
public static <T> R<T> failed(T data) {
return restResult(data, CommonConstants.FAIL, null);
}
public static <T> R<T> failed(T data, String msg) {
return restResult(data, CommonConstants.FAIL, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
}

View File

@ -61,7 +61,7 @@ public class PigAccessDeniedHandler extends OAuth2AccessDeniedHandler {
log.info("授权失败,禁止访问 {}", request.getRequestURI());
response.setCharacterEncoding(CommonConstants.UTF8);
response.setContentType(CommonConstants.CONTENT_TYPE);
R<String> result = new R<>(new PigDeniedException("授权失败,禁止访问"));
R<PigDeniedException> result = R.failed(new PigDeniedException("授权失败,禁止访问"));
response.setStatus(HttpStatus.HTTP_FORBIDDEN);
PrintWriter printWriter = response.getWriter();
printWriter.append(objectMapper.writeValueAsString(result));

View File

@ -82,8 +82,7 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
try {
return response.writeWith(Mono.just(response.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(
R.builder().msg(e.getMessage())
.code(CommonConstants.FAIL).build()))));
R.failed(e.getMessage())))));
} catch (JsonProcessingException e1) {
log.error("对象输出异常", e1);
}

View File

@ -48,7 +48,7 @@ public class DeptController {
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R<>(sysDeptService.getById(id));
return R.ok(sysDeptService.getById(id));
}
@ -59,7 +59,7 @@ public class DeptController {
*/
@GetMapping(value = "/tree")
public R listDeptTrees() {
return new R<>(sysDeptService.listDeptTrees());
return R.ok(sysDeptService.listDeptTrees());
}
/**
@ -69,7 +69,7 @@ public class DeptController {
*/
@GetMapping(value = "/user-tree")
public R listCurrentUserDeptTrees() {
return new R<>(sysDeptService.listCurrentUserDeptTrees());
return R.ok(sysDeptService.listCurrentUserDeptTrees());
}
/**
@ -82,7 +82,7 @@ public class DeptController {
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_dept_add')")
public R save(@Valid @RequestBody SysDept sysDept) {
return new R<>(sysDeptService.saveDept(sysDept));
return R.ok(sysDeptService.saveDept(sysDept));
}
/**
@ -95,7 +95,7 @@ public class DeptController {
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_dept_del')")
public R removeById(@PathVariable Integer id) {
return new R<>(sysDeptService.removeDeptById(id));
return R.ok(sysDeptService.removeDeptById(id));
}
/**
@ -109,6 +109,6 @@ public class DeptController {
@PreAuthorize("@pms.hasPermission('sys_dept_edit')")
public R update(@Valid @RequestBody SysDept sysDept) {
sysDept.setUpdateTime(LocalDateTime.now());
return new R<>(sysDeptService.updateDeptById(sysDept));
return R.ok(sysDeptService.updateDeptById(sysDept));
}
}

View File

@ -54,7 +54,7 @@ public class DictController {
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R<>(sysDictService.getById(id));
return R.ok(sysDictService.getById(id));
}
/**
@ -65,7 +65,7 @@ public class DictController {
*/
@GetMapping("/page")
public R<IPage> getDictPage(Page page, SysDict sysDict) {
return new R<>(sysDictService.page(page, Wrappers.query(sysDict)));
return R.ok(sysDictService.page(page, Wrappers.query(sysDict)));
}
/**
@ -77,7 +77,7 @@ public class DictController {
@GetMapping("/type/{type}")
@Cacheable(value = "dict_details", key = "#type")
public R getDictByType(@PathVariable String type) {
return new R<>(sysDictService.list(Wrappers
return R.ok(sysDictService.list(Wrappers
.<SysDict>query().lambda()
.eq(SysDict::getType, type)));
}
@ -93,7 +93,7 @@ public class DictController {
@CacheEvict(value = "dict_details", key = "#sysDict.type")
@PreAuthorize("@pms.hasPermission('sys_dict_add')")
public R save(@Valid @RequestBody SysDict sysDict) {
return new R<>(sysDictService.save(sysDict));
return R.ok(sysDictService.save(sysDict));
}
/**
@ -108,7 +108,7 @@ public class DictController {
@CacheEvict(value = "dict_details", key = "#type")
@PreAuthorize("@pms.hasPermission('sys_dict_del')")
public R removeById(@PathVariable Integer id, @PathVariable String type) {
return new R<>(sysDictService.removeById(id));
return R.ok(sysDictService.removeById(id));
}
/**
@ -122,6 +122,6 @@ public class DictController {
@CacheEvict(value = "dict_details", key = "#sysDict.type")
@PreAuthorize("@pms.hasPermission('sys_dict_edit')")
public R updateById(@Valid @RequestBody SysDict sysDict) {
return new R<>(sysDictService.updateById(sysDict));
return R.ok(sysDictService.updateById(sysDict));
}
}

View File

@ -50,7 +50,7 @@ public class LogController {
*/
@GetMapping("/page")
public R getLogPage(Page page, SysLog sysLog) {
return new R<>(sysLogService.page(page, Wrappers.query(sysLog)));
return R.ok(sysLogService.page(page, Wrappers.query(sysLog)));
}
/**
@ -62,7 +62,7 @@ public class LogController {
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_log_del')")
public R removeById(@PathVariable Long id) {
return new R<>(sysLogService.removeById(id));
return R.ok(sysLogService.removeById(id));
}
/**
@ -74,7 +74,7 @@ public class LogController {
@Inner
@PostMapping
public R save(@Valid @RequestBody SysLog sysLog) {
return new R<>(sysLogService.save(sysLog));
return R.ok(sysLogService.save(sysLog));
}
}

View File

@ -63,7 +63,7 @@ public class MenuController {
.map(MenuTree::new)
.sorted(Comparator.comparingInt(MenuTree::getSort))
.collect(Collectors.toList());
return new R<>(TreeUtil.buildByLoop(menuTreeList, -1));
return R.ok(TreeUtil.buildByLoop(menuTreeList, -1));
}
/**
@ -73,7 +73,7 @@ public class MenuController {
*/
@GetMapping(value = "/tree")
public R getTree() {
return new R<>(TreeUtil.buildTree(sysMenuService.list(Wrappers.emptyWrapper()), -1));
return R.ok(TreeUtil.buildTree(sysMenuService.list(Wrappers.emptyWrapper()), -1));
}
/**
@ -98,7 +98,7 @@ public class MenuController {
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R<>(sysMenuService.getById(id));
return R.ok(sysMenuService.getById(id));
}
/**
@ -111,7 +111,7 @@ public class MenuController {
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_menu_add')")
public R save(@Valid @RequestBody SysMenu sysMenu) {
return new R<>(sysMenuService.save(sysMenu));
return R.ok(sysMenuService.save(sysMenu));
}
/**
@ -137,7 +137,7 @@ public class MenuController {
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_menu_edit')")
public R update(@Valid @RequestBody SysMenu sysMenu) {
return new R<>(sysMenuService.updateMenuById(sysMenu));
return R.ok(sysMenuService.updateMenuById(sysMenu));
}
}

View File

@ -50,7 +50,7 @@ public class OauthClientDetailsController {
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R<>(sysOauthClientDetailsService.getById(id));
return R.ok(sysOauthClientDetailsService.getById(id));
}
@ -63,7 +63,7 @@ public class OauthClientDetailsController {
*/
@GetMapping("/page")
public R getOauthClientDetailsPage(Page page, SysOauthClientDetails sysOauthClientDetails) {
return new R<>(sysOauthClientDetailsService.page(page, Wrappers.query(sysOauthClientDetails)));
return R.ok(sysOauthClientDetailsService.page(page, Wrappers.query(sysOauthClientDetails)));
}
/**
@ -76,7 +76,7 @@ public class OauthClientDetailsController {
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_client_add')")
public R add(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) {
return new R<>(sysOauthClientDetailsService.save(sysOauthClientDetails));
return R.ok(sysOauthClientDetailsService.save(sysOauthClientDetails));
}
/**
@ -89,7 +89,7 @@ public class OauthClientDetailsController {
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_client_del')")
public R removeById(@PathVariable String id) {
return new R<>(sysOauthClientDetailsService.removeClientDetailsById(id));
return R.ok(sysOauthClientDetailsService.removeClientDetailsById(id));
}
/**
@ -102,6 +102,6 @@ public class OauthClientDetailsController {
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_client_edit')")
public R update(@Valid @RequestBody SysOauthClientDetails sysOauthClientDetails) {
return new R<>(sysOauthClientDetailsService.updateClientDetailsById(sysOauthClientDetails));
return R.ok(sysOauthClientDetailsService.updateClientDetailsById(sysOauthClientDetails));
}
}

View File

@ -48,7 +48,7 @@ public class RoleController {
*/
@GetMapping("/{id}")
public R getById(@PathVariable Integer id) {
return new R<>(sysRoleService.getById(id));
return R.ok(sysRoleService.getById(id));
}
/**
@ -61,7 +61,7 @@ public class RoleController {
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_role_add')")
public R save(@Valid @RequestBody SysRole sysRole) {
return new R<>(sysRoleService.save(sysRole));
return R.ok(sysRoleService.save(sysRole));
}
/**
@ -74,7 +74,7 @@ public class RoleController {
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_role_edit')")
public R update(@Valid @RequestBody SysRole sysRole) {
return new R<>(sysRoleService.updateById(sysRole));
return R.ok(sysRoleService.updateById(sysRole));
}
/**
@ -87,7 +87,7 @@ public class RoleController {
@DeleteMapping("/{id}")
@PreAuthorize("@pms.hasPermission('sys_role_del')")
public R removeById(@PathVariable Integer id) {
return new R<>(sysRoleService.removeRoleById(id));
return R.ok(sysRoleService.removeRoleById(id));
}
/**
@ -97,7 +97,7 @@ public class RoleController {
*/
@GetMapping("/list")
public R listRoles() {
return new R<>(sysRoleService.list(Wrappers.emptyWrapper()));
return R.ok(sysRoleService.list(Wrappers.emptyWrapper()));
}
/**
@ -108,7 +108,7 @@ public class RoleController {
*/
@GetMapping("/page")
public R getRolePage(Page page) {
return new R<>(sysRoleService.page(page, Wrappers.emptyWrapper()));
return R.ok(sysRoleService.page(page, Wrappers.emptyWrapper()));
}
/**
@ -123,6 +123,6 @@ public class RoleController {
@PreAuthorize("@pms.hasPermission('sys_role_perm')")
public R saveRoleMenus(Integer roleId, @RequestParam(value = "menuIds", required = false) String menuIds) {
SysRole sysRole = sysRoleService.getById(roleId);
return new R<>(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleId, menuIds));
return R.ok(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleId, menuIds));
}
}

View File

@ -53,9 +53,9 @@ public class UserController {
SysUser user = userService.getOne(Wrappers.<SysUser>query()
.lambda().eq(SysUser::getUsername, username));
if (user == null) {
return new R<>(Boolean.FALSE, "获取当前用户信息失败");
return R.failed("获取当前用户信息失败");
}
return new R<>(userService.getUserInfo(user));
return R.ok(userService.getUserInfo(user));
}
/**
@ -69,9 +69,9 @@ public class UserController {
SysUser user = userService.getOne(Wrappers.<SysUser>query()
.lambda().eq(SysUser::getUsername, username));
if (user == null) {
return new R<>(Boolean.FALSE, String.format("用户信息为空 %s", username));
return R.failed(String.format("用户信息为空 %s", username));
}
return new R<>(userService.getUserInfo(user));
return R.ok(userService.getUserInfo(user));
}
/**
@ -82,7 +82,7 @@ public class UserController {
*/
@GetMapping("/{id}")
public R user(@PathVariable Integer id) {
return new R<>(userService.getUserVoById(id));
return R.ok(userService.getUserVoById(id));
}
/**
@ -95,7 +95,7 @@ public class UserController {
public R user(@PathVariable String username) {
SysUser condition = new SysUser();
condition.setUsername(username);
return new R<>(userService.getOne(new QueryWrapper<>(condition)));
return R.ok(userService.getOne(new QueryWrapper<>(condition)));
}
/**
@ -109,7 +109,7 @@ public class UserController {
@PreAuthorize("@pms.hasPermission('sys_user_del')")
public R userDel(@PathVariable Integer id) {
SysUser sysUser = userService.getById(id);
return new R<>(userService.removeUserById(sysUser));
return R.ok(userService.removeUserById(sysUser));
}
/**
@ -122,7 +122,7 @@ public class UserController {
@PostMapping
@PreAuthorize("@pms.hasPermission('sys_user_add')")
public R user(@RequestBody UserDTO userDto) {
return new R<>(userService.saveUser(userDto));
return R.ok(userService.saveUser(userDto));
}
/**
@ -135,7 +135,7 @@ public class UserController {
@PutMapping
@PreAuthorize("@pms.hasPermission('sys_user_edit')")
public R updateUser(@Valid @RequestBody UserDTO userDto) {
return new R<>(userService.updateUser(userDto));
return R.ok(userService.updateUser(userDto));
}
/**
@ -147,7 +147,7 @@ public class UserController {
*/
@GetMapping("/page")
public R getUserPage(Page page, UserDTO userDTO) {
return new R<>(userService.getUserWithRolePage(page, userDTO));
return R.ok(userService.getUserWithRolePage(page, userDTO));
}
/**
@ -168,6 +168,6 @@ public class UserController {
*/
@GetMapping("/ancestor/{username}")
public R listAncestorUsers(@PathVariable String username) {
return new R<>(userService.listAncestorUsersByUsername(username));
return R.ok(userService.listAncestorUsersByUsername(username));
}
}

View File

@ -62,9 +62,7 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query()
.lambda().eq(SysMenu::getParentId, id));
if (CollUtil.isNotEmpty(menuList)) {
return R.builder()
.code(CommonConstants.FAIL)
.msg("菜单含有下级不能删除").build();
return R.failed("菜单含有下级不能删除");
}
sysRoleMenuMapper
@ -72,7 +70,7 @@ public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> impl
.lambda().eq(SysRoleMenu::getMenuId, id));
//删除当前菜单及其子菜单
return new R(this.removeById(id));
return R.ok(this.removeById(id));
}
@Override

View File

@ -166,13 +166,13 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
sysUser.setPassword(ENCODER.encode(userDto.getNewpassword1()));
} else {
log.warn("原密码错误,修改密码失败:{}", userDto.getUsername());
return new R<>(Boolean.FALSE, "原密码错误,修改失败");
return R.failed("原密码错误,修改失败");
}
}
sysUser.setPhone(userDto.getPhone());
sysUser.setUserId(userVO.getUserId());
sysUser.setAvatar(userDto.getAvatar());
return new R<>(this.updateById(sysUser));
return R.ok(this.updateById(sysUser));
}
@Override

View File

@ -49,7 +49,7 @@ public class SysGeneratorController {
*/
@GetMapping("/page")
public R<IPage> list(Page page, String tableName) {
return new R<>(sysGeneratorService.queryPage(page, tableName));
return R.ok(sysGeneratorService.queryPage(page, tableName));
}
/**

View File

@ -47,7 +47,7 @@ public class ${className}Controller {
*/
@GetMapping("/page")
public R<IPage<${className}>> get${className}Page(Page<${className}> page, ${className} ${classname}) {
return new R<>(${classname}Service.get${className}Page(page,${classname}));
return R.ok(${classname}Service.get${className}Page(page,${classname}));
}
@ -58,7 +58,7 @@ public class ${className}Controller {
*/
@GetMapping("/{${pk.lowerAttrName}}")
public R<${className}> getById(@PathVariable("${pk.lowerAttrName}") ${pk.attrType} ${pk.lowerAttrName}){
return new R<>(${classname}Service.getById(${pk.lowerAttrName}));
return R.ok(${classname}Service.getById(${pk.lowerAttrName}));
}
/**
@ -70,7 +70,7 @@ public class ${className}Controller {
@PostMapping
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_add')")
public R save(@RequestBody ${className} ${classname}){
return new R<>(${classname}Service.save(${classname}));
return R.ok(${classname}Service.save(${classname}));
}
/**
@ -82,7 +82,7 @@ public class ${className}Controller {
@PutMapping
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_edit')")
public R update(@RequestBody ${className} ${classname}){
return new R<>(${classname}Service.updateById(${classname}));
return R.ok()(${classname}Service.updateById(${classname}));
}
/**
@ -94,7 +94,7 @@ public class ${className}Controller {
@DeleteMapping("/{${pk.lowerAttrName}}")
@PreAuthorize("@pms.hasPermission('${moduleName}_${pathName}_del')")
public R removeById(@PathVariable ${pk.attrType} ${pk.lowerAttrName}){
return new R<>(${classname}Service.removeById(${pk.lowerAttrName}));
return R.ok(${classname}Service.removeById(${pk.lowerAttrName}));
}
}