Commit 2831ef16 by fengshuonan

删除core模块

parent d35355fe
......@@ -18,8 +18,9 @@
<dependencies>
<dependency>
<groupId>com.stylefeng</groupId>
<artifactId>guns-core</artifactId>
<groupId>cn.stylefeng.roses</groupId>
<artifactId>kernel-core</artifactId>
<version>1.0.0</version>
</dependency>
<!--spring boot依赖-->
......
package com.stylefeng.guns.config.datasource;
import cn.stylefeng.roses.core.config.properties.DruidProperties;
import cn.stylefeng.roses.core.config.properties.MutiDataSourceProperties;
import cn.stylefeng.roses.core.datascope.DataScopeInterceptor;
import cn.stylefeng.roses.core.mutidatasource.DynamicDataSource;
import cn.stylefeng.roses.core.mutidatasource.aop.MultiSourceExAop;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.stylefeng.guns.core.config.properties.DruidProperties;
import com.stylefeng.guns.core.config.properties.MutiDataSourceProperties;
import com.stylefeng.guns.core.datascope.DataScopeInterceptor;
import com.stylefeng.guns.core.mutidatasource.DynamicDataSource;
import com.stylefeng.guns.core.mutidatasource.aop.MultiSourceExAop;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
......
package com.stylefeng.guns.config.datasource;
import cn.stylefeng.roses.core.config.properties.DruidProperties;
import cn.stylefeng.roses.core.datascope.DataScopeInterceptor;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.stylefeng.guns.core.config.properties.DruidProperties;
import com.stylefeng.guns.core.datascope.DataScopeInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
......
package com.stylefeng.guns.config.properties;
import com.stylefeng.guns.core.util.ToolUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
......
package com.stylefeng.guns.config.properties;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.File;
import static com.stylefeng.guns.core.util.ToolUtil.getTempPath;
import static com.stylefeng.guns.core.util.ToolUtil.isEmpty;
import static cn.stylefeng.roses.core.util.ToolUtil.getTempPath;
/**
* guns项目配置
......@@ -42,7 +42,7 @@ public class GunsProperties {
public String getFileUploadPath() {
//如果没有写文件上传路径,保存到临时目录
if (isEmpty(fileUploadPath)) {
if (ToolUtil.isEmpty(fileUploadPath)) {
return getTempPath();
} else {
//判断有没有结尾符,没有得加上
......
package com.stylefeng.guns.config.web;
import cn.stylefeng.roses.core.xss.XssFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
......@@ -10,7 +11,6 @@ import com.google.code.kaptcha.util.Config;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.intercept.RestApiInteceptor;
import com.stylefeng.guns.core.listener.ConfigListener;
import com.stylefeng.guns.core.xss.XssFilter;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
......
package com.stylefeng.guns.core.aop;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.common.exception.InvalidKaptchaException;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroKit;
......@@ -22,8 +22,8 @@ import org.springframework.web.bind.annotation.ResponseStatus;
import java.lang.reflect.UndeclaredThrowableException;
import static com.stylefeng.guns.core.support.HttpKit.getIp;
import static com.stylefeng.guns.core.support.HttpKit.getRequest;
import static cn.stylefeng.roses.core.util.HttpContext.getIp;
import static cn.stylefeng.roses.core.util.HttpContext.getRequest;
/**
* 全局的的异常拦截器(拦截所有的控制器)(带有@RequestMapping注解的方法上都会拦截)
......@@ -40,14 +40,14 @@ public class GlobalExceptionHandler {
/**
* 拦截业务异常
*/
@ExceptionHandler(GunsException.class)
@ExceptionHandler(ServiceException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFount(GunsException e) {
public ErrorResponseData bussiness(ServiceException e) {
LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
getRequest().setAttribute("tip", e.getMessage());
log.error("业务异常:", e);
return new ErrorTip(e.getCode(), e.getMessage());
return new ErrorResponseData(e.getCode(), e.getMessage());
}
/**
......@@ -102,10 +102,10 @@ public class GlobalExceptionHandler {
@ExceptionHandler(UndeclaredThrowableException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public ErrorTip credentials(UndeclaredThrowableException e) {
public ErrorResponseData credentials(UndeclaredThrowableException e) {
getRequest().setAttribute("tip", "权限异常");
log.error("权限异常!", e);
return new ErrorTip(BizExceptionEnum.NO_PERMITION.getCode(), BizExceptionEnum.NO_PERMITION.getMessage());
return new ErrorResponseData(BizExceptionEnum.NO_PERMITION.getCode(), BizExceptionEnum.NO_PERMITION.getMessage());
}
/**
......@@ -114,10 +114,10 @@ public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFount(RuntimeException e) {
public ErrorResponseData notFount(RuntimeException e) {
LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
getRequest().setAttribute("tip", "服务器未知运行时异常");
log.error("运行时异常:", e);
return new ErrorTip(BizExceptionEnum.SERVER_ERROR.getCode(), BizExceptionEnum.SERVER_ERROR.getMessage());
return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(), BizExceptionEnum.SERVER_ERROR.getMessage());
}
}
package com.stylefeng.guns.core.aop;
import cn.stylefeng.roses.core.util.HttpContext;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.dictmap.base.AbstractDictMap;
import com.stylefeng.guns.core.log.LogManager;
......@@ -7,7 +8,6 @@ import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.Contrast;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
......@@ -90,12 +90,12 @@ public class LogAop {
//如果涉及到修改,比对变化
String msg;
if (bussinessName.indexOf("修改") != -1 || bussinessName.indexOf("编辑") != -1) {
if (bussinessName.contains("修改") || bussinessName.contains("编辑")) {
Object obj1 = LogObjectHolder.me().get();
Map<String, String> obj2 = HttpKit.getRequestParameters();
Map<String, String> obj2 = HttpContext.getRequestParameters();
msg = Contrast.contrastObj(dictClass, key, obj1, obj2);
} else {
Map<String, String> parameters = HttpKit.getRequestParameters();
Map<String, String> parameters = HttpContext.getRequestParameters();
AbstractDictMap dictMap = (AbstractDictMap) dictClass.newInstance();
msg = Contrast.parseMutiKey(dictMap,key,parameters);
}
......
package com.stylefeng.guns.core.beetl;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.stylefeng.guns.core.tag.DictSelectorTag;
import com.stylefeng.guns.core.util.KaptchaUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.core.Tag;
......
package com.stylefeng.guns.core.common.constant.dictmap.factory;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.constant.factory.IConstantFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import java.lang.reflect.Method;
......@@ -25,7 +25,7 @@ public class DictFieldWarpperFactory {
Method method = IConstantFactory.class.getMethod(methodName, Integer.class);
return method.invoke(constantFactory, Integer.parseInt(parameter.toString()));
} catch (Exception e1) {
throw new GunsException(BizExceptionEnum.ERROR_WRAPPER_FIELD);
throw new ServiceException(BizExceptionEnum.ERROR_WRAPPER_FIELD);
}
}
}
......
package com.stylefeng.guns.core.common.constant.factory;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.common.constant.cache.Cache;
import com.stylefeng.guns.core.common.constant.cache.CacheKey;
import com.stylefeng.guns.core.common.constant.state.ManagerStatus;
import com.stylefeng.guns.core.common.constant.state.MenuStatus;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.system.dao.*;
import com.stylefeng.guns.modular.system.model.*;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.support.StrKit;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.SpringContextHolder;
import com.stylefeng.guns.core.util.ToolUtil;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
......@@ -87,7 +87,7 @@ public class ConstantFactory implements IConstantFactory {
sb.append(roleObj.getName()).append(",");
}
}
return StrKit.removeSuffix(sb.toString(), ",");
return StrUtil.removeSuffix(sb.toString(), ",");
}
/**
......@@ -148,7 +148,7 @@ public class ConstantFactory implements IConstantFactory {
sb.append(menuObj.getName()).append(",");
}
}
return StrKit.removeSuffix(sb.toString(), ",");
return StrUtil.removeSuffix(sb.toString(), ",");
}
/**
......@@ -324,7 +324,7 @@ public class ConstantFactory implements IConstantFactory {
String[] split = pids.split(",");
ArrayList<Integer> parentDeptIds = new ArrayList<>();
for (String s : split) {
parentDeptIds.add(Integer.valueOf(StrKit.removeSuffix(StrKit.removePrefix(s, "["), "]")));
parentDeptIds.add(Integer.valueOf(StrUtil.removeSuffix(StrUtil.removePrefix(s, "["), "]")));
}
return parentDeptIds;
}
......
package com.stylefeng.guns.core.common.constant.factory;
import com.stylefeng.guns.core.support.StrKit;
import com.stylefeng.guns.core.util.ToolUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import java.util.ArrayList;
import java.util.HashMap;
......@@ -52,42 +53,18 @@ public class MutiStrFactory {
* @author fengshuonan
* @Date 2017/4/27 16:44
*/
public static List<Map<String,String>> parseKeyValue(String mutiString){
if(ToolUtil.isEmpty(mutiString)){
return new ArrayList<>();
}else{
ArrayList<Map<String,String>> results = new ArrayList<>();
String[] items = StrKit.split(StrKit.removeSuffix(mutiString, ITEM_SPLIT), ITEM_SPLIT);
for (String item : items) {
String[] attrs = item.split(ATTR_SPLIT);
HashMap<String, String> itemMap = new HashMap<>();
itemMap.put(MUTI_STR_CODE,attrs[0]);
itemMap.put(MUTI_STR_NAME,attrs[1]);
itemMap.put(MUTI_STR_NUM,attrs[2]);
results.add(itemMap);
}
return results;
}
}
/**
* 解析id:key:value这样类型的字符串
*
* @author fengshuonan
* @Date 2017/4/28 11:06
*/
public static List<Map<String,String>> parseIdKeyValue(String mutiString){
if(ToolUtil.isEmpty(mutiString)){
public static List<Map<String, String>> parseKeyValue(String mutiString) {
if (ToolUtil.isEmpty(mutiString)) {
return new ArrayList<>();
}else{
ArrayList<Map<String,String>> results = new ArrayList<>();
String[] items = StrKit.split(StrKit.removeSuffix(mutiString, ITEM_SPLIT), ITEM_SPLIT);
} else {
ArrayList<Map<String, String>> results = new ArrayList<>();
String[] items = StrUtil.split(StrUtil.removeSuffix(mutiString, ITEM_SPLIT), ITEM_SPLIT);
for (String item : items) {
String[] attrs = item.split(ATTR_SPLIT);
HashMap<String, String> itemMap = new HashMap<>();
itemMap.put(MUTI_STR_CODE,attrs[0]);
itemMap.put(MUTI_STR_NAME,attrs[1]);
itemMap.put(MUTI_STR_NUM,attrs[2]);
itemMap.put(MUTI_STR_CODE, attrs[0]);
itemMap.put(MUTI_STR_NAME, attrs[1]);
itemMap.put(MUTI_STR_NUM, attrs[2]);
results.add(itemMap);
}
return results;
......
package com.stylefeng.guns.core.common.constant.factory;
import cn.stylefeng.roses.core.util.HttpContext;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.state.Order;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.ToolUtil;
import javax.servlet.http.HttpServletRequest;
......@@ -16,7 +16,7 @@ import javax.servlet.http.HttpServletRequest;
public class PageFactory<T> {
public Page<T> defaultPage() {
HttpServletRequest request = HttpKit.getRequest();
HttpServletRequest request = HttpContext.getRequest();
int limit = Integer.valueOf(request.getParameter("limit")); //每页多少条数据
int offset = Integer.valueOf(request.getParameter("offset")); //每页的偏移量(本页当前有多少条)
String sort = request.getParameter("sort"); //排序字段名称
......
package com.stylefeng.guns.core.common.exception;
import com.stylefeng.guns.core.exception.ServiceExceptionEnum;
import cn.stylefeng.roses.kernel.model.exception.AbstractBaseExceptionEnum;
/**
* @author fengshuonan
* @Description 所有业务异常的枚举
* @date 2016年11月12日 下午5:04:51
*/
public enum BizExceptionEnum implements ServiceExceptionEnum {
public enum BizExceptionEnum implements AbstractBaseExceptionEnum {
/**
* 字典
......
package com.stylefeng.guns.core.base.controller;
package com.stylefeng.guns.core.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
......
package com.stylefeng.guns.core.base.controller;
package com.stylefeng.guns.core.controller;
import org.springframework.web.servlet.View;
......
package com.stylefeng.guns.core.intercept;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import cn.stylefeng.roses.core.util.RenderUtil;
import com.stylefeng.guns.core.common.constant.JwtConstants;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.util.JwtTokenUtil;
import com.stylefeng.guns.core.util.RenderUtil;
import io.jsonwebtoken.JwtException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
......@@ -43,17 +43,17 @@ public class RestApiInteceptor extends HandlerInterceptorAdapter {
try {
boolean flag = JwtTokenUtil.isTokenExpired(authToken);
if (flag) {
RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
RenderUtil.renderJson(response, new ErrorResponseData(BizExceptionEnum.TOKEN_EXPIRED.getCode(), BizExceptionEnum.TOKEN_EXPIRED.getMessage()));
return false;
}
} catch (JwtException e) {
//有异常就是token解析失败
RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
RenderUtil.renderJson(response, new ErrorResponseData(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
return false;
}
} else {
//header没有带Bearer字段
RenderUtil.renderJson(response, new ErrorTip(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
RenderUtil.renderJson(response, new ErrorResponseData(BizExceptionEnum.TOKEN_ERROR.getCode(), BizExceptionEnum.TOKEN_ERROR.getMessage()));
return false;
}
return true;
......
package com.stylefeng.guns.core.intercept;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.HttpSessionHolder;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.HttpSessionContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
......@@ -24,11 +24,11 @@ public class SessionHolderInterceptor extends BaseController {
@Around("cutService()")
public Object sessionKit(ProceedingJoinPoint point) throws Throwable {
HttpSessionHolder.put(super.getHttpServletRequest().getSession());
HttpSessionContext.put(super.getHttpServletRequest().getSession());
try {
return point.proceed();
} finally {
HttpSessionHolder.remove();
HttpSessionContext.remove();
}
}
}
package com.stylefeng.guns.core.log;
import com.stylefeng.guns.core.util.SpringContextHolder;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
......@@ -28,7 +28,6 @@ public class LogObjectHolder implements Serializable{
}
public static LogObjectHolder me(){
LogObjectHolder bean = SpringContextHolder.getBean(LogObjectHolder.class);
return bean;
return SpringContextHolder.getBean(LogObjectHolder.class);
}
}
package com.stylefeng.guns.core.log.factory;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.stylefeng.guns.core.common.constant.state.LogSucceed;
import com.stylefeng.guns.core.common.constant.state.LogType;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.modular.system.dao.LoginLogMapper;
import com.stylefeng.guns.modular.system.dao.OperationLogMapper;
import com.stylefeng.guns.modular.system.model.LoginLog;
import com.stylefeng.guns.modular.system.model.OperationLog;
import com.stylefeng.guns.core.db.Db;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.util.ToolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -23,8 +23,8 @@ import java.util.TimerTask;
public class LogTaskFactory {
private static Logger logger = LoggerFactory.getLogger(LogManager.class);
private static LoginLogMapper loginLogMapper = Db.getMapper(LoginLogMapper.class);
private static OperationLogMapper operationLogMapper = Db.getMapper(OperationLogMapper.class);
private static LoginLogMapper loginLogMapper = SpringContextHolder.getBean(LoginLogMapper.class);
private static OperationLogMapper operationLogMapper = SpringContextHolder.getBean(OperationLogMapper.class);
public static TimerTask loginLog(final Integer userId, final String ip) {
return new TimerTask() {
......@@ -59,7 +59,7 @@ public class LogTaskFactory {
return new TimerTask() {
@Override
public void run() {
LoginLog loginLog = LogFactory.createLoginLog(LogType.EXIT, userId, null,ip);
LoginLog loginLog = LogFactory.createLoginLog(LogType.EXIT, userId, null, ip);
try {
loginLogMapper.insert(loginLog);
} catch (Exception e) {
......
package com.stylefeng.guns.core.node;
import com.stylefeng.guns.core.constant.IsMenu;
import org.apache.commons.lang3.StringUtils;
import cn.stylefeng.roses.kernel.model.enums.YesOrNotEnum;
import java.util.*;
......@@ -196,7 +195,7 @@ public class MenuNode implements Comparable {
return nodes;
}
//剔除非菜单
nodes.removeIf(node -> node.getIsmenu() != IsMenu.YES.getCode());
nodes.removeIf(node -> !node.getIsmenu().equals(YesOrNotEnum.Y.getCode()));
//对菜单排序,返回列表按菜单等级,序号的排序方式排列
Collections.sort(nodes);
return mergeList(nodes, nodes.get(nodes.size() - 1).getLevels(), null);
......
package com.stylefeng.guns.core.shiro;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.stylefeng.guns.core.shiro.factory.IShiro;
import com.stylefeng.guns.core.shiro.factory.ShiroFactroy;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
......
......@@ -15,9 +15,9 @@
*/
package com.stylefeng.guns.core.shiro;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.util.ToolUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
......
......@@ -15,17 +15,18 @@
*/
package com.stylefeng.guns.core.shiro.check;
import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.roses.core.util.HttpContext;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import com.stylefeng.guns.core.listener.ConfigListener;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.support.CollectionKit;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.SpringContextHolder;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
/**
* 权限自定义检查
......@@ -45,7 +46,8 @@ public class PermissionCheckFactory implements ICheck {
if (null == user) {
return false;
}
String join = CollectionKit.join(permissions, ",");
ArrayList<Object> objects = CollectionUtil.newArrayList(permissions);
String join = CollectionUtil.join(objects, ",");
if (ShiroKit.hasAnyRoles(join)) {
return true;
}
......@@ -54,7 +56,7 @@ public class PermissionCheckFactory implements ICheck {
@Override
public boolean checkAll() {
HttpServletRequest request = HttpKit.getRequest();
HttpServletRequest request = HttpContext.getRequest();
ShiroUser user = ShiroKit.getUser();
if (null == user) {
return false;
......
......@@ -15,7 +15,8 @@
*/
package com.stylefeng.guns.core.shiro.check;
import com.stylefeng.guns.core.util.SpringContextHolder;
import cn.stylefeng.roses.core.util.SpringContextHolder;
/**
* 权限检查管理器(入口)
......
package com.stylefeng.guns.core.shiro.factory;
import cn.hutool.core.convert.Convert;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.constant.state.ManagerStatus;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.SpringContextHolder;
import com.stylefeng.guns.modular.system.dao.MenuMapper;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.User;
......
package com.stylefeng.guns.core.tag;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Dict;
import com.stylefeng.guns.modular.system.service.IDictService;
import org.beetl.core.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
......@@ -31,7 +32,7 @@ public class DictSelectorTag extends Tag {
//String tagName = (String) this.args[0];
Map attrs = (Map) args[1];
if(ToolUtil.isEmpty(attrs.get("code"))){
throw new GunsException(BizExceptionEnum.ERROR_CODE_EMPTY);
throw new ServiceException(BizExceptionEnum.ERROR_CODE_EMPTY);
}
//字典类型编码
......
package com.stylefeng.guns.core.util;
import com.stylefeng.guns.core.common.constant.Const;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.node.MenuNode;
import java.util.ArrayList;
......
package com.stylefeng.guns.core.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.stylefeng.guns.core.common.constant.dictmap.base.AbstractDictMap;
import com.stylefeng.guns.core.common.constant.dictmap.factory.DictFieldWarpperFactory;
import com.stylefeng.guns.core.support.StrKit;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
......@@ -45,7 +46,7 @@ public class Contrast {
continue;
}
if (o1 instanceof Date) {
o1 = DateUtil.getDay((Date) o1);
o1 = DateUtil.formatDate((Date) o1);
}
if (!o1.toString().equals(o2.toString())) {
if (i != 1) {
......@@ -81,12 +82,12 @@ public class Contrast {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMethod = pd.getReadMethod();
Object o1 = getMethod.invoke(pojo1);
Object o2 = pojo2.get(StrKit.firstCharToLowerCase(getMethod.getName().substring(3)));
Object o2 = pojo2.get(StrUtil.lowerFirst(getMethod.getName().substring(3)));
if (o1 == null || o2 == null) {
continue;
}
if (o1 instanceof Date) {
o1 = DateUtil.getDay((Date) o1);
o1 = DateUtil.formatDate((Date) o1);
} else if (o1 instanceof Integer) {
o2 = Integer.parseInt(o2.toString());
}
......@@ -137,18 +138,18 @@ public class Contrast {
}
Method getMethod = null;
try {
getMethod = clazz.getDeclaredMethod(prefix + StrKit.firstCharToUpperCase(field.getName()));
getMethod = clazz.getDeclaredMethod(prefix + StrUtil.upperFirst(field.getName()));
} catch (java.lang.NoSuchMethodException e) {
System.err.println("this className:" + clazz.getName() + " is not methodName: " + e.getMessage());
continue;
}
Object o1 = getMethod.invoke(pojo1);
Object o2 = pojo2.get(StrKit.firstCharToLowerCase(getMethod.getName().substring(prefixLength)));
Object o2 = pojo2.get(StrUtil.lowerFirst(getMethod.getName().substring(prefixLength)));
if (o1 == null || o2 == null) {
continue;
}
if (o1 instanceof Date) {
o1 = DateUtil.getDay((Date) o1);
o1 = DateUtil.formatDate((Date) o1);
} else if (o1 instanceof Integer) {
o2 = Integer.parseInt(o2.toString());
}
......@@ -182,7 +183,7 @@ public class Contrast {
*/
public static String parseMutiKey(AbstractDictMap dictMap, String key, Map<String, String> requests) {
StringBuilder sb = new StringBuilder();
if (key.indexOf(",") != -1) {
if (key.contains(",")) {
String[] keys = key.split(",");
for (String item : keys) {
String fieldWarpperMethodName = dictMap.getFieldWarpperMethodName(item);
......@@ -194,7 +195,7 @@ public class Contrast {
sb.append(dictMap.get(item) + "=" + value + ",");
}
}
return StrKit.removeSuffix(sb.toString(), ",");
return StrUtil.removeSuffix(sb.toString(), ",");
} else {
String fieldWarpperMethodName = dictMap.getFieldWarpperMethodName(key);
String value = requests.get(key);
......
package com.stylefeng.guns.core.util;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.stylefeng.guns.core.common.constant.JwtConstants;
import io.jsonwebtoken.*;
......
package com.stylefeng.guns.core.util;
import cn.stylefeng.roses.core.util.SpringContextHolder;
import com.stylefeng.guns.config.properties.GunsProperties;
/**
......
package com.stylefeng.guns.modular.api;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ErrorResponseData;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.JwtTokenUtil;
......@@ -64,7 +64,7 @@ public class ApiController extends BaseController {
result.put("token", JwtTokenUtil.generateToken(String.valueOf(user.getId())));
return result;
} else {
return new ErrorTip(500, "账号密码错误!");
return new ErrorResponseData(500, "账号密码错误!");
}
}
......
package com.stylefeng.guns.modular.system.controller;
import com.stylefeng.guns.core.base.controller.BaseController;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.stylefeng.guns.modular.system.service.INoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
......
package com.stylefeng.guns.modular.system.controller;
import com.stylefeng.guns.core.base.controller.BaseController;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.dictmap.DeptDict;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Dept;
import com.stylefeng.guns.modular.system.service.IDeptService;
import com.stylefeng.guns.modular.system.warpper.DeptWarpper;
......@@ -88,7 +88,7 @@ public class DeptController extends BaseController {
@ResponseBody
public Object add(Dept dept) {
if (ToolUtil.isOneEmpty(dept, dept.getSimplename())) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
//完善pids,根据pid拿到pid的pids
deptSetPids(dept);
......@@ -125,7 +125,7 @@ public class DeptController extends BaseController {
@ResponseBody
public Object update(Dept dept) {
if (ToolUtil.isEmpty(dept) || dept.getId() == null) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
deptSetPids(dept);
deptService.updateById(dept);
......
package com.stylefeng.guns.modular.system.controller;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.dictmap.DictMap;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Dict;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.warpper.DictWarpper;
......@@ -81,7 +81,7 @@ public class DictController extends BaseController {
@ResponseBody
public Object add(String dictCode,String dictTips,String dictName, String dictValues) {
if (ToolUtil.isOneEmpty(dictCode,dictName, dictValues)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
this.dictService.addDict(dictCode,dictName,dictTips,dictValues);
return SUCCESS_TIP;
......@@ -117,7 +117,7 @@ public class DictController extends BaseController {
@ResponseBody
public Object update(Integer dictId,String dictCode,String dictName, String dictTips,String dictValues) {
if (ToolUtil.isOneEmpty(dictId, dictCode, dictName, dictValues)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
dictService.editDict(dictId, dictCode,dictName, dictTips,dictValues);
return SUCCESS_TIP;
......
package com.stylefeng.guns.modular.system.controller;
import cn.stylefeng.roses.core.util.FileUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
......
package com.stylefeng.guns.modular.system.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.SqlRunner;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.constant.state.BizLogType;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.modular.system.model.OperationLog;
import com.stylefeng.guns.modular.system.service.IOperationLogService;
import com.stylefeng.guns.modular.system.warpper.LogWarpper;
......@@ -54,8 +55,8 @@ public class LogController extends BaseController {
public Object list(@RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) String logName, @RequestParam(required = false) Integer logType) {
Page<OperationLog> page = new PageFactory<OperationLog>().defaultPage();
List<Map<String, Object>> result = operationLogService.getOperationLogs(page, beginTime, endTime, logName, BizLogType.valueOf(logType), page.getOrderByField(), page.isAsc());
page.setRecords((List<OperationLog>) new LogWarpper(result).warp());
return super.packForBT(page);
page.setRecords(new LogWarpper(result).wrap());
return new PageInfoBT<>(page);
}
/**
......@@ -66,7 +67,7 @@ public class LogController extends BaseController {
@ResponseBody
public Object detail(@PathVariable Integer id) {
OperationLog operationLog = operationLogService.selectById(id);
Map<String, Object> stringObjectMap = BeanKit.beanToMap(operationLog);
Map<String, Object> stringObjectMap = BeanUtil.beanToMap(operationLog);
return super.warpObject(new LogWarpper(stringObjectMap));
}
......
package com.stylefeng.guns.modular.system.controller;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.google.code.kaptcha.Constants;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.exception.InvalidKaptchaException;
import com.stylefeng.guns.core.log.LogManager;
import com.stylefeng.guns.core.log.factory.LogTaskFactory;
......@@ -10,7 +11,6 @@ import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.shiro.ShiroUser;
import com.stylefeng.guns.core.util.ApiMenuFilter;
import com.stylefeng.guns.core.util.KaptchaUtil;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.service.IMenuService;
import com.stylefeng.guns.modular.system.service.IUserService;
......@@ -24,7 +24,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
import static com.stylefeng.guns.core.support.HttpKit.getIp;
import static cn.stylefeng.roses.core.util.HttpContext.getIp;
/**
* 登录控制器
......
package com.stylefeng.guns.modular.system.controller;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.SqlRunner;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.modular.system.model.LoginLog;
import com.stylefeng.guns.modular.system.service.ILoginLogService;
import com.stylefeng.guns.modular.system.warpper.LogWarpper;
......@@ -51,8 +52,8 @@ public class LoginLogController extends BaseController {
public Object list(@RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) String logName) {
Page<LoginLog> page = new PageFactory<LoginLog>().defaultPage();
List<Map<String, Object>> result = loginLogService.getLoginLogs(page, beginTime, endTime, logName, page.getOrderByField(), page.isAsc());
page.setRecords((List<LoginLog>) new LogWarpper(result).warp());
return super.packForBT(page);
page.setRecords(new LogWarpper(result).wrap());
return new PageInfoBT<>(page);
}
/**
......
package com.stylefeng.guns.modular.system.controller;
import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.Tip;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
......@@ -10,11 +13,8 @@ import com.stylefeng.guns.core.common.constant.dictmap.MenuDict;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.constant.state.MenuStatus;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Menu;
import com.stylefeng.guns.modular.system.service.IMenuService;
import com.stylefeng.guns.modular.system.warpper.MenuWarpper;
......@@ -69,7 +69,7 @@ public class MenuController extends BaseController {
@RequestMapping(value = "/menu_edit/{menuId}")
public String menuEdit(@PathVariable Long menuId, Model model) {
if (ToolUtil.isEmpty(menuId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
Menu menu = this.menuService.selectById(menuId);
......@@ -86,7 +86,7 @@ public class MenuController extends BaseController {
menu.setPcode(String.valueOf(pMenu.getId()));
}
Map<String, Object> menuMap = BeanKit.beanToMap(menu);
Map<String, Object> menuMap = BeanUtil.beanToMap(menu);
menuMap.put("pcodeName", ConstantFactory.me().getMenuNameByCode(temp.getCode()));
model.addAttribute("menu", menuMap);
LogObjectHolder.me().set(menu);
......@@ -100,9 +100,9 @@ public class MenuController extends BaseController {
@RequestMapping(value = "/edit")
@BussinessLog(value = "修改菜单", key = "name", dict = MenuDict.class)
@ResponseBody
public Tip edit(@Valid Menu menu, BindingResult result) {
public ResponseData edit(@Valid Menu menu, BindingResult result) {
if (result.hasErrors()) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
//设置父级菜单编号
menuSetPcode(menu);
......@@ -129,15 +129,15 @@ public class MenuController extends BaseController {
@RequestMapping(value = "/add")
@BussinessLog(value = "菜单新增", key = "name", dict = MenuDict.class)
@ResponseBody
public Tip add(@Valid Menu menu, BindingResult result) {
public ResponseData add(@Valid Menu menu, BindingResult result) {
if (result.hasErrors()) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
//判断是否存在该编号
String existedMenuName = ConstantFactory.me().getMenuNameByCode(menu.getCode());
if (ToolUtil.isNotEmpty(existedMenuName)) {
throw new GunsException(BizExceptionEnum.EXISTED_THE_MENU);
throw new ServiceException(BizExceptionEnum.EXISTED_THE_MENU);
}
//设置父级菜单编号
......@@ -155,9 +155,9 @@ public class MenuController extends BaseController {
@RequestMapping(value = "/remove")
@BussinessLog(value = "删除菜单", key = "menuId", dict = MenuDict.class)
@ResponseBody
public Tip remove(@RequestParam Long menuId) {
public ResponseData remove(@RequestParam Long menuId) {
if (ToolUtil.isEmpty(menuId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
//缓存菜单的名称
......@@ -172,9 +172,9 @@ public class MenuController extends BaseController {
*/
@RequestMapping(value = "/view/{menuId}")
@ResponseBody
public Tip view(@PathVariable Long menuId) {
public ResponseData view(@PathVariable Long menuId) {
if (ToolUtil.isEmpty(menuId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
this.menuService.selectById(menuId);
return SUCCESS_TIP;
......@@ -186,8 +186,7 @@ public class MenuController extends BaseController {
@RequestMapping(value = "/menuTreeList")
@ResponseBody
public List<ZTreeNode> menuTreeList() {
List<ZTreeNode> roleTreeList = this.menuService.menuTreeList();
return roleTreeList;
return this.menuService.menuTreeList();
}
/**
......@@ -209,11 +208,9 @@ public class MenuController extends BaseController {
public List<ZTreeNode> menuTreeListByRoleId(@PathVariable Integer roleId) {
List<Long> menuIds = this.menuService.getMenuIdsByRoleId(roleId);
if (ToolUtil.isEmpty(menuIds)) {
List<ZTreeNode> roleTreeList = this.menuService.menuTreeList();
return roleTreeList;
return this.menuService.menuTreeList();
} else {
List<ZTreeNode> roleTreeListByUserId = this.menuService.menuTreeListByMenuIds(menuIds);
return roleTreeListByUserId;
return this.menuService.menuTreeListByMenuIds(menuIds);
}
}
......@@ -233,7 +230,7 @@ public class MenuController extends BaseController {
//如果编号和父编号一致会导致无限递归
if (menu.getCode().equals(menu.getPcode())) {
throw new GunsException(BizExceptionEnum.MENU_PCODE_COINCIDENCE);
throw new ServiceException(BizExceptionEnum.MENU_PCODE_COINCIDENCE);
}
menu.setLevels(pLevels + 1);
......
package com.stylefeng.guns.modular.system.controller;
import com.stylefeng.guns.core.base.controller.BaseController;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.dictmap.NoticeMap;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Notice;
import com.stylefeng.guns.modular.system.service.INoticeService;
import com.stylefeng.guns.modular.system.warpper.NoticeWrapper;
......@@ -94,7 +94,7 @@ public class NoticeController extends BaseController {
@BussinessLog(value = "新增通知",key = "title",dict = NoticeMap.class)
public Object add(Notice notice) {
if (ToolUtil.isOneEmpty(notice, notice.getTitle(), notice.getContent())) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
notice.setCreater(ShiroKit.getUser().getId());
notice.setCreatetime(new Date());
......@@ -126,7 +126,7 @@ public class NoticeController extends BaseController {
@BussinessLog(value = "修改通知",key = "title",dict = NoticeMap.class)
public Object update(Notice notice) {
if (ToolUtil.isOneEmpty(notice, notice.getId(), notice.getTitle(), notice.getContent())) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
Notice old = this.noticeService.selectById(notice.getId());
old.setTitle(notice.getTitle());
......
package com.stylefeng.guns.modular.system.controller;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.Tip;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.annotion.Permission;
......@@ -10,11 +12,8 @@ import com.stylefeng.guns.core.common.constant.cache.Cache;
import com.stylefeng.guns.core.common.constant.dictmap.RoleDict;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.Role;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.service.IRoleService;
......@@ -74,7 +73,7 @@ public class RoleController extends BaseController {
@RequestMapping(value = "/role_edit/{roleId}")
public String roleEdit(@PathVariable Integer roleId, Model model) {
if (ToolUtil.isEmpty(roleId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
Role role = this.roleService.selectById(roleId);
model.addAttribute(role);
......@@ -91,7 +90,7 @@ public class RoleController extends BaseController {
@RequestMapping(value = "/role_assign/{roleId}")
public String roleAssign(@PathVariable("roleId") Integer roleId, Model model) {
if (ToolUtil.isEmpty(roleId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
model.addAttribute("roleId", roleId);
model.addAttribute("roleName", ConstantFactory.me().getSingleRoleName(roleId));
......@@ -116,9 +115,9 @@ public class RoleController extends BaseController {
@BussinessLog(value = "添加角色", key = "name", dict = RoleDict.class)
@Permission(Const.ADMIN_NAME)
@ResponseBody
public Tip add(@Valid Role role, BindingResult result) {
public ResponseData add(@Valid Role role, BindingResult result) {
if (result.hasErrors()) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
role.setId(null);
this.roleService.insert(role);
......@@ -132,9 +131,9 @@ public class RoleController extends BaseController {
@BussinessLog(value = "修改角色", key = "name", dict = RoleDict.class)
@Permission(Const.ADMIN_NAME)
@ResponseBody
public Tip edit(@Valid Role role, BindingResult result) {
public ResponseData edit(@Valid Role role, BindingResult result) {
if (result.hasErrors()) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
this.roleService.updateById(role);
......@@ -150,14 +149,14 @@ public class RoleController extends BaseController {
@BussinessLog(value = "删除角色", key = "roleId", dict = RoleDict.class)
@Permission(Const.ADMIN_NAME)
@ResponseBody
public Tip remove(@RequestParam Integer roleId) {
public ResponseData remove(@RequestParam Integer roleId) {
if (ToolUtil.isEmpty(roleId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
//不能删除超级管理员角色
if (roleId.equals(Const.ADMIN_ROLE_ID)) {
throw new GunsException(BizExceptionEnum.CANT_DELETE_ADMIN);
throw new ServiceException(BizExceptionEnum.CANT_DELETE_ADMIN);
}
//缓存被删除的角色名称
......@@ -175,9 +174,9 @@ public class RoleController extends BaseController {
*/
@RequestMapping(value = "/view/{roleId}")
@ResponseBody
public Tip view(@PathVariable Integer roleId) {
public ResponseData view(@PathVariable Integer roleId) {
if (ToolUtil.isEmpty(roleId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
this.roleService.selectById(roleId);
return SUCCESS_TIP;
......@@ -190,9 +189,9 @@ public class RoleController extends BaseController {
@BussinessLog(value = "配置权限", key = "roleId,ids", dict = RoleDict.class)
@Permission(Const.ADMIN_NAME)
@ResponseBody
public Tip setAuthority(@RequestParam("roleId") Integer roleId, @RequestParam("ids") String ids) {
public ResponseData setAuthority(@RequestParam("roleId") Integer roleId, @RequestParam("ids") String ids) {
if (ToolUtil.isOneEmpty(roleId)) {
throw new GunsException(BizExceptionEnum.REQUEST_NULL);
throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
}
this.roleService.setAuthority(roleId, ids);
return SUCCESS_TIP;
......@@ -218,12 +217,10 @@ public class RoleController extends BaseController {
User theUser = this.userService.selectById(userId);
String roleid = theUser.getRoleid();
if (ToolUtil.isEmpty(roleid)) {
List<ZTreeNode> roleTreeList = this.roleService.roleTreeList();
return roleTreeList;
return this.roleService.roleTreeList();
} else {
String[] strArray = Convert.toStrArray(",", roleid);
List<ZTreeNode> roleTreeListByUserId = this.roleService.roleTreeListByRoleId(strArray);
return roleTreeListByUserId;
String[] strArray = roleid.split(",");
return this.roleService.roleTreeListByRoleId(strArray);
}
}
......
package com.stylefeng.guns.modular.system.dao;
import cn.stylefeng.roses.core.datascope.DataScope;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.modular.system.model.User;
import org.apache.ibatis.annotations.Param;
......
package com.stylefeng.guns.modular.system.factory;
import com.stylefeng.guns.core.util.ToolUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.transfer.UserDto;
import org.springframework.beans.BeanUtils;
......
package com.stylefeng.guns.modular.system.service;
import cn.stylefeng.roses.core.datascope.DataScope;
import com.baomidou.mybatisplus.service.IService;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.modular.system.model.User;
import org.apache.ibatis.annotations.Param;
......
package com.stylefeng.guns.modular.system.service.impl;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.modular.system.dao.DictMapper;
import com.stylefeng.guns.modular.system.model.Dict;
import com.stylefeng.guns.modular.system.service.IDictService;
......@@ -29,7 +29,7 @@ public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements ID
//判断有没有该字典
List<Dict> dicts = dictMapper.selectList(new EntityWrapper<Dict>().eq("code", dictCode).and().eq("pid", 0));
if (dicts != null && dicts.size() > 0) {
throw new GunsException(BizExceptionEnum.DICT_EXISTED);
throw new ServiceException(BizExceptionEnum.DICT_EXISTED);
}
//解析dictValues
......@@ -57,7 +57,7 @@ public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements ID
try {
itemDict.setNum(Integer.valueOf(num));
} catch (NumberFormatException e) {
throw new GunsException(BizExceptionEnum.DICT_MUST_BE_NUMBER);
throw new ServiceException(BizExceptionEnum.DICT_MUST_BE_NUMBER);
}
this.dictMapper.insert(itemDict);
}
......
package com.stylefeng.guns.modular.system.service.impl;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.modular.system.dao.RelationMapper;
import com.stylefeng.guns.modular.system.dao.RoleMapper;
import com.stylefeng.guns.modular.system.model.Relation;
......@@ -32,7 +32,7 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IR
this.roleMapper.deleteRolesById(roleId);
// 添加新的权限
for (Long id : Convert.toLongArray(true, Convert.toStrArray(",", ids))) {
for (Long id : Convert.toLongArray(ids.split(","))) {
Relation relation = new Relation();
relation.setRoleid(roleId);
relation.setMenuid(id);
......
package com.stylefeng.guns.modular.system.service.impl;
import cn.stylefeng.roses.core.datascope.DataScope;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.service.IUserService;
......
package com.stylefeng.guns.modular.system.warpper;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import com.stylefeng.guns.core.util.ToolUtil;
import java.util.List;
import java.util.Map;
/**
......@@ -12,15 +15,26 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年4月25日 18:10:31
*/
public class DeptWarpper extends BaseControllerWarpper {
public class DeptWarpper extends BaseControllerWrapper {
public DeptWarpper(Object list) {
super(list);
public DeptWarpper(Map<String, Object> single) {
super(single);
}
@Override
public void warpTheMap(Map<String, Object> map) {
public DeptWarpper(List<Map<String, Object>> multi) {
super(multi);
}
public DeptWarpper(Page<Map<String, Object>> page) {
super(page);
}
public DeptWarpper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
protected void wrapTheMap(Map<String, Object> map) {
Integer pid = (Integer) map.get("pid");
if (ToolUtil.isEmpty(pid) || pid.equals(0)) {
......@@ -29,5 +43,4 @@ public class DeptWarpper extends BaseControllerWarpper {
map.put("pName", ConstantFactory.me().getDeptName(pid));
}
}
}
package com.stylefeng.guns.modular.system.warpper;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.modular.system.model.Dict;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import com.stylefeng.guns.core.util.ToolUtil;
import java.util.List;
import java.util.Map;
......@@ -14,23 +16,34 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年4月25日 18:10:31
*/
public class DictWarpper extends BaseControllerWarpper {
public class DictWarpper extends BaseControllerWrapper {
public DictWarpper(Object list) {
super(list);
public DictWarpper(Map<String, Object> single) {
super(single);
}
public DictWarpper(List<Map<String, Object>> multi) {
super(multi);
}
public DictWarpper(Page<Map<String, Object>> page) {
super(page);
}
public DictWarpper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
public void warpTheMap(Map<String, Object> map) {
protected void wrapTheMap(Map<String, Object> map) {
StringBuffer detail = new StringBuffer();
Integer id = Integer.valueOf(map.get("id").toString());
List<Dict> dicts = ConstantFactory.me().findInDict(id);
if(dicts != null){
if (dicts != null) {
for (Dict dict : dicts) {
detail.append(dict.getCode() + ":" +dict.getName() + ",");
detail.append(dict.getCode() + ":" + dict.getName() + ",");
}
map.put("detail", ToolUtil.removeSuffix(detail.toString(),","));
map.put("detail", StrUtil.removeSuffix(detail.toString(), ","));
}
}
}
package com.stylefeng.guns.modular.system.warpper;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import com.stylefeng.guns.core.util.Contrast;
import com.stylefeng.guns.core.util.ToolUtil;
import java.util.List;
import java.util.Map;
/**
......@@ -13,14 +16,26 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年4月5日22:56:24
*/
public class LogWarpper extends BaseControllerWarpper {
public class LogWarpper extends BaseControllerWrapper {
public LogWarpper(Object list) {
super(list);
public LogWarpper(Map<String, Object> single) {
super(single);
}
public LogWarpper(List<Map<String, Object>> multi) {
super(multi);
}
public LogWarpper(Page<Map<String, Object>> page) {
super(page);
}
public LogWarpper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
public void warpTheMap(Map<String, Object> map) {
protected void wrapTheMap(Map<String, Object> map) {
String message = (String) map.get("message");
Integer userid = (Integer) map.get("userid");
......@@ -35,10 +50,9 @@ public class LogWarpper extends BaseControllerWarpper {
//如果信息中包含分割符号;;; 则分割字符串返给前台
if (ToolUtil.isNotEmpty(message) && message.indexOf(Contrast.separator) != -1) {
String[] msgs = message.split(Contrast.separator);
map.put("regularMessage",msgs);
}else{
map.put("regularMessage",message);
map.put("regularMessage", msgs);
} else {
map.put("regularMessage", message);
}
}
}
package com.stylefeng.guns.modular.system.warpper;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.kernel.model.enums.YesOrNotEnum;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.constant.IsMenu;
import java.util.List;
import java.util.Map;
......@@ -13,16 +15,28 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年2月19日15:07:29
*/
public class MenuWarpper extends BaseControllerWarpper {
public class MenuWarpper extends BaseControllerWrapper {
public MenuWarpper(List<Map<String, Object>> list) {
super(list);
public MenuWarpper(Map<String, Object> single) {
super(single);
}
public MenuWarpper(List<Map<String, Object>> multi) {
super(multi);
}
public MenuWarpper(Page<Map<String, Object>> page) {
super(page);
}
public MenuWarpper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
public void warpTheMap(Map<String, Object> map) {
protected void wrapTheMap(Map<String, Object> map) {
map.put("statusName", ConstantFactory.me().getMenuStatusName((Integer) map.get("status")));
map.put("isMenuName", IsMenu.valueOf((Integer) map.get("ismenu")));
map.put("isMenuName", YesOrNotEnum.valueOf((Integer) map.get("ismenu")));
}
}
package com.stylefeng.guns.modular.system.warpper;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import java.util.List;
import java.util.Map;
/**
......@@ -11,16 +14,27 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年4月25日 18:10:31
*/
public class NoticeWrapper extends BaseControllerWarpper {
public class NoticeWrapper extends BaseControllerWrapper {
public NoticeWrapper(Object list) {
super(list);
public NoticeWrapper(Map<String, Object> single) {
super(single);
}
public NoticeWrapper(List<Map<String, Object>> multi) {
super(multi);
}
public NoticeWrapper(Page<Map<String, Object>> page) {
super(page);
}
public NoticeWrapper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
public void warpTheMap(Map<String, Object> map) {
protected void wrapTheMap(Map<String, Object> map) {
Integer creater = (Integer) map.get("creater");
map.put("createrName", ConstantFactory.me().getUserNameById(creater));
}
}
package com.stylefeng.guns.modular.system.warpper;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import java.util.List;
import java.util.Map;
......@@ -12,14 +14,26 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年2月19日10:59:02
*/
public class RoleWarpper extends BaseControllerWarpper {
public class RoleWarpper extends BaseControllerWrapper {
public RoleWarpper(List<Map<String, Object>> list) {
super(list);
public RoleWarpper(Map<String, Object> single) {
super(single);
}
public RoleWarpper(List<Map<String, Object>> multi) {
super(multi);
}
public RoleWarpper(Page<Map<String, Object>> page) {
super(page);
}
public RoleWarpper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
public void warpTheMap(Map<String, Object> map) {
protected void wrapTheMap(Map<String, Object> map) {
map.put("pName", ConstantFactory.me().getSingleRoleName((Integer) map.get("pid")));
map.put("deptName", ConstantFactory.me().getDeptName((Integer) map.get("deptid")));
}
......
package com.stylefeng.guns.modular.system.warpper;
import cn.stylefeng.roses.core.base.warpper.BaseControllerWrapper;
import cn.stylefeng.roses.kernel.model.page.PageResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import java.util.List;
import java.util.Map;
......@@ -12,14 +14,26 @@ import java.util.Map;
* @author fengshuonan
* @date 2017年2月13日 下午10:47:03
*/
public class UserWarpper extends BaseControllerWarpper {
public class UserWarpper extends BaseControllerWrapper {
public UserWarpper(List<Map<String, Object>> list) {
super(list);
public UserWarpper(Map<String, Object> single) {
super(single);
}
public UserWarpper(List<Map<String, Object>> multi) {
super(multi);
}
public UserWarpper(Page<Map<String, Object>> page) {
super(page);
}
public UserWarpper(PageResult<Map<String, Object>> pageResult) {
super(pageResult);
}
@Override
public void warpTheMap(Map<String, Object> map) {
protected void wrapTheMap(Map<String, Object> map) {
map.put("sexName", ConstantFactory.me().getSexName((Integer) map.get("sex")));
map.put("roleName", ConstantFactory.me().getRoleName((String) map.get("roleid")));
map.put("deptName", ConstantFactory.me().getDeptName((Integer) map.get("deptid")));
......
package com.stylefeng.guns.multi.service.impl;
import cn.stylefeng.roses.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.core.common.constant.DatasourceEnum;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.multi.entity.Test;
import com.stylefeng.guns.multi.mapper.TestMapper;
import com.stylefeng.guns.multi.service.TestService;
......
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.stylefeng</groupId>
<artifactId>guns-parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>guns-core</artifactId>
<packaging>jar</packaging>
<name>guns-core</name>
<url>http://maven.apache.org</url>
<dependencies>
<!--通用依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatisplus-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
<!--aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<scope>provided</scope>
</dependency>
<!--二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<scope>provided</scope>
</dependency>
<!--缓存-->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
</build>
</project>
package com.stylefeng.guns.core;
/**
* 此类用来获取core模块的包路径
*
* @author fengshuonan
* @Date 2017/12/5 下午12:44
*/
public class CoreFlag {
}
\ No newline at end of file
package com.stylefeng.guns.core.aop;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.exception.GunsExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* 全局的的异常拦截器(拦截所有的控制器)(带有@RequestMapping注解的方法上都会拦截)
*
* @author fengshuonan
* @date 2016年11月12日 下午3:19:56
*/
public class BaseControllerExceptionHandler {
private Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 拦截业务异常
*/
@ExceptionHandler(GunsException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFount(GunsException e) {
log.error("业务异常:", e);
return new ErrorTip(e.getCode(), e.getMessage());
}
/**
* 拦截未知的运行时异常
*/
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorTip notFount(RuntimeException e) {
log.error("运行时异常:", e);
return new ErrorTip(GunsExceptionEnum.SERVER_ERROR.getCode(), GunsExceptionEnum.SERVER_ERROR.getMessage());
}
}
package com.stylefeng.guns.core.base.controller;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.base.warpper.BaseControllerWarpper;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.core.util.FileUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
public class BaseController {
protected static String SUCCESS = "SUCCESS";
protected static String ERROR = "ERROR";
protected static String REDIRECT = "redirect:";
protected static String FORWARD = "forward:";
protected static SuccessTip SUCCESS_TIP = new SuccessTip();
protected HttpServletRequest getHttpServletRequest() {
return HttpKit.getRequest();
}
protected HttpServletResponse getHttpServletResponse() {
return HttpKit.getResponse();
}
protected HttpSession getSession() {
return HttpKit.getRequest().getSession();
}
protected HttpSession getSession(Boolean flag) {
return HttpKit.getRequest().getSession(flag);
}
protected String getPara(String name) {
return HttpKit.getRequest().getParameter(name);
}
protected void setAttr(String name, Object value) {
HttpKit.getRequest().setAttribute(name, value);
}
protected Integer getSystemInvokCount() {
return (Integer) this.getHttpServletRequest().getServletContext().getAttribute("systemCount");
}
/**
* 把service层的分页信息,封装为bootstrap table通用的分页封装
*/
protected <T> PageInfoBT<T> packForBT(Page<T> page) {
return new PageInfoBT<T>(page);
}
/**
* 包装一个list,让list增加额外属性
*/
protected Object warpObject(BaseControllerWarpper warpper) {
return warpper.warp();
}
/**
* 删除cookie
*/
protected void deleteCookieByName(String cookieName) {
Cookie[] cookies = this.getHttpServletRequest().getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
Cookie temp = new Cookie(cookie.getName(), "");
temp.setMaxAge(0);
this.getHttpServletResponse().addCookie(temp);
}
}
}
/**
* 删除所有cookie
*/
protected void deleteAllCookie() {
Cookie[] cookies = this.getHttpServletRequest().getCookies();
for (Cookie cookie : cookies) {
Cookie temp = new Cookie(cookie.getName(), "");
temp.setMaxAge(0);
this.getHttpServletResponse().addCookie(temp);
}
}
/**
* 返回前台文件流
*
* @author fengshuonan
* @date 2017年2月28日 下午2:53:19
*/
protected ResponseEntity<byte[]> renderFile(String fileName, String filePath) {
byte[] bytes = FileUtil.toByteArray(filePath);
return renderFile(fileName, bytes);
}
/**
* 返回前台文件流
*
* @author fengshuonan
* @date 2017年2月28日 下午2:53:19
*/
protected ResponseEntity<byte[]> renderFile(String fileName, byte[] fileBytes) {
String dfileName = null;
try {
dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", dfileName);
return new ResponseEntity<byte[]>(fileBytes, headers, HttpStatus.CREATED);
}
}
package com.stylefeng.guns.core.base.tips;
/**
* 返回给前台的错误提示
*
* @author fengshuonan
* @date 2016年11月12日 下午5:05:22
*/
public class ErrorTip extends Tip {
public ErrorTip(int code, String message) {
super();
this.code = code;
this.message = message;
}
}
package com.stylefeng.guns.core.base.tips;
/**
* 返回给前台的成功提示
*
* @author fengshuonan
* @date 2016年11月12日 下午5:05:22
*/
public class SuccessTip extends Tip {
public SuccessTip(){
super.code = 200;
super.message = "操作成功";
}
}
package com.stylefeng.guns.core.base.tips;
/**
* 返回给前台的提示(最终转化为json形式)
*
* @author fengshuonan
* @Date 2017年1月11日 下午11:58:00
*/
public abstract class Tip {
protected int code;
protected String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.stylefeng.guns.core.base.warpper;
import java.util.List;
import java.util.Map;
/**
* 控制器查询结果的包装类基类
*
* @author fengshuonan
* @date 2017年2月13日 下午10:49:36
*/
public abstract class BaseControllerWarpper {
public Object obj = null;
public BaseControllerWarpper(Object obj) {
this.obj = obj;
}
@SuppressWarnings("unchecked")
public Object warp() {
if (this.obj instanceof List) {
List<Map<String, Object>> list = (List<Map<String, Object>>) this.obj;
for (Map<String, Object> map : list) {
warpTheMap(map);
}
return list;
} else if (this.obj instanceof Map) {
Map<String, Object> map = (Map<String, Object>) this.obj;
warpTheMap(map);
return map;
} else {
return this.obj;
}
}
protected abstract void warpTheMap(Map<String, Object> map);
}
package com.stylefeng.guns.core.config;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* fastjson配置类
*
* @author fengshuonan
* @date 2017-05-23 22:56
*/
@Configuration("defaultFastjsonConfig")
@ConditionalOnClass(com.alibaba.fastjson.JSON.class)
@ConditionalOnMissingBean(FastJsonHttpMessageConverter.class)
@ConditionalOnWebApplication
public class DefaultFastjsonConfig {
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
converter.setFastJsonConfig(fastjsonConfig());
converter.setSupportedMediaTypes(getSupportedMediaType());
return converter;
}
/**
* fastjson的配置
*/
public FastJsonConfig fastjsonConfig() {
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteEnumUsingToString
);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
ValueFilter valueFilter = new ValueFilter() {
public Object process(Object o, String s, Object o1) {
if (null == o1) {
o1 = "";
}
return o1;
}
};
fastJsonConfig.setCharset(Charset.forName("utf-8"));
fastJsonConfig.setSerializeFilters(valueFilter);
//解决Long转json精度丢失的问题
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
serializeConfig.put(Long.class, ToStringSerializer.instance);
serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
fastJsonConfig.setSerializeConfig(serializeConfig);
return fastJsonConfig;
}
/**
* 支持的mediaType类型
*/
public List<MediaType> getSupportedMediaType() {
ArrayList<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
return mediaTypes;
}
}
package com.stylefeng.guns.core.config;
import com.stylefeng.guns.core.mutidatasource.aop.MultiSourceExAop;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 多数据源配置
*
* @author stylefeng
* @Date 2017/5/20 21:58
*/
@Configuration
@ConditionalOnProperty(prefix = "guns", name = "muti-datasource-open", havingValue = "true")
public class DefaultMultiConfig {
@Bean
public MultiSourceExAop multiSourceExAop() {
return new MultiSourceExAop();
}
}
package com.stylefeng.guns.core.config;
import com.stylefeng.guns.core.config.properties.DruidProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 默认的配置
*
* @author fengshuonan
* @date 2018-01-07 12:33
*/
@Configuration
@PropertySource("classpath:/default-config.properties")
public class DefaultProperties {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidProperties druidProperties() {
return new DruidProperties();
}
}
package com.stylefeng.guns.core.config;
import com.stylefeng.guns.core.base.controller.GunsErrorView;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.exception.GunsExceptionEnum;
import com.stylefeng.guns.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.regex.Pattern;
@Configuration
public class DefaultWebConfig extends WebMvcConfigurationSupport {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@Bean("error")
public GunsErrorView error() {
return new GunsErrorView();
}
@PostConstruct
public void addConversionConfig() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
genericConversionService.addConverter(new StringToDateConverter());
}
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String dateString) {
String patternDate = "\\d{4}-\\d{1,2}-\\d{1,2}";
String patternTimeMinutes = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}";
String patternTimeSeconds = "\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}";
boolean dateFlag = Pattern.matches(patternDate, dateString);
boolean timeMinutesFlag = Pattern.matches(patternTimeMinutes, dateString);
boolean timeSecondsFlag = Pattern.matches(patternTimeSeconds, dateString);
if (dateFlag) {
return DateUtil.parseDate(dateString);
} else if (timeMinutesFlag) {
return DateUtil.parseTimeMinutes(dateString);
} else if (timeSecondsFlag) {
return DateUtil.parseTime(dateString);
} else {
throw new GunsException(GunsExceptionEnum.INVLIDE_DATE_STRING);
}
}
}
}
package com.stylefeng.guns.core.config.properties;
import com.alibaba.druid.pool.DruidDataSource;
import java.sql.SQLException;
/**
* <p>数据库数据源配置</p>
* <p>说明:这个类中包含了许多默认配置,若这些配置符合您的情况,您可以不用管,若不符合,建议不要修改本类,建议直接在"application.yml"中配置即可</p>
* @author stylefeng
* @date 2017-05-21 11:18
*/
public class DruidProperties {
private String url = "jdbc:mysql://127.0.0.1:3306/guns?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
private String username = "root";
private String password = "root";
private String driverClassName = "com.mysql.cj.jdbc.Driver";
private Integer initialSize = 2;
private Integer minIdle = 1;
private Integer maxActive = 20;
private Integer maxWait = 60000;
private Integer timeBetweenEvictionRunsMillis = 60000;
private Integer minEvictableIdleTimeMillis = 300000;
private String validationQuery = "SELECT 'x'";
private Boolean testWhileIdle = true;
private Boolean testOnBorrow = false;
private Boolean testOnReturn = false;
private Boolean poolPreparedStatements = true;
private Integer maxPoolPreparedStatementPerConnectionSize = 20;
private String filters = "stat";
public void config(DruidDataSource dataSource) {
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setInitialSize(initialSize); //定义初始连接数
dataSource.setMinIdle(minIdle); //最小空闲
dataSource.setMaxActive(maxActive); //定义最大连接数
dataSource.setMaxWait(maxWait); //最长等待时间
// 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// 配置一个连接在池中最小生存的时间,单位是毫秒
dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
// 打开PSCache,并且指定每个连接上PSCache的大小
dataSource.setPoolPreparedStatements(poolPreparedStatements);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
dataSource.setFilters(filters);
} catch (SQLException e) {
e.printStackTrace();
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public Integer getInitialSize() {
return initialSize;
}
public void setInitialSize(Integer initialSize) {
this.initialSize = initialSize;
}
public Integer getMinIdle() {
return minIdle;
}
public void setMinIdle(Integer minIdle) {
this.minIdle = minIdle;
}
public Integer getMaxActive() {
return maxActive;
}
public void setMaxActive(Integer maxActive) {
this.maxActive = maxActive;
}
public Integer getMaxWait() {
return maxWait;
}
public void setMaxWait(Integer maxWait) {
this.maxWait = maxWait;
}
public Integer getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public Integer getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}
package com.stylefeng.guns.core.config.properties;
import com.alibaba.druid.pool.DruidDataSource;
/**
* 默认多数据源配置
*
* @author fengshuonan
* @date 2017-08-16 10:02
*/
public class MutiDataSourceProperties {
private String url = "jdbc:mysql://127.0.0.1:3306/biz?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
private String username = "root";
private String password = "root";
private String driverClassName = "com.mysql.cj.jdbc.Driver";
private String validationQuery = "SELECT 'x'";
private String[] dataSourceNames = {"dataSourceGuns", "dataSourceBiz"};
public void config(DruidDataSource dataSource) {
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClassName);
dataSource.setValidationQuery(validationQuery);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public String[] getDataSourceNames() {
return dataSourceNames;
}
public void setDataSourceNames(String[] dataSourceNames) {
this.dataSourceNames = dataSourceNames;
}
}
package com.stylefeng.guns.core.constant;
/**
* 是否是菜单的枚举
*
* @author fengshuonan
* @date 2017年6月1日22:50:11
*/
public enum IsMenu {
YES(1, "是"),
NO(0, "不是"); //不是菜单的是按钮
int code;
String message;
IsMenu(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static String valueOf(Integer status) {
if (status == null) {
return "";
} else {
for (IsMenu s : IsMenu.values()) {
if (s.getCode() == status) {
return s.getMessage();
}
}
return "";
}
}
}
package com.stylefeng.guns.core.datascope;
import java.util.List;
/**
* 数据范围
*
* @author fengshuonan
* @date 2017-07-23 22:19
*/
public class DataScope {
/**
* 限制范围的字段名称
*/
private String scopeName = "deptid";
/**
* 具体的数据范围
*/
private List<Integer> deptIds;
public DataScope() {
}
public DataScope(List<Integer> deptIds) {
this.deptIds = deptIds;
}
public DataScope(String scopeName, List<Integer> deptIds) {
this.scopeName = scopeName;
this.deptIds = deptIds;
}
public List<Integer> getDeptIds() {
return deptIds;
}
public void setDeptIds(List<Integer> deptIds) {
this.deptIds = deptIds;
}
public String getScopeName() {
return scopeName;
}
public void setScopeName(String scopeName) {
this.scopeName = scopeName;
}
}
package com.stylefeng.guns.core.datascope;
import com.baomidou.mybatisplus.toolkit.PluginUtils;
import com.stylefeng.guns.core.support.CollectionKit;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import java.sql.Connection;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* 数据范围的拦截器
*
* @author fengshuonan
* @date 2017-07-23 21:26
*/
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class DataScopeInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
return invocation.proceed();
}
BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
String originalSql = boundSql.getSql();
Object parameterObject = boundSql.getParameterObject();
//查找参数中包含DataScope类型的参数
DataScope dataScope = findDataScopeObject(parameterObject);
if (dataScope == null) {
return invocation.proceed();
} else {
String scopeName = dataScope.getScopeName();
List<Integer> deptIds = dataScope.getDeptIds();
String join = CollectionKit.join(deptIds, ",");
originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
return invocation.proceed();
}
}
/**
* 查找参数是否包括DataScope对象
*/
public DataScope findDataScopeObject(Object parameterObj) {
if (parameterObj instanceof DataScope) {
return (DataScope) parameterObj;
} else if (parameterObj instanceof Map) {
for (Object val : ((Map<?, ?>) parameterObj).values()) {
if (val instanceof DataScope) {
return (DataScope) val;
}
}
}
return null;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}
package com.stylefeng.guns.core.db;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.stylefeng.guns.core.util.SpringContextHolder;
import java.util.HashMap;
import java.util.List;
/**
* <p>
* 便捷数据库操作类
* <p>
* <p>
* 本类的使用情景:
* <p>
* 1.单纯想创建现有的Mapper
* <p>例如:
* Db.getMapper(UserLoginMapper.class).selectById("14779707158513204");<br>
* <p>
*
* @author fengshuonan
* @date 2017年2月22日 下午8:07:17
*/
@SuppressWarnings("all")
public class Db<T> {
/**
* 每个Db类,包装一个Mapper接口,这个clazz就是接口的类类型,例如UserMapper.class
*/
private Class<T> clazz;
/**
* Mapper的父类接口
*/
private BaseMapper<?> baseMapper;
/**
* 私有构造方法,不允许自己创建
*/
private Db(Class clazz) {
this.clazz = clazz;
this.baseMapper = (BaseMapper<?>) SpringContextHolder.getBean(clazz);
}
/**
* <p>
* 创建包含指定mapper的Db工具类,使用本类的第一种用法
*
* @param clazz mapper的类类型
* @date 2017年2月22日 下午10:09:31
*/
public static <T> Db<T> create(Class<T> clazz) {
return new Db<T>(clazz);
}
/**
* <p>
* 获取一个mapper的快捷方法
*
* @param clazz mapper类的类对象
* @date 2017年2月22日 下午10:31:35
*/
public BaseMapper<?> getMapper() {
return this.baseMapper;
}
/**
* <p>
* 获取一个mapper的快捷方法
*
* @param clazz mapper类的类对象
* @date 2017年2月22日 下午10:31:35
*/
public static <T> T getMapper(Class<T> clazz) {
return SpringContextHolder.getBean(clazz);
}
/**
* 通过一个条件获取数据库中的一条记录(会返回null)
*
* @date 2017年2月22日 下午10:45:51
*/
public <E> E selectOneByCon(String condition, Object value) {
List<?> results = selectOneByConList(condition, value);
if (results != null && results.size() > 0) {
return (E) results.get(0);
} else {
return null;
}
}
/**
* 通过一个条件获取一堆记录(会返回null)
*
* @date 2017年2月22日 下午10:45:51
*/
public <E> List<E> selectOneByConList(String condition, Object value) {
HashMap<String, Object> conditionMap = new HashMap<String, Object>();
conditionMap.put(condition, value);
List<E> results = (List<E>) this.baseMapper.selectByMap(conditionMap);
if (results == null || results.size() == 0) {
return null;
} else {
return results;
}
}
}
package com.stylefeng.guns.core.exception;
/**
* 封装guns的异常
*
* @author fengshuonan
* @Date 2017/12/28 下午10:32
*/
public class GunsException extends RuntimeException {
private Integer code;
private String message;
public GunsException(ServiceExceptionEnum serviceExceptionEnum) {
this.code = serviceExceptionEnum.getCode();
this.message = serviceExceptionEnum.getMessage();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.stylefeng.guns.core.exception;
/**
* Guns异常枚举
*
* @author fengshuonan
* @Date 2017/12/28 下午10:33
*/
public enum GunsExceptionEnum implements ServiceExceptionEnum {
/**
* 其他
*/
INVLIDE_DATE_STRING(400, "输入日期格式不对"),
/**
* 其他
*/
WRITE_ERROR(500, "渲染界面错误"),
/**
* 文件上传
*/
FILE_READING_ERROR(400, "FILE_READING_ERROR!"),
FILE_NOT_FOUND(400, "FILE_NOT_FOUND!"),
/**
* 错误的请求
*/
REQUEST_NULL(400, "请求有错误"),
SERVER_ERROR(500, "服务器异常");
GunsExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
private Integer code;
private String message;
@Override
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.stylefeng.guns.core.exception;
/**
* 抽象接口
*
* @author fengshuonan
* @date 2017-12-28-下午10:27
*/
public interface ServiceExceptionEnum {
/**
* 获取异常编码
*/
Integer getCode();
/**
* 获取异常信息
*/
String getMessage();
}
package com.stylefeng.guns.core.mutidatasource;
/**
* datasource的上下文
*
* @author fengshuonan
* @date 2017年3月5日 上午9:10:58
*/
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
/**
* 设置数据源类型
*
* @param dataSourceType 数据库类型
*/
public static void setDataSourceType(String dataSourceType) {
contextHolder.set(dataSourceType);
}
/**
* 获取数据源类型
*/
public static String getDataSourceType() {
return contextHolder.get();
}
/**
* 清除数据源类型
*/
public static void clearDataSourceType() {
contextHolder.remove();
}
}
package com.stylefeng.guns.core.mutidatasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源
*
* @author fengshuonan
* @date 2017年3月5日 上午9:11:49
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSourceType();
}
}
package com.stylefeng.guns.core.mutidatasource.annotion;
import java.lang.annotation.*;
/**
*
* 多数据源标识
*
* @author fengshuonan
* @date 2017年3月5日 上午9:44:24
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface DataSource {
String name() default "";
}
package com.stylefeng.guns.core.mutidatasource.aop;
import com.stylefeng.guns.core.mutidatasource.DataSourceContextHolder;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.core.config.properties.MutiDataSourceProperties;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import java.lang.reflect.Method;
/**
* 多数据源切换的aop
*
* @author fengshuonan
* @date 2017年3月5日 上午10:22:16
*/
@Aspect
public class MultiSourceExAop implements Ordered {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
MutiDataSourceProperties mutiDataSourceProperties;
@Pointcut(value = "@annotation(com.stylefeng.guns.core.mutidatasource.annotion.DataSource)")
private void cut() {
}
@Around("cut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
Signature signature = point.getSignature();
MethodSignature methodSignature = null;
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只能用于方法");
}
methodSignature = (MethodSignature) signature;
Object target = point.getTarget();
Method currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
DataSource datasource = currentMethod.getAnnotation(DataSource.class);
if (datasource != null) {
DataSourceContextHolder.setDataSourceType(datasource.name());
log.debug("设置数据源为:" + datasource.name());
} else {
DataSourceContextHolder.setDataSourceType(mutiDataSourceProperties.getDataSourceNames()[0]);
log.debug("设置数据源为:dataSourceCurrent");
}
try {
return point.proceed();
} finally {
log.debug("清空数据源信息!");
DataSourceContextHolder.clearDataSourceType();
}
}
/**
* aop的顺序要早于spring的事务
*/
@Override
public int getOrder() {
return 1;
}
}
package com.stylefeng.guns.core.support;
import java.util.HashMap;
import java.util.Map;
/**
* 基本变量类型的枚举
*
* @author xiaoleilu
*/
public enum BasicType {
BYTE, SHORT, INT, INTEGER, LONG, DOUBLE, FLOAT, BOOLEAN, CHAR, CHARACTER, STRING;
/**
* 原始类型为Key,包装类型为Value,例如: int.class -> Integer.class.
*/
public static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>(8);
/**
* 包装类型为Key,原始类型为Value,例如: Integer.class -> int.class.
*/
public static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>(8);
static {
wrapperPrimitiveMap.put(Boolean.class, boolean.class);
wrapperPrimitiveMap.put(Byte.class, byte.class);
wrapperPrimitiveMap.put(Character.class, char.class);
wrapperPrimitiveMap.put(Double.class, double.class);
wrapperPrimitiveMap.put(Float.class, float.class);
wrapperPrimitiveMap.put(Integer.class, int.class);
wrapperPrimitiveMap.put(Long.class, long.class);
wrapperPrimitiveMap.put(Short.class, short.class);
for (Map.Entry<Class<?>, Class<?>> entry : wrapperPrimitiveMap.entrySet()) {
primitiveWrapperMap.put(entry.getValue(), entry.getKey());
}
}
}
package com.stylefeng.guns.core.support;
import com.stylefeng.guns.core.support.exception.ToolBoxException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* 类工具类
* 1、扫描指定包下的所有类<br>
* 参考 http://www.oschina.net/code/snippet_234657_22722
* @author seaside_hi, xiaoleilu, chill
*
*/
public class ClassKit {
private ClassKit() {
// 静态类不可实例化
}
/**
* 是否为标准的类<br>
* 这个类必须:<br>
* 1、非接口 2、非抽象类 3、非Enum枚举 4、非数组 5、非注解 6、非原始类型(int, long等)
*
* @param clazz 类
* @return 是否为标准类
*/
public static boolean isNormalClass(Class<?> clazz) {
return null != clazz && false == clazz.isInterface() && false == isAbstract(clazz) && false == clazz.isEnum() && false == clazz.isArray() && false == clazz.isAnnotation() && false == clazz
.isSynthetic() && false == clazz.isPrimitive();
}
/**
* 是否为抽象类
*
* @param clazz 类
* @return 是否为抽象类
*/
public static boolean isAbstract(Class<?> clazz) {
return Modifier.isAbstract(clazz.getModifiers());
}
/**
* 实例化对象
*
* @param clazz 类名
* @return 对象
*/
@SuppressWarnings("unchecked")
public static <T> T newInstance(String clazz) {
if (null == clazz)
return null;
try {
return (T) Class.forName(clazz).newInstance();
} catch (Exception e) {
throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
}
}
/**
* 实例化对象
*
* @param clazz 类
* @return 对象
*/
public static <T> T newInstance(Class<T> clazz) {
if (null == clazz)
return null;
try {
return (T) clazz.newInstance();
} catch (Exception e) {
throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
}
}
/**
* 实例化对象
*
* @param clazz 类
* @return 对象
*/
public static <T> T newInstance(Class<T> clazz, Object... params) {
if (null == clazz)
return null;
if (CollectionKit.isEmpty(params)) {
return newInstance(clazz);
}
try {
return clazz.getDeclaredConstructor(getClasses(params)).newInstance(params);
} catch (Exception e) {
throw new ToolBoxException(StrKit.format("Instance class [{}] error!", clazz), e);
}
}
/**
* 获得对象数组的类数组
* @param objects 对象数组
* @return 类数组
*/
public static Class<?>[] getClasses(Object... objects){
Class<?>[] classes = new Class<?>[objects.length];
for (int i = 0; i < objects.length; i++) {
classes[i] = objects[i].getClass();
}
return classes;
}
/**
* 检查目标类是否可以从原类转化<br>
* 转化包括:<br>
* 1、原类是对象,目标类型是原类型实现的接口<br>
* 2、目标类型是原类型的父类<br>
* 3、两者是原始类型或者包装类型(相互转换)
*
* @param targetType 目标类型
* @param sourceType 原类型
* @return 是否可转化
*/
public static boolean isAssignable(Class<?> targetType, Class<?> sourceType) {
if (null == targetType || null == sourceType) {
return false;
}
// 对象类型
if (targetType.isAssignableFrom(sourceType)) {
return true;
}
// 基本类型
if (targetType.isPrimitive()) {
// 原始类型
Class<?> resolvedPrimitive = BasicType.wrapperPrimitiveMap.get(sourceType);
if (resolvedPrimitive != null && targetType.equals(resolvedPrimitive)) {
return true;
}
} else {
// 包装类型
Class<?> resolvedWrapper = BasicType.primitiveWrapperMap.get(sourceType);
if (resolvedWrapper != null && targetType.isAssignableFrom(resolvedWrapper)) {
return true;
}
}
return false;
}
/**
* 设置方法为可访问
*
* @param method 方法
* @return 方法
*/
public static Method setAccessible(Method method) {
if (null != method && ClassKit.isNotPublic(method)) {
method.setAccessible(true);
}
return method;
}
/**
* 指定类是否为非public
*
* @param clazz 类
* @return 是否为非public
*/
public static boolean isNotPublic(Class<?> clazz) {
return false == isPublic(clazz);
}
/**
* 指定方法是否为非public
*
* @param method 方法
* @return 是否为非public
*/
public static boolean isNotPublic(Method method) {
return false == isPublic(method);
}
/**
* 指定类是否为Public
*
* @param clazz 类
* @return 是否为public
*/
public static boolean isPublic(Class<?> clazz) {
if (null == clazz) {
throw new NullPointerException("Class to provided is null.");
}
return Modifier.isPublic(clazz.getModifiers());
}
/**
* 指定方法是否为Public
*
* @param method 方法
* @return 是否为public
*/
public static boolean isPublic(Method method) {
if (null == method) {
throw new NullPointerException("Method to provided is null.");
}
return isPublic(method.getDeclaringClass());
}
}
\ No newline at end of file
package com.stylefeng.guns.core.support;
import java.util.Date;
/**
* 封装java.util.Date
* @author xiaoleilu
*
*/
public class DateTime extends Date{
private static final long serialVersionUID = -5395712593979185936L;
/**
* 转换JDK date为 DateTime
* @param date JDK Date
* @return DateTime
*/
public static DateTime parse(Date date) {
return new DateTime(date);
}
/**
* 当前时间
*/
public DateTime() {
super();
}
/**
* 给定日期的构造
* @param date 日期
*/
public DateTime(Date date) {
this(date.getTime());
}
/**
* 给定日期毫秒数的构造
* @param timeMillis 日期毫秒数
*/
public DateTime(long timeMillis) {
super(timeMillis);
}
@Override
public String toString() {
return DateTimeKit.formatDateTime(this);
}
public String toString(String format) {
return DateTimeKit.format(this, format);
}
/**
* @return 输出精确到毫秒的标准日期形式
*/
public String toMsStr() {
return DateTimeKit.format(this, DateTimeKit.NORM_DATETIME_MS_PATTERN);
}
/**
* @return java.util.Date
*/
public Date toDate() {
return new Date(this.getTime());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment