基础BaseController

1.依赖状态枚举

/**
 *  status enum
 */
public enum Status {

    SUCCESS(0, "success", "成功"),

    INTERNAL_SERVER_ERROR_ARGS(10000, "Internal Server Error: {0}", "服务端异常: {0}"),

    REQUEST_PARAMS_NOT_VALID_ERROR(10001, "request parameter {0} is not valid", "请求参数[{0}]无效"),
    CREATE_JOB_FAILED(10002, "create job failed", "创建任务失败"),
    JOB_NOT_EXISTS(10005, "job {0} not exists", "任务{0}不存在"),
    SCENE_NOT_EXISTS(10055, "scene {0} not exists", "场景{0}不存在"),
    UPDATE_SCENE_ERROR(10056, "update scene error", "场景更新失败"),
    DELETE_PROJECT_ERROR_JOBS_NOT_NULL(10137, "please delete the job in project first!", "请先删除全部Job"),
    STOP_JOB_FAILED(10007, "stop job failed", "停止任务失败"),
    EXECUTE_JOB_FAILED(10008, "execute job failed", "执行任务失败"),
    QUERY_JOB_FAILED(10009, "query job failed", "查询任务失败"),
    QUERY_JOB_NODE_FAILED(40001, "query job node failed", "查询任务节点失败"),
    STOP_JOB_NODE_FAILED(40002, "stop job node failed", "停止任务节点失败"),
    JOB_NODE_NOT_RUNNING(40003, "job node {0} is not running", "任务节点{0}已停止"),
    DELETE_JOB_FAILED(10003, "query job failed", "删除任务失败"),
    RELEASE_JOB_FAILED(40000, "release job failed", "上线任务失败"),
    JOB_STATUS_FAILED(10006, "job status failed", "任务状态异常"),
    JOB_HAS_RUNNING_INSTANCE(10061, "job {0} has running instance", "任务{0}已经提交过,请勿重复提交"),
    JOB_NOT_ONLINE(10060, "job {0} not online", "任务{0}未上线"),
    JOB_NOT_RUNNING(10062, "job {0} not running", "任务{0}为运行"),
    USER_NAME_NULL(10004,"user name is null", "用户名不能为空"),
    USER_NOT_EXIST(10010, "user {0} not exists", "用户[{0}]不存在"),
    USER_NAME_PASSWD_ERROR(10013,"user name or password error", "用户名或密码错误"),
    LOGIN_SESSION_FAILED(10014,"create session failed!", "创建session失败"),
    LOGIN_SUCCESS(10042,"login success", "登录成功"),
    IP_IS_EMPTY(10125,"ip is empty", "IP地址不能为空"),
    PROJECT_ALREADY_EXISTS(10019, "project {0} already exists", "项目名称[{0}]已存在"),
    JOB_NOT_ALLOWED_EDIT(10020, "job {0} online not allowed edit", "项目名称[{0}]已存在"),
    CREATE_PROJECT_ERROR(10048,"create project error", "创建项目错误"),
    PROJECT_NOT_FOUNT(10018, "project {0} not found ", "项目[{0}]不存在"),
    UPDATE_PROJECT_ERROR(10046,"update project error", "更新项目信息错误"),
    UPDATE_JOB_ERROR(10107,"update job error", "更新Job信息错误"),
    UPDATE_NODE_ERROR(10108,"update node {0} error", "更新Node {0} 信息错误"),
    USER_NO_OPERATION_PERM(30001, "user has no operation privilege", "当前用户没有操作权限"),
    DELETE_PROJECT_ERROR(10050,"delete project error", "删除项目错误"),
    DELETE_JOB_ERROR(10055,"delete job error", "删除Job错误"),
    TARGET_KEYWORD_ERROR(10051,"target app {0} keyword error", "目标应用 {0} 关键字未配置"),
    TARGET_ERROR(10054,"target error", "目标配置错误"),
    CREATE_PROJECT_USER_ERROR(10052,"create project user error", "创建项目关联用户错误"),
    DEL_PROJECT_USER_ERROR(10053,"del project user error", "删除项目关系错误"),
    USER_NO_OPERATION_PROJECT_PERM(30002, "user {0} is not has project {1} permission", "当前用户[{0}]没有[{1}]项目的操作权限"),
    START_JOB_ERROR(50014,"start job error", "运行任务失败"),
    STOP_JOB_ERROR(50015,"stop job error", "停止任务失败"),
    STOP_JOB_NODE_ERROR(50016,"stop job node error", "停止任务节点失败"),
    QUERY_JOB_NODE_LIST_ERROR(50017,"query job node list error", "查询任务节点失败"),
    QUERY_JOB_LIST_ERROR(50018,"query job list error", "查询任务失败"),
    QUERY_APP_LIST_ERROR(50019,"query app list error", "查询APP失败"),
    QUERY_INSTANCE_LIST_ERROR(50020,"query instance list error", "查询实例失败"),
    UPDATE_APP_KEYWORD_FAILED(50021,"update app {0} keyword error", "更新应用 {0} 关键字失败"),
    DELETE_RE_APP_ERROR(50022,"delete app error", "删除授权失败"),
    UPDATE_APP_KEYWORD_ERROR(50021,"update app keyword error", "更新应用关键字失败"),
    CLIENT_DEPLOY_ERROR(60001,"client deploy error", "客户端部署失败"),
    JOB_IDS_IS_EMPTY(60002,"job ids is empty", "请求的ids为空"),
    QUERY_APP_NO_PERMISSION(60003,"query all app no permission", "没有权限查询所有app"),
    QUERY_PROJECT_NO_PERMISSION(60004,"query all project no permission", "没有权限查询所有项目"),
    APP_IDS_IS_EMPTY(60005,"app id is null", "传入的appId为空"),
    ;

    private final int code;
    private final String enMsg;
    private final String zhMsg;

    private Status(int code, String enMsg, String zhMsg) {
        this.code = code;
        this.enMsg = enMsg;
        this.zhMsg = zhMsg;
    }

    public int getCode() {
        return this.code;
    }

    public String getMsg() {
        if (Locale.SIMPLIFIED_CHINESE.getLanguage().equals(LocaleContextHolder.getLocale().getLanguage())) {
            return this.zhMsg;
        } else {
            return this.enMsg;
        }
    }
}

2.基础controller,封装统一返回,包含success方法,error方法

public class BaseController {

    /**
     * get ip address in the http request
     *
     * @param request http servlet request
     * @return client ip address
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String clientIp = request.getHeader(HTTP_X_FORWARDED_FOR);

        if (StringUtils.isNotEmpty(clientIp) && !clientIp.equalsIgnoreCase(HTTP_HEADER_UNKNOWN)) {
            int index = clientIp.indexOf(COMMA);
            if (index != -1) {
                return clientIp.substring(0, index);
            } else {
                return clientIp;
            }
        }

        clientIp = request.getHeader(HTTP_X_REAL_IP);
        if (StringUtils.isNotEmpty(clientIp) && !clientIp.equalsIgnoreCase(HTTP_HEADER_UNKNOWN)) {
            return clientIp;
        }

        return request.getRemoteAddr();
    }

    /**
     * return data list
     *
     * @param result result code
     * @return result code
     */
    public Result returnDataList(Map<String, Object> result) {
        Status status = (Status) result.get(Constants.STATUS);
        if (status == Status.SUCCESS) {
            String msg = Status.SUCCESS.getMsg();
            Object datalist = result.get(Constants.DATA_LIST);
            return success(msg, datalist);
        } else {
            Integer code = status.getCode();
            String msg = (String) result.get(Constants.MSG);
            return error(code, msg);
        }
    }

    /**
     * success
     *
     * @return success result code
     */
    public Result success() {
        Result result = new Result();
        result.setCode(Status.SUCCESS.getCode());
        result.setMsg(Status.SUCCESS.getMsg());

        return result;
    }

    /**
     * success does not need to return data
     *
     * @param msg success message
     * @return success result code
     */
    public Result success(String msg) {
        Result result = new Result();
        result.setCode(Status.SUCCESS.getCode());
        result.setMsg(msg);

        return result;
    }

    public Result returnDataListPaging(Map<String, Object> result) {
        Status status = (Status) result.get(Constants.STATUS);
        if (status == Status.SUCCESS) {
            result.put(Constants.MSG, Status.SUCCESS.getMsg());
            PageInfo<Object> pageInfo = (PageInfo<Object>) result.get(Constants.DATA_LIST);
            return success(pageInfo.getLists(), pageInfo.getCurrentPage(), pageInfo.getTotalCount(),
                    pageInfo.getTotalPage());
        } else {
            Integer code = status.getCode();
            String msg = (String) result.get(Constants.MSG);
            return error(code, msg);
        }
    }

    /**
     * return data no paging
     *
     * @param msg success message
     * @param list data list
     * @return success result code
     */
    public Result success(String msg, Object list) {
        return getResult(msg, list);
    }

    /**
     * return data no paging
     *
     * @param list success
     * @return success result code
     */
    public Result success(Object list) {
        return getResult(Status.SUCCESS.getMsg(), list);
    }

    /**
     * return the data use Map format, for example, passing the value of key, value, passing a value
     * eg. "/user/add"  then return user name: zhangsan
     *
     * @param msg message
     * @param object success object data
     * @return success result code
     */
    public Result success(String msg, Map<String, Object> object) {
        return getResult(msg, object);
    }

    /**
     * return data with paging
     *
     * @param totalList success object list
     * @param currentPage current page
     * @param total total
     * @param totalPage  total page
     * @return success result code
     */
    public Result success(Object totalList, Integer currentPage,
                                                  Integer total, Integer totalPage) {
        Result result = new Result();
        result.setCode(Status.SUCCESS.getCode());
        result.setMsg(Status.SUCCESS.getMsg());

        Map<String, Object> map = new HashMap<>(4);
        map.put(Constants.TOTAL_LIST, totalList);
        map.put(Constants.CURRENT_PAGE, currentPage);
        map.put(Constants.TOTAL_PAGE, totalPage);
        map.put(Constants.TOTAL, total);
        result.setData(map);
        return result;
    }

    /**
     * error handle
     *
     * @param code result code
     * @param msg result message
     * @return error result code
     */
    public Result error(Integer code, String msg) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    /**
     * put message to map
     *
     * @param result result
     * @param status status
     * @param statusParams object messages
     */
    protected void putMsg(Map<String, Object> result, Status status, Object... statusParams) {
        result.put(Constants.STATUS, status);
        if (statusParams != null && statusParams.length > 0) {
            result.put(Constants.MSG, MessageFormat.format(status.getMsg(), statusParams));
        } else {
            result.put(Constants.MSG, status.getMsg());
        }
    }

    /**
     * put message to result object
     *
     * @param result result
     * @param status status
     * @param statusParams status parameters
     */
    protected void putMsg(Result result, Status status, Object... statusParams) {
        result.setCode(status.getCode());

        if (statusParams != null && statusParams.length > 0) {
            result.setMsg(MessageFormat.format(status.getMsg(), statusParams));
        } else {
            result.setMsg(status.getMsg());
        }

    }

    /**
     * get result
     * @param msg message
     * @param list object list
     * @return result code
     */
    private Result getResult(String msg, Object list) {
        Result result = new Result();
        result.setCode(Status.SUCCESS.getCode());
        result.setMsg(msg);

        result.setData(list);
        return result;
    }
}

3.统计封装对象Result

public class Result<T> {
    /**
     * status
     */
    private Integer code;

    /**
     * message
     */
    private String msg;

    /**
     * data
     */
    private T data;

    public Result() {
    }

    public Result(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private Result(T data) {
        this.code  = 0;
        this.data = data;
    }

    private Result(Status status) {
        if (status != null) {
            this.code = status.getCode();
            this.msg = status.getMsg();
        }
    }

    /**
     * Call this function if there is success
     *
     * @param data data
     * @param <T> type
     * @return resule
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(data);
    }

    /**
     * Call this function if there is any error
     *
     * @param status status
     * @return result
     */
    public static Result error(Status status) {
        return new Result(status);
    }

    /**
     * Call this function if there is any error
     *
     * @param status status
     * @param args args
     * @return result
     */
    public static Result errorWithArgs(Status status, Object... args) {
        return new Result(status.getCode(), MessageFormat.format(status.getMsg(), args));
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


    @Override
    public String toString() {
        return "Status{" +
                "code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

4.基础service,封装统一的业务逻辑,权限,数据

public class BaseService {

    /**
     * check admin
     *
     * @param user input user
     * @return ture if administrator, otherwise return false
     */
    protected boolean isAdmin(ChaosUser user) {
        return user.getUserType() == UserType.ADMIN_USER;
    }

    /**
     * check admin
     *
     * @param loginUser login user
     * @param result result code
     * @return true if administrator, otherwise false
     */
    protected boolean checkAdmin(ChaosUser loginUser, Map<String, Object> result) {
        //only admin can operate
        if (!isAdmin(loginUser)) {
            putMsg(result, Status.USER_NO_OPERATION_PERM);
            return true;
        }
        return false;
    }

    /**
     * put message to map
     *
     * @param result result code
     * @param status status
     * @param statusParams status message
     */
    protected void putMsg(Map<String, Object> result, Status status, Object... statusParams) {
        result.put(Constants.STATUS, status);
        if (statusParams != null && statusParams.length > 0) {
            result.put(Constants.MSG, MessageFormat.format(status.getMsg(), statusParams));
        } else {
            result.put(Constants.MSG, status.getMsg());
        }
    }

    /**
     * put message to result object
     *
     * @param result result code
     * @param status status
     * @param statusParams status message
     */
    protected void putMsg(Result result, Status status, Object... statusParams) {
        result.setCode(status.getCode());

        if (statusParams != null && statusParams.length > 0) {
            result.setMsg(MessageFormat.format(status.getMsg(), statusParams));
        } else {
            result.setMsg(status.getMsg());
        }

    }

    /**
     * get cookie info by name
     * @param request request
     * @param name 'sessionId'
     * @return get cookie info
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.isNotEmpty(name) && name.equalsIgnoreCase(cookie.getName())) {
                    return cookie;
                }
            }
        }

        return null;
    }

    protected boolean hasPerm(ChaosUser operateUser, int groupId, List<Integer> currentGroupIds){
        return isAdmin(operateUser) || currentGroupIds.contains(groupId);
    }

    protected boolean hasPerm(ChaosUser operateUser, String createUserName){
        return operateUser.getUsername().equalsIgnoreCase(createUserName) || isAdmin(operateUser);
    }
}

5.基于BaseController 写自己的业务controller

@RestController
@RequestMapping("projects/user")
@Api(tags = "用户授权管理")
public class ProjectUserController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ProjectUserController.class);

    @Resource
    ProjectUserService projectUserService;

    /**
     * 添加场景
     */
    @ApiOperation(value = "添加权限", notes = "添加权限")
    @PostMapping("/perm/add")
    public Result addProjectUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) ChaosUser loginUser,
                                 @RequestParam(value = "userNames") String userErp,
                                 @RequestParam(value = "projectId") int projectId) {
        logger.info("user {}, add perm user:{} projectId:{}", loginUser.getUsername(), userErp, projectId);
        Map<String, Object> result = projectUserService.addBatch(loginUser, userErp, projectId);
        return returnDataList(result);
    }


    /**
     * 添加场景
     */
    @ApiOperation(value = "查询权限", notes = "查询权限")
    @GetMapping("/perm/list")
    public Result listProjectUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) ChaosUser loginUser) {
        logger.info("user {}, query perm list", loginUser.getUsername());
        Map<String, Object> result = projectUserService.listProjectUser();
        return returnDataList(result);
    }

    /**
     * 添加场景
     */
    @ApiOperation(value = "删除权限", notes = "删除权限")
    @DeleteMapping("/perm/del/{id}")
    public Result delProjectUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) ChaosUser loginUser,
                                 @ApiParam(name = "id", value = "主键id", required = true) @PathVariable("id") int id) {
        logger.info("user {}, query perm list", loginUser.getUsername());
        Map<String, Object> result = projectUserService.delProjectUser(id);
        return returnDataList(result);
    }

    @ApiOperation(value = "查询全部用户", notes = "查询全部用户")
    @GetMapping("/all")
    public Result queryAllUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) ChaosUser loginUser) {
        logger.info("user {}, query all user list", loginUser.getUsername());
        Map<String, Object> result = projectUserService.listAllUser();
        return returnDataList(result);
    }
}

6.基于BaseService编写自己的业务service

@Service
public class ProjectUserService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(ProjectUserService.class);

    @Resource
    ProjectUserMapper projectUserMapper;

    @Resource
    private ChaosLoginErpMapper loginErpMapper;


    /**
     * 添加权限
     * @param loginUser
     * @param userErp
     * @param projectId
     * @return
     */
    public Map<String,Object> addProjectUser(ChaosUser loginUser, String userErp, int projectId){
        Map<String, Object> result = Maps.newHashMap();
        QueryWrapper<ProjectUser> queryWrapper = Wrappers.query();
        queryWrapper.eq(ProjectUser.USER_NAME,userErp);
        queryWrapper.eq(ProjectUser.PROJECT_ID,projectId);
        List<ProjectUser> list = projectUserMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            boolean permStatus = generateProjectUser(loginUser,userErp,projectId);
            if (!permStatus){
                putMsg(result,Status.CREATE_PROJECT_USER_ERROR,Status.CREATE_PROJECT_USER_ERROR.getMsg());
            }else{
                putMsg(result,Status.SUCCESS);
            }
        }else{
            putMsg(result,Status.SUCCESS);
        }
        return result;
    }

    @Transactional
    public Map<String, Object> addBatch(ChaosUser loginUser, String erps, int projectId) {
        Map<String, Object> result = Maps.newHashMap();
        projectUserMapper.deleteByProjectId(projectId);
        if (StringUtils.isEmpty(erps)) {
            putMsg(result, Status.SUCCESS);
            return result;
        }

        String[] erpArray = erps.split(COMMA);
        for (String s : erpArray) {
            generateProjectUser(loginUser, s, projectId);
        }
        putMsg(result,Status.SUCCESS);
        return result;
    }

    public boolean generateProjectUser(ChaosUser loginUser,String userErp,int projectId){
        ProjectUser projectUser = new ProjectUser();
        projectUser.setUserName(userErp);
        projectUser.setProjectId(projectId);
        projectUser.setCreateTime(new Date());
        projectUser.setUpdateTime(new Date());
        projectUser.setCreateUser(loginUser.getUsername());
        projectUser.setUpdateUser(loginUser.getUsername());
        return projectUserMapper.insert(projectUser) > 0;
    }

    /**
     * 列出用户权限
     * @return
     */
    public Map<String,Object> listProjectUser(){
        Map<String,Object> result = Maps.newHashMap();
//        List<ProjectUser> list = projectUserMapper.selectList(null);
        List<ProjectUser> list = projectUserMapper.queryProjectUser();
        putMsg(result,Status.SUCCESS);
        result.put(Constants.DATA_LIST,list);
        return result;
    }

    public Map<String,Object> listAllUser(){
        Map<String,Object> result = Maps.newHashMap();
//        List<ProjectUser> list = projectUserMapper.selectList(null);
        List<ChaosLoginErp> list = loginErpMapper.selectList(null);
        putMsg(result,Status.SUCCESS);
        result.put(Constants.DATA_LIST,list);
        return result;
    }

    public Map<String,Object> delProjectUser(int id){
        Map<String,Object> result = Maps.newHashMap();
        boolean delStatus = projectUserMapper.deleteById(id) > 0 ? true: false;
        if (!delStatus){
            putMsg(result,Status.DEL_PROJECT_USER_ERROR,Status.DEL_PROJECT_USER_ERROR.getMsg());
        }else{
            putMsg(result,Status.SUCCESS);
        }
        return result;
    }

}
posted @ 2020-09-02 10:12  SpecialSpeculator  阅读(2900)  评论(0编辑  收藏  举报