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;
} }

基础BaseController的更多相关文章

  1. springMVC基础controller类

    此文章是基于 搭建SpringMVC+Spring+Hibernate平台 功能:设置请求.响应对象:session.cookie操作:ajax访问返回json数据: 创建springMVC基础con ...

  2. 使用Spring Boot搭建应用开发框架(一) —— 基础架构

    Spring的简史 第一阶段:XML配置,在Spring1.x时代,使用Spring开发满眼都是xml配置的Bean,随着项目的扩大,我们需要把xml配置文件分放到不同的配置文件里,那时候需要频繁的在 ...

  3. Spring Boot 构建电商基础秒杀项目 (十) 交易下单

    SpringBoot构建电商基础秒杀项目 学习笔记 新建表 create table if not exists order_info ( id varchar(32) not null defaul ...

  4. Spring Boot 构建电商基础秒杀项目 (八) 商品创建

    SpringBoot构建电商基础秒杀项目 学习笔记 新建数据表 create table if not exists item ( id int not null auto_increment, ti ...

  5. Spring Boot 构建电商基础秒杀项目 (四) getotp 页面

    SpringBoot构建电商基础秒杀项目 学习笔记 BaseController 添加 public static final String CONTENT_TYPE_FORMED = "a ...

  6. Spring Boot 构建电商基础秒杀项目 (三) 通用的返回对象 & 异常处理

    SpringBoot构建电商基础秒杀项目 学习笔记 定义通用的返回对象 public class CommonReturnType { // success, fail private String ...

  7. 接口开发-基于SpringBoot创建基础框架

    说到接口开发,能想到的开发语言有很多种,像什么Java啊..NET啊.PHP啊.NodeJS啊,太多可以用.为什么选择Java,究其原因,最后只有一个解释,那就是“学Java的人多,人员招聘范围大,有 ...

  8. 基于SpringBoot搭建应用开发框架(一) —— 基础架构

    目录 Spring的简史 零.开发技术简介 一.创建项目 1.创建工程 2.创建Starter 3.启动项目 4.Spring Boot 配置 5.项目结构划分 二.基础结构功能 1.web支持 2. ...

  9. 六、EnterpriseFrameWork框架基础功能之权限管理

    回<[开源]EnterpriseFrameWork框架系列文章索引> 从本章开始进入框架的第二块内容“EnterpriseFrameWork框架的基础功能”,包括:权限管理.字典数据管理. ...

随机推荐

  1. (数据科学学习手札119)Python+Dash快速web应用开发——多页面应用

    本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 这是我的系列教程Python+Dash快速web ...

  2. 分布式任务调度系统:xxl-job

    任务调度,通俗来说实际上就是"定时任务",分布式任务调度系统,翻译一下就是"分布式环境下定时任务系统". xxl-job一个分布式任务调度平台,其核心设计目标是 ...

  3. git 配置ssh

    git 配置ssh 生成一个个人账号/邮箱的sshkey ssh-keygen -t rsa -C "youremail@yourcompany.com" -f ~/.ssh/XX ...

  4. 从苏宁电器到卡巴斯基第15篇:我在苏宁电器当营业员 VII

    我们苹果的倒班制度 当年我在苏宁的时候,实行的是单休制度,而且只能选择在周一到周五其中的某一天,因为周六周日顾客比较多,是不允许休息的.尽管是单休,但并不表示我们在上班的时候每天都要完完整整地上八小时 ...

  5. hdu4685 最大匹配可能性

    题意:       给你n个王子和m个公主,每个王子可以和自己喜欢的公主结婚,问你在不影响最大匹配的前提下每个王子都可以去哪些公主. 思路:       所有王子向他喜欢的公主连一条边,然后匹配一遍, ...

  6. Windows PE 第一章开发环境和基本工具使用

    第一章 Windows PE 基本工具 1.1开发语言MASM32 1.1.1设置开发环境 这个不细说了,我在整理Intel汇编的时候详细的说了环境搭建以及细节.地址是:http://blog.csd ...

  7. 去除腾讯视频logo水印

    打开F12,然后再console中输入下面代码,即可. document.querySelectorAll(".txp_waterMark_pic").forEach(functi ...

  8. Spring Cloud Gateway + Nacos(1)简单配置

    当初我学习时候就是参考这位大佬的博客: Nacos集成Spring Cloud Gateway 基础使用 现在学习到spring cloud alibaba 使用nacos做服务中心,dubbo做通信 ...

  9. ES6新增常用方法

    字符串新增方法 padStart.padEnd 如果原字符串不够指定长度,则会在左侧(右侧)填充字符串,用以补全 padStart( length: number, fillStr?: string ...

  10. MySQL中几种常见的日志

    前言: 在 MySQL 系统中,有着诸多不同类型的日志.各种日志都有着自己的用途,通过分析日志,我们可以优化数据库性能,排除故障,甚至能够还原数据.这些不同类型的日志有助于我们更清晰的了解数据库,在日 ...