提交 bf7c1eeb 编写于 作者: D dqjdda

代码优化完成,去除大量idea警告,代码生成器优化等

上级 e3c3ebb1
......@@ -13,9 +13,9 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
public @interface Query {
/** Dong ZhaoYang 2017/8/7 基本对象的属性名 */
// Dong ZhaoYang 2017/8/7 基本对象的属性名
String propName() default "";
/** Dong ZhaoYang 2017/8/7 查询方式 */
// Dong ZhaoYang 2017/8/7 查询方式
Type type() default Type.EQUAL;
/**
......
......@@ -35,7 +35,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
return null;
}
String str = new String(bytes, StandardCharsets.UTF_8);
return (T) JSON.parseObject(str, clazz);
return JSON.parseObject(str, clazz);
}
}
......@@ -35,7 +35,7 @@ public class SwaggerConfig {
@Bean
public Docket createRestApi() {
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
List<Parameter> pars = new ArrayList<>();
ticketPar.name(tokenHeader).description("token")
.modelRef(new ModelRef("string"))
.parameterType("header")
......
......@@ -19,9 +19,6 @@ public class EncryptUtils {
/**
* 对称加密
* @param source
* @return
* @throws Exception
*/
public static String desEncrypt(String source) throws Exception {
if (source == null || source.length() == 0){
......
......@@ -11,6 +11,7 @@ import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
......@@ -92,7 +93,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
* 文件大小转换
*/
public static String getSize(long size){
String resultSize = "";
String resultSize;
if (size / GB >= 1) {
//如果当前Byte的值大于等于1GB
resultSize = DF.format(size / (float) GB) + "GB ";
......@@ -117,7 +118,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
return file;
}
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
......@@ -144,7 +145,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
String d = dest.getPath();
file.transferTo(dest);// 文件写入
return dest;
} catch (Exception e) {
......@@ -155,7 +155,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
public static String fileToBase64(File file) throws Exception {
FileInputStream inputFile = new FileInputStream(file);
String base64 =null;
String base64;
byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer);
inputFile.close();
......@@ -210,4 +210,64 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
throw new BadRequestException("文件超出规定大小");
}
}
/**
* 判断两个文件是否相同
*/
public static boolean check(File file1, File file2) {
String img1Md5 = getMD5(file1);
String img2Md5 = getMD5(file2);
return img1Md5.equals(img2Md5);
}
/**
* 判断两个文件是否相同
*/
public static boolean check(String file1Md5, String file2Md5) {
return file1Md5.equals(file2Md5);
}
private static byte[] getByte(File file) {
// 得到文件长度
byte[] b = new byte[(int) file.length()];
try {
InputStream in = new FileInputStream(file);
try {
in.read(b);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return b;
}
private static String getMD5(byte[] bytes) {
// 16进制字符
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(bytes);
byte[] md = mdTemp.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
// 移位 输出字符串
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getMD5(File file) {
return getMD5(getByte(file));
}
}
......@@ -112,7 +112,8 @@ public class QueryHelp {
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return cb.and(list.toArray(new Predicate[list.size()]));
int size = list.size();
return cb.and(list.toArray(new Predicate[size]));
}
@SuppressWarnings("unchecked")
......@@ -124,8 +125,7 @@ public class QueryHelp {
}
}
@SuppressWarnings("unchecked")
public static boolean isBlank(final CharSequence cs) {
private static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
......@@ -138,7 +138,6 @@ public class QueryHelp {
return true;
}
@SuppressWarnings("unchecked")
private static List<Field> getAllFields(Class clazz, List<Field> fields) {
if (clazz != null) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
......
......@@ -13,7 +13,7 @@ import org.springframework.security.core.userdetails.UserDetails;
public class SecurityUtils {
public static UserDetails getUserDetails() {
UserDetails userDetails = null;
UserDetails userDetails;
try {
userDetails = (UserDetails) org.springframework.security.core.context.SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) {
......
......@@ -7,7 +7,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author
* @author Jie
* @date 2019-01-07
*/
@Slf4j
......@@ -15,14 +15,6 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
private static ApplicationContext applicationContext = null;
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
......@@ -53,14 +45,14 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}
@Override
public void destroy() throws Exception {
public void destroy(){
SpringContextHolder.clearHolder();
}
......
......@@ -18,25 +18,6 @@ import java.util.Date;
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
static boolean inString(String str, String... strs) {
if (str != null) {
for (String s : strs) {
if (str.equals(trim(s))) {
return true;
}
}
}
return false;
}
/**
* 驼峰命名法工具
......@@ -151,9 +132,9 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
DbConfig config = new DbConfig();
File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name);
DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method = null;
Method method;
method = searcher.getClass().getMethod("btreeSearch", String.class);
DataBlock dataBlock = null;
DataBlock dataBlock;
dataBlock = (DataBlock) method.invoke(searcher, ip);
String address = dataBlock.getRegion().replace("0|","");
if(address.charAt(address.length()-1) == '|'){
......
......@@ -36,7 +36,7 @@ public class TranslatorUtil {
}
}
private static String parseResult(String inputJson) throws Exception {
private static String parseResult(String inputJson){
JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0);
StringBuilder result = new StringBuilder();
for (Object o : jsonArray2) {
......
package me.zhengjie.utils;
import cn.hutool.core.util.ObjectUtil;
import me.zhengjie.exception.BadRequestException;
import java.util.Optional;
/**
* 验证工具
......@@ -13,11 +13,9 @@ public class ValidationUtil{
/**
* 验证空
*/
public static void isNull(Optional optional, String entity,String parameter , Object value){
if(!optional.isPresent()){
String msg = entity
+ " 不存在 "
+"{ "+ parameter +":"+ value.toString() +" }";
public static void isNull(Object obj, String entity, String parameter , Object value){
if(ObjectUtil.isNull(obj)){
String msg = entity + " 不存在: "+ parameter +" is "+ value;
throw new BadRequestException(msg);
}
}
......
......@@ -11,12 +11,6 @@ import static org.junit.Assert.*;
public class StringUtilsTest {
@Test
public void testInString() {
assertTrue(inString("?", "?"));
assertFalse(inString("?", new String[]{}));
}
@Test
public void testToCamelCase() {
assertNull(toCamelCase(null));
......
......@@ -16,26 +16,26 @@ public class GenConfig {
@Id
private Long id;
/** 包路径 **/
// 包路径
private String pack;
/** 模块名 **/
// 模块名
@Column(name = "module_name")
private String moduleName;
/** 前端文件路径 **/
// 前端文件路径
private String path;
/** 前端文件路径 **/
// 前端文件路径
@Column(name = "api_path")
private String apiPath;
/** 作者 **/
// 作者
private String author;
/** 表前缀 **/
// 表前缀
private String prefix;
/** 是否覆盖 **/
// 是否覆盖
private Boolean cover;
}
......@@ -14,27 +14,27 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class ColumnInfo {
/** 数据库字段名称 **/
// 数据库字段名称
private Object columnName;
/** 允许空值 **/
// 允许空值
private Object isNullable;
/** 数据库字段类型 **/
// 数据库字段类型
private Object columnType;
/** 数据库字段注释 **/
// 数据库字段注释
private Object columnComment;
/** 数据库字段键类型 **/
// 数据库字段键类型
private Object columnKey;
/** 额外的参数 **/
// 额外的参数
private Object extra;
/** 查询 1:模糊 2:精确 **/
// 查询 1:模糊 2:精确
private String columnQuery;
/** 是否在列表显示 **/
// 是否在列表显示
private String columnShow;
}
......@@ -14,10 +14,10 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class TableInfo {
/** 表名称 **/
// 表名称
private Object tableName;
/** 创建日期 **/
// 创建日期
private Object createTime;
// 数据库引擎
......
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.domain.GenConfig;
import me.zhengjie.service.GenConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
......@@ -13,23 +14,25 @@ import org.springframework.web.bind.annotation.*;
* @date 2019-01-14
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/genConfig")
@Api(tags = "系统:代码生成器配置管理")
public class GenConfigController {
@Autowired
private GenConfigService genConfigService;
private final GenConfigService genConfigService;
/**
* 查询生成器配置
* @return
*/
@GetMapping(value = "/genConfig")
public GenConfigController(GenConfigService genConfigService) {
this.genConfigService = genConfigService;
}
@ApiOperation("查询")
@GetMapping
public ResponseEntity get(){
return new ResponseEntity(genConfigService.find(), HttpStatus.OK);
return new ResponseEntity<>(genConfigService.find(), HttpStatus.OK);
}
@PutMapping(value = "/genConfig")
@ApiOperation("修改")
@PutMapping
public ResponseEntity emailConfig(@Validated @RequestBody GenConfig genConfig){
return new ResponseEntity(genConfigService.update(genConfig),HttpStatus.OK);
return new ResponseEntity<>(genConfigService.update(genConfig),HttpStatus.OK);
}
}
package me.zhengjie.rest;
import cn.hutool.core.util.PageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.domain.vo.ColumnInfo;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.service.GenConfigService;
import me.zhengjie.service.GeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -17,49 +18,39 @@ import java.util.List;
* @date 2019-01-02
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/generator")
@Api(tags = "系统:代码生成管理")
public class GeneratorController {
@Autowired
private GeneratorService generatorService;
private final GeneratorService generatorService;
@Autowired
private GenConfigService genConfigService;
private final GenConfigService genConfigService;
@Value("${generator.enabled}")
private Boolean generatorEnabled;
/**
* 查询数据库元数据
* @param name
* @param page
* @param size
* @return
*/
@GetMapping(value = "/generator/tables")
public GeneratorController(GeneratorService generatorService, GenConfigService genConfigService) {
this.generatorService = generatorService;
this.genConfigService = genConfigService;
}
@ApiOperation("查询数据库元数据")
@GetMapping(value = "/tables")
public ResponseEntity getTables(@RequestParam(defaultValue = "") String name,
@RequestParam(defaultValue = "0")Integer page,
@RequestParam(defaultValue = "10")Integer size){
int[] startEnd = PageUtil.transToStartEnd(page+1, size);
return new ResponseEntity(generatorService.getTables(name,startEnd), HttpStatus.OK);
return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK);
}
/**
* 查询表内元数据
* @param tableName
* @return
*/
@GetMapping(value = "/generator/columns")
@ApiOperation("查询表内元数据")
@GetMapping(value = "/columns")
public ResponseEntity getTables(@RequestParam String tableName){
return new ResponseEntity(generatorService.getColumns(tableName), HttpStatus.OK);
return new ResponseEntity<>(generatorService.getColumns(tableName), HttpStatus.OK);
}
/**
* 生成代码
* @param columnInfos
* @return
*/
@PostMapping(value = "/generator")
@ApiOperation("生成代码")
@PostMapping
public ResponseEntity generator(@RequestBody List<ColumnInfo> columnInfos, @RequestParam String tableName){
if(!generatorEnabled){
throw new BadRequestException("此环境不允许生成代码!");
......
......@@ -10,21 +10,9 @@ import org.springframework.cache.annotation.Cacheable;
* @author Zheng Jie
* @date 2019-01-14
*/
@CacheConfig(cacheNames = "genConfig")
public interface GenConfigService {
/**
* find
* @return
*/
@Cacheable(key = "'1'")
GenConfig find();
/**
* update
* @param genConfig
* @return
*/
@CacheEvict(allEntries = true)
GenConfig update(GenConfig genConfig);
}
......@@ -12,24 +12,24 @@ public interface GeneratorService {
/**
* 查询数据库元数据
* @param name
* @param startEnd
* @return
* @param name 表名
* @param startEnd 分页参数
* @return /
*/
Object getTables(String name, int[] startEnd);
/**
* 得到数据表的元数据
* @param name
* @return
* @param name 表名
* @return /
*/
Object getColumns(String name);
/**
* 生成代码
* @param columnInfos
* @param genConfig
* @param tableName
* @param columnInfos 表字段数据
* @param genConfig 代码生成配置
* @param tableName 表名
*/
void generator(List<ColumnInfo> columnInfos, GenConfig genConfig, String tableName);
}
......@@ -3,9 +3,10 @@ package me.zhengjie.service.impl;
import me.zhengjie.domain.GenConfig;
import me.zhengjie.repository.GenConfigRepository;
import me.zhengjie.service.GenConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.Optional;
......@@ -14,35 +15,37 @@ import java.util.Optional;
* @date 2019-01-14
*/
@Service
@CacheConfig(cacheNames = "genConfig")
public class GenConfigServiceImpl implements GenConfigService {
@Autowired
private GenConfigRepository genConfigRepository;
private final GenConfigRepository genConfigRepository;
public GenConfigServiceImpl(GenConfigRepository genConfigRepository) {
this.genConfigRepository = genConfigRepository;
}
@Override
@Cacheable(key = "'1'")
public GenConfig find() {
Optional<GenConfig> genConfig = genConfigRepository.findById(1L);
if(genConfig.isPresent()){
return genConfig.get();
} else {
return new GenConfig();
}
return genConfig.orElseGet(GenConfig::new);
}
@Override
@CacheEvict(allEntries = true)
public GenConfig update(GenConfig genConfig) {
genConfig.setId(1L);
// 自动设置Api路径,注释掉前需要同步取消前端的注释
String separator = File.separator;
String[] paths = null;
String[] paths;
if (separator.equals("\\")) {
paths = genConfig.getPath().split("\\\\");
} else paths = genConfig.getPath().split(File.separator);
StringBuffer api = new StringBuffer();
for (int i = 0; i < paths.length; i++) {
api.append(paths[i]);
StringBuilder api = new StringBuilder();
for (String path : paths) {
api.append(path);
api.append(separator);
if(paths[i].equals("src")){
if (path.equals("src")) {
api.append("api");
break;
}
......
......@@ -37,10 +37,11 @@ public class GeneratorServiceImpl implements GeneratorService {
query.setFirstResult(startEnd[0]);
query.setMaxResults(startEnd[1]-startEnd[0]);
query.setParameter(1, StringUtils.isNotBlank(name) ? ("%" + name + "%") : "%%");
List<Object[]> result = query.getResultList();
List result = query.getResultList();
List<TableInfo> tableInfos = new ArrayList<>();
for (Object[] obj : result) {
tableInfos.add(new TableInfo(obj[0],obj[1],obj[2],obj[3], ObjectUtil.isNotEmpty(obj[4])? obj[4] : "-"));
for (Object obj : result) {
Object[] arr = (Object[]) obj;
tableInfos.add(new TableInfo(arr[0],arr[1],arr[2],arr[3], ObjectUtil.isNotEmpty(arr[4])? arr[4] : "-"));
}
Query query1 = em.createNativeQuery("SELECT COUNT(*) from information_schema.tables where table_schema = (select database())");
Object totalElements = query1.getSingleResult();
......@@ -54,10 +55,11 @@ public class GeneratorServiceImpl implements GeneratorService {
"where table_name = ? and table_schema = (select database()) order by ordinal_position";
Query query = em.createNativeQuery(sql);
query.setParameter(1, StringUtils.isNotBlank(name) ? name : null);
List<Object[]> result = query.getResultList();
List result = query.getResultList();
List<ColumnInfo> columnInfos = new ArrayList<>();
for (Object[] obj : result) {
columnInfos.add(new ColumnInfo(obj[0],obj[1],obj[2],obj[3],obj[4],obj[5],null,"true"));
for (Object obj : result) {
Object[] arr = (Object[]) obj;
columnInfos.add(new ColumnInfo(arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],null,"true"));
}
return PageUtil.toPage(columnInfos,columnInfos.size());
}
......
......@@ -12,11 +12,12 @@ public class ColUtil {
/**
* 转换mysql数据类型为java数据类型
* @param type
* @return
* @param type 数据库字段类型
* @return String
*/
public static String cloToJava(String type){
static String cloToJava(String type){
Configuration config = getConfig();
assert config != null;
return config.getString(type,"unknowType");
}
......
......@@ -34,9 +34,9 @@ public class GenUtil {
/**
* 获取后端代码模板名称
* @return
* @return List
*/
public static List<String> getAdminTemplateNames() {
private static List<String> getAdminTemplateNames() {
List<String> templateNames = new ArrayList<>();
templateNames.add("Entity");
templateNames.add("Dto");
......@@ -51,9 +51,9 @@ public class GenUtil {
/**
* 获取前端代码模板名称
* @return
* @return List
*/
public static List<String> getFrontTemplateNames() {
private static List<String> getFrontTemplateNames() {
List<String> templateNames = new ArrayList<>();
templateNames.add("api");
templateNames.add("index");
......@@ -67,7 +67,7 @@ public class GenUtil {
* @param genConfig 生成代码的参数配置,如包路径,作者
*/
public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConfig, String tableName) throws IOException {
Map<String,Object> map = new HashMap();
Map<String,Object> map = new HashMap<>();
map.put("package",genConfig.getPack());
map.put("moduleName",genConfig.getModuleName());
map.put("author",genConfig.getAuthor());
......@@ -85,6 +85,8 @@ public class GenUtil {
map.put("upperCaseClassName", className.toUpperCase());
map.put("changeClassName", changeClassName);
map.put("hasTimestamp",false);
map.put("queryHasTimestamp",false);
map.put("queryHasBigDecimal",false);
map.put("hasBigDecimal",false);
map.put("hasQuery",false);
map.put("auto",false);
......@@ -92,7 +94,7 @@ public class GenUtil {
List<Map<String,Object>> columns = new ArrayList<>();
List<Map<String,Object>> queryColumns = new ArrayList<>();
for (ColumnInfo column : columnInfos) {
Map<String,Object> listMap = new HashMap();
Map<String,Object> listMap = new HashMap<>();
listMap.put("columnComment",column.getColumnComment());
listMap.put("columnKey",column.getColumnKey());
......@@ -124,6 +126,12 @@ public class GenUtil {
if(!StringUtils.isBlank(column.getColumnQuery())){
listMap.put("columnQuery",column.getColumnQuery());
map.put("hasQuery",true);
if(TIMESTAMP.equals(colType)){
map.put("queryHasTimestamp",true);
}
if(BIGDECIMAL.equals(colType)){
map.put("queryHasBigDecimal",true);
}
queryColumns.add(listMap);
}
columns.add(listMap);
......@@ -138,6 +146,7 @@ public class GenUtil {
Template template = engine.getTemplate("generator/admin/"+templateName+".ftl");
String filePath = getAdminFilePath(templateName,genConfig,className);
assert filePath != null;
File file = new File(filePath);
// 如果非覆盖生成
......@@ -154,6 +163,7 @@ public class GenUtil {
Template template = engine.getTemplate("generator/front/"+templateName+".ftl");
String filePath = getFrontFilePath(templateName,genConfig,map.get("changeClassName").toString());
assert filePath != null;
File file = new File(filePath);
// 如果非覆盖生成
......@@ -168,7 +178,7 @@ public class GenUtil {
/**
* 定义后端文件路径以及名称
*/
public static String getAdminFilePath(String templateName, GenConfig genConfig, String className) {
private static String getAdminFilePath(String templateName, GenConfig genConfig, String className) {
String projectPath = System.getProperty("user.dir") + File.separator + genConfig.getModuleName();
String packagePath = projectPath + File.separator + "src" +File.separator+ "main" + File.separator + "java" + File.separator;
if (!ObjectUtils.isEmpty(genConfig.getPack())) {
......@@ -213,7 +223,7 @@ public class GenUtil {
/**
* 定义前端文件路径以及名称
*/
public static String getFrontFilePath(String templateName, GenConfig genConfig, String apiName) {
private static String getFrontFilePath(String templateName, GenConfig genConfig, String apiName) {
String path = genConfig.getPath();
if ("api".equals(templateName)) {
......@@ -230,18 +240,17 @@ public class GenUtil {
return null;
}
public static void genFile(File file,Template template,Map<String,Object> map) throws IOException {
private static void genFile(File file, Template template, Map<String, Object> map) throws IOException {
// 生成目标文件
Writer writer = null;
try {
FileUtil.touch(file);
writer = new FileWriter(file);
template.render(map, writer);
} catch (TemplateException e) {
throw new RuntimeException(e);
} catch (IOException e) {
} catch (TemplateException | IOException e) {
throw new RuntimeException(e);
} finally {
assert writer != null;
writer.close();
}
}
......
......@@ -48,7 +48,7 @@ public class LogAspect {
*/
@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
Object result;
currentTime = System.currentTimeMillis();
result = joinPoint.proceed();
Log log = new Log("INFO",System.currentTimeMillis() - currentTime);
......
......@@ -21,56 +21,38 @@ public class Log implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 操作用户
*/
// 操作用户
private String username;
/**
* 描述
*/
// 描述
private String description;
/**
* 方法名
*/
// 方法名
private String method;
/**
* 参数
*/
// 参数
@Column(columnDefinition = "text")
private String params;
/**
* 日志类型
*/
// 日志类型
@Column(name = "log_type")
private String logType;
/**
* 请求ip
*/
// 请求ip
@Column(name = "request_ip")
private String requestIp;
@Column(name = "address")
private String address;
/**
* 请求耗时
*/
// 请求耗时
private Long time;
/**
* 异常详细
*/
// 异常详细
@Column(name = "exception_detail", columnDefinition = "text")
private byte[] exceptionDetail;
/**
* 创建日期
*/
// 创建日期
@CreationTimestamp
@Column(name = "create_time")
private Timestamp createTime;
......
......@@ -11,22 +11,14 @@ import org.springframework.stereotype.Repository;
* @date 2018-11-24
*/
@Repository
public interface LogRepository extends JpaRepository<Log,Long>, JpaSpecificationExecutor {
public interface LogRepository extends JpaRepository<Log,Long>, JpaSpecificationExecutor<Log> {
/**
* 获取一个时间段的IP记录
* @param date1
* @param date2
* @return
*/
@Query(value = "select count(*) FROM (select request_ip FROM log where create_time between ?1 and ?2 GROUP BY request_ip) as s",nativeQuery = true)
Long findIp(String date1, String date2);
/**
* findExceptionById
* @param id
* @return
*/
@Query(value = "select exception_detail FROM log where id = ?1",nativeQuery = true)
String findExceptionById(Long id);
@Query(value = "select l FROM Log l where l.id = ?1")
Log findExceptionById(Long id);
}
package me.zhengjie.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.service.LogService;
import me.zhengjie.service.dto.LogQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -18,36 +19,44 @@ import org.springframework.web.bind.annotation.RestController;
* @date 2018-11-24
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/logs")
@Api(tags = "监控:日志管理")
public class LogController {
@Autowired
private LogService logService;
private final LogService logService;
@GetMapping(value = "/logs")
public LogController(LogService logService) {
this.logService = logService;
}
@GetMapping
@ApiOperation("日志查询")
@PreAuthorize("hasAnyRole('ADMIN')")
public ResponseEntity getLogs(LogQueryCriteria criteria, Pageable pageable){
criteria.setLogType("INFO");
return new ResponseEntity(logService.queryAll(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK);
}
@GetMapping(value = "/logs/user")
@GetMapping(value = "/user")
@ApiOperation("用户日志查询")
public ResponseEntity getUserLogs(LogQueryCriteria criteria, Pageable pageable){
criteria.setLogType("INFO");
criteria.setBlurry(SecurityUtils.getUsername());
return new ResponseEntity(logService.queryAllByUser(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK);
}
@GetMapping(value = "/logs/error")
@GetMapping(value = "/error")
@ApiOperation("错误日志查询")
@PreAuthorize("hasAnyRole('ADMIN')")
public ResponseEntity getErrorLogs(LogQueryCriteria criteria, Pageable pageable){
criteria.setLogType("ERROR");
return new ResponseEntity(logService.queryAll(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(logService.queryAll(criteria,pageable), HttpStatus.OK);
}
@GetMapping(value = "/logs/error/{id}")
@GetMapping(value = "/error/{id}")
@ApiOperation("日志异常详情查询")
@PreAuthorize("hasAnyRole('ADMIN')")
public ResponseEntity getErrorLogs(@PathVariable Long id){
return new ResponseEntity(logService.findByErrDetail(id), HttpStatus.OK);
return new ResponseEntity<>(logService.findByErrDetail(id), HttpStatus.OK);
}
}
......@@ -12,36 +12,17 @@ import org.springframework.scheduling.annotation.Async;
*/
public interface LogService {
/**
* queryAll
* @param criteria
* @param pageable
* @return
*/
Object queryAll(LogQueryCriteria criteria, Pageable pageable);
/**
* queryAllByUser
* @param criteria
* @param pageable
* @return
*/
Object queryAllByUser(LogQueryCriteria criteria, Pageable pageable);
/**
* 新增日志
* @param username
* @param ip
* @param joinPoint
* @param log
*/
@Async
void save(String username, String ip, ProceedingJoinPoint joinPoint, Log log);
/**
* 查询异常详情
* @param id
* @return
* @param id 日志ID
* @return Object
*/
Object findByErrDetail(Long id);
}
......@@ -13,36 +13,24 @@ public class LogErrorDTO implements Serializable {
private Long id;
/**
* 操作用户
*/
// 操作用户
private String username;
/**
* 描述
*/
// 描述
private String description;
/**
* 方法名
*/
// 方法名
private String method;
/**
* 参数
*/
// 参数
private String params;
/**
* 请求ip
*/
// 请求ip
private String requestIp;
private String address;
/**
* 创建日期
*/
// 创建日期
private Timestamp createTime;
}
\ No newline at end of file
package me.zhengjie.service.dto;
import lombok.Data;
import java.io.Serializable;
import java.sql.Timestamp;
......@@ -12,25 +11,17 @@ import java.sql.Timestamp;
@Data
public class LogSmallDTO implements Serializable {
/**
* 描述
*/
// 描述
private String description;
/**
* 请求ip
*/
// 请求ip
private String requestIp;
/**
* 请求耗时
*/
// 请求耗时
private Long time;
private String address;
/**
* 创建日期
*/
// 创建日期
private Timestamp createTime;
}
......@@ -13,7 +13,6 @@ import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
......@@ -29,16 +28,17 @@ import java.lang.reflect.Method;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class LogServiceImpl implements LogService {
@Autowired
private LogRepository logRepository;
private final LogRepository logRepository;
@Autowired
private LogErrorMapper logErrorMapper;
private final LogErrorMapper logErrorMapper;
@Autowired
private LogSmallMapper logSmallMapper;
private final LogSmallMapper logSmallMapper;
private final String LOGINPATH = "login";
public LogServiceImpl(LogRepository logRepository, LogErrorMapper logErrorMapper, LogSmallMapper logSmallMapper) {
this.logRepository = logRepository;
this.logErrorMapper = logErrorMapper;
this.logSmallMapper = logSmallMapper;
}
@Override
public Object queryAll(LogQueryCriteria criteria, Pageable pageable){
......@@ -63,32 +63,31 @@ public class LogServiceImpl implements LogService {
Method method = signature.getMethod();
me.zhengjie.aop.log.Log aopLog = method.getAnnotation(me.zhengjie.aop.log.Log.class);
// 描述
if (log != null) {
log.setDescription(aopLog.value());
}
// 方法路径
String methodName = joinPoint.getTarget().getClass().getName()+"."+signature.getName()+"()";
String params = "{";
StringBuilder params = new StringBuilder("{");
//参数值
Object[] argValues = joinPoint.getArgs();
//参数名称
String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
if(argValues != null){
for (int i = 0; i < argValues.length; i++) {
params += " " + argNames[i] + ": " + argValues[i];
params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
}
}
// 获取IP地址
// 描述
if (log != null) {
log.setDescription(aopLog.value());
}
assert log != null;
log.setRequestIp(ip);
String LOGINPATH = "login";
if(LOGINPATH.equals(signature.getName())){
try {
JSONObject jsonObject = new JSONObject(argValues[0]);
username = jsonObject.get("username").toString();
assert argValues != null;
username = new JSONObject(argValues[0]).get("username").toString();
}catch (Exception e){
e.printStackTrace();
}
......@@ -96,12 +95,12 @@ public class LogServiceImpl implements LogService {
log.setAddress(StringUtils.getCityInfo(log.getRequestIp()));
log.setMethod(methodName);
log.setUsername(username);
log.setParams(params + " }");
log.setParams(params.toString() + " }");
logRepository.save(log);
}
@Override
public Object findByErrDetail(Long id) {
return Dict.create().set("exception",logRepository.findExceptionById(id));
return Dict.create().set("exception",logRepository.findExceptionById(id).getExceptionDetail());
}
}
......@@ -10,7 +10,7 @@ import org.mapstruct.ReportingPolicy;
* @author Zheng Jie
* @date 2019-5-22
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LogErrorMapper extends EntityMapper<LogErrorDTO, Log> {
}
\ No newline at end of file
......@@ -10,7 +10,7 @@ import org.mapstruct.ReportingPolicy;
* @author Zheng Jie
* @date 2019-5-22
*/
@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.IGNORE)
@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LogSmallMapper extends EntityMapper<LogSmallDTO, Log> {
}
\ No newline at end of file
......@@ -25,14 +25,17 @@ public class DataScope {
private final String[] scopeType = {"全部","本级","自定义"};
@Autowired
private UserService userService;
private final UserService userService;
@Autowired
private RoleService roleService;
private final RoleService roleService;
@Autowired
private DeptService deptService;
private final DeptService deptService;
public DataScope(UserService userService, RoleService roleService, DeptService deptService) {
this.userService = userService;
this.roleService = roleService;
this.deptService = deptService;
}
public Set<Long> getDeptIds() {
......@@ -76,7 +79,7 @@ public class DataScope {
deptList.forEach(dept -> {
if (dept!=null && dept.getEnabled()){
List<Dept> depts = deptService.findByPid(dept.getId());
if(deptList!=null && deptList.size()!=0){
if(deptList.size() != 0){
list.addAll(getDeptChildren(depts));
}
list.add(dept.getId());
......
package me.zhengjie.modules.monitor.config;
import me.zhengjie.modules.monitor.service.VisitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
......@@ -13,8 +12,11 @@ import org.springframework.stereotype.Component;
@Component
public class VisitsInitialization implements ApplicationRunner {
@Autowired
private VisitsService visitsService;
private final VisitsService visitsService;
public VisitsInitialization(VisitsService visitsService) {
this.visitsService = visitsService;
}
@Override
public void run(ApplicationArguments args) throws Exception {
......
......@@ -4,7 +4,6 @@ import me.zhengjie.modules.monitor.domain.Visits;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
......@@ -16,18 +15,17 @@ public interface VisitsRepository extends JpaRepository<Visits,Long> {
/**
* findByDate
* @param date
* @return
* @param date 日期
* @return Visits
*/
Visits findByDate(String date);
/**
* 获得一个时间段的记录
* @param date1
* @param date2
* @return
* @param date1 日期1
* @param date2 日期2
* @return List
*/
@Query(value = "select * FROM visits where " +
"create_time between ?1 and ?2",nativeQuery = true)
@Query(value = "select * FROM visits where create_time between ?1 and ?2",nativeQuery = true)
List<Visits> findAllVisits(String date1, String date2);
}
package me.zhengjie.modules.monitor.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.annotation.Limit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
......@@ -12,15 +14,17 @@ import java.util.concurrent.atomic.AtomicInteger;
* 接口限流测试类
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/limit")
@Api(tags = "系统:限流测试管理")
public class LimitController {
private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger();
/**
* 测试限流注解,下面配置说明该接口 60秒内最多只能访问 10次,保存到redis的键名为 limit_test,
*/
@GetMapping
@ApiOperation("测试")
@Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit")
@GetMapping("/limit")
public int testLimit() {
return ATOMIC_INTEGER.incrementAndGet();
}
......
package me.zhengjie.modules.monitor.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.monitor.domain.vo.RedisVo;
import me.zhengjie.modules.monitor.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
......@@ -16,21 +16,27 @@ import org.springframework.web.bind.annotation.*;
* @date 2018-12-10
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/redis")
@Api(tags = "系统:Redis缓存管理")
public class RedisController {
@Autowired
private RedisService redisService;
private final RedisService redisService;
public RedisController(RedisService redisService) {
this.redisService = redisService;
}
@Log("查询Redis缓存")
@GetMapping(value = "/redis")
@GetMapping
@ApiOperation("查询Redis缓存")
@PreAuthorize("hasAnyRole('ADMIN','REDIS_ALL','REDIS_SELECT')")
public ResponseEntity getRedis(String key, Pageable pageable){
return new ResponseEntity(redisService.findByKey(key,pageable), HttpStatus.OK);
return new ResponseEntity<>(redisService.findByKey(key,pageable), HttpStatus.OK);
}
@Log("删除Redis缓存")
@DeleteMapping(value = "/redis")
@DeleteMapping
@ApiOperation("删除Redis缓存")
@PreAuthorize("hasAnyRole('ADMIN','REDIS_ALL','REDIS_DELETE')")
public ResponseEntity delete(@RequestBody RedisVo resources){
redisService.delete(resources.getKey());
......@@ -38,7 +44,8 @@ public class RedisController {
}
@Log("清空Redis缓存")
@DeleteMapping(value = "/redis/all")
@DeleteMapping(value = "/all")
@ApiOperation("清空Redis缓存")
@PreAuthorize("hasAnyRole('ADMIN','REDIS_ALL','REDIS_DELETE')")
public ResponseEntity deleteAll(){
redisService.flushdb();
......
package me.zhengjie.modules.monitor.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.modules.monitor.service.VisitsService;
import me.zhengjie.utils.RequestHolder;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -15,25 +17,32 @@ import org.springframework.web.bind.annotation.RestController;
* @date 2018-12-13
*/
@RestController
@RequestMapping("api")
@RequestMapping("/api/visits")
@Api(tags = "系统:访问记录管理")
public class VisitsController {
@Autowired
private VisitsService visitsService;
private final VisitsService visitsService;
@PostMapping(value = "/visits")
public VisitsController(VisitsService visitsService) {
this.visitsService = visitsService;
}
@PostMapping
@ApiOperation("创建访问记录")
public ResponseEntity create(){
visitsService.count(RequestHolder.getHttpServletRequest());
return new ResponseEntity(HttpStatus.CREATED);
}
@GetMapping(value = "/visits")
@GetMapping
@ApiOperation("查询")
public ResponseEntity get(){
return new ResponseEntity(visitsService.get(),HttpStatus.OK);
return new ResponseEntity<>(visitsService.get(),HttpStatus.OK);
}
@GetMapping(value = "/visits/chartData")
@GetMapping(value = "/chartData")
@ApiOperation("查询图表数据")
public ResponseEntity getChartData(){
return new ResponseEntity(visitsService.getChartData(),HttpStatus.OK);
return new ResponseEntity<>(visitsService.getChartData(),HttpStatus.OK);
}
}
......@@ -13,28 +13,28 @@ public interface RedisService {
/**
* findById
* @param key
* @return
* @param key
* @return /
*/
Page findByKey(String key, Pageable pageable);
/**
* 查询验证码的值
* @param key
* @return
* @param key
* @return /
*/
String getCodeVal(String key);
/**
* 保存验证码
* @param key
* @param val
* @param key
* @param val
*/
void saveCode(String key, Object val);
/**
* delete
* @param key
* @param key
*/
void delete(String key);
......
package me.zhengjie.modules.monitor.service;
import org.springframework.scheduling.annotation.Async;
import javax.servlet.http.HttpServletRequest;
/**
......@@ -17,20 +16,20 @@ public interface VisitsService {
/**
* 新增记录
* @param request
* @param request /
*/
@Async
void count(HttpServletRequest request);
/**
* 获取数据
* @return
* @return /
*/
Object get();
/**
* getChartData
* @return
* @return /
*/
Object getChartData();
}
......@@ -3,7 +3,6 @@ package me.zhengjie.modules.monitor.service.impl;
import me.zhengjie.modules.monitor.domain.vo.RedisVo;
import me.zhengjie.modules.monitor.service.RedisService;
import me.zhengjie.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
......@@ -12,6 +11,7 @@ import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
......@@ -21,54 +21,58 @@ import java.util.concurrent.TimeUnit;
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
RedisTemplate redisTemplate;
private final RedisTemplate redisTemplate;
@Value("${loginCode.expiration}")
private Long expiration;
public RedisServiceImpl(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
@SuppressWarnings("unchecked")
public Page<RedisVo> findByKey(String key, Pageable pageable){
List<RedisVo> redisVos = new ArrayList<>();
if(!"*".equals(key)){
key = "*" + key + "*";
}
for (Object s : redisTemplate.keys(key)) {
for (Object s : Objects.requireNonNull(redisTemplate.keys(key))) {
// 过滤掉权限的缓存
if (s.toString().indexOf("role::loadPermissionByUser") != -1 || s.toString().indexOf("user::loadUserByUsername") != -1) {
if (s.toString().contains("role::loadPermissionByUser") || s.toString().contains("user::loadUserByUsername")) {
continue;
}
RedisVo redisVo = new RedisVo(s.toString(),redisTemplate.opsForValue().get(s.toString()).toString());
RedisVo redisVo = new RedisVo(s.toString(), Objects.requireNonNull(redisTemplate.opsForValue().get(s.toString())).toString());
redisVos.add(redisVo);
}
Page<RedisVo> page = new PageImpl<RedisVo>(
return new PageImpl<RedisVo>(
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),redisVos),
pageable,
redisVos.size());
return page;
}
@Override
@SuppressWarnings("unchecked")
public void delete(String key) {
redisTemplate.delete(key);
}
@Override
public void flushdb() {
redisTemplate.getConnectionFactory().getConnection().flushDb();
Objects.requireNonNull(redisTemplate.getConnectionFactory()).getConnection().flushDb();
}
@Override
public String getCodeVal(String key) {
try {
String value = redisTemplate.opsForValue().get(key).toString();
return value;
return Objects.requireNonNull(redisTemplate.opsForValue().get(key)).toString();
}catch (Exception e){
return "";
}
}
@Override
@SuppressWarnings("unchecked")
public void saveCode(String key, Object val) {
redisTemplate.opsForValue().set(key,val);
redisTemplate.expire(key,expiration, TimeUnit.MINUTES);
......
......@@ -26,11 +26,14 @@ import java.util.stream.Collectors;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class VisitsServiceImpl implements VisitsService {
@Autowired
private VisitsRepository visitsRepository;
private final VisitsRepository visitsRepository;
@Autowired
private LogRepository logRepository;
private final LogRepository logRepository;
public VisitsServiceImpl(VisitsRepository visitsRepository, LogRepository logRepository) {
this.visitsRepository = visitsRepository;
this.logRepository = logRepository;
}
@Override
public void save() {
......@@ -58,7 +61,7 @@ public class VisitsServiceImpl implements VisitsService {
@Override
public Object get() {
Map map = new HashMap();
Map<String,Object> map = new HashMap<>();
LocalDate localDate = LocalDate.now();
Visits visits = visitsRepository.findByDate(localDate.toString());
List<Visits> list = visitsRepository.findAllVisits(localDate.minusDays(6).toString(),localDate.plusDays(1).toString());
......@@ -77,7 +80,7 @@ public class VisitsServiceImpl implements VisitsService {
@Override
public Object getChartData() {
Map map = new HashMap();
Map<String,Object> map = new HashMap<>();
LocalDate localDate = LocalDate.now();
List<Visits> list = visitsRepository.findAllVisits(localDate.minusDays(6).toString(),localDate.plusDays(1).toString());
map.put("weekDays",list.stream().map(Visits::getWeekDay).collect(Collectors.toList()));
......
......@@ -3,7 +3,6 @@ package me.zhengjie.modules.quartz.config;
import me.zhengjie.modules.quartz.domain.QuartzJob;
import me.zhengjie.modules.quartz.repository.QuartzJobRepository;
import me.zhengjie.modules.quartz.utils.QuartzManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
......@@ -17,24 +16,24 @@ import java.util.List;
@Component
public class JobRunner implements ApplicationRunner {
@Autowired
private QuartzJobRepository quartzJobRepository;
private final QuartzJobRepository quartzJobRepository;
@Autowired
private QuartzManage quartzManage;
private final QuartzManage quartzManage;
public JobRunner(QuartzJobRepository quartzJobRepository, QuartzManage quartzManage) {
this.quartzJobRepository = quartzJobRepository;
this.quartzManage = quartzManage;
}
/**
* 项目启动时重新激活启用的定时任务
* @param applicationArguments
* @throws Exception
* @param applicationArguments /
*/
@Override
public void run(ApplicationArguments applicationArguments){
System.out.println("--------------------注入定时任务---------------------");
List<QuartzJob> quartzJobs = quartzJobRepository.findByIsPauseIsFalse();
quartzJobs.forEach(quartzJob -> {
quartzManage.addJob(quartzJob);
});
quartzJobs.forEach(quartzManage::addJob);
System.out.println("--------------------定时任务注入完成---------------------");
}
}
......@@ -2,7 +2,6 @@ package me.zhengjie.modules.quartz.config;
import org.quartz.Scheduler;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -12,7 +11,7 @@ import org.springframework.stereotype.Component;
/**
* 定时任务配置
* @author
* @author /
* @date 2019-01-07
*/
@Configuration
......@@ -22,10 +21,13 @@ public class QuartzConfig {
* 解决Job中注入Spring Bean为null的问题
*/
@Component("quartzJobFactory")
public class QuartzJobFactory extends AdaptableJobFactory {
public static class QuartzJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
private final AutowireCapableBeanFactory capableBeanFactory;
public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) {
this.capableBeanFactory = capableBeanFactory;
}
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
......@@ -39,9 +41,9 @@ public class QuartzConfig {
/**
* 注入scheduler到spring
* @param quartzJobFactory
* @return
* @throws Exception
* @param quartzJobFactory /
* @return Scheduler
* @throws Exception /
*/
@Bean(name = "scheduler")
public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception {
......
......@@ -25,55 +25,39 @@ public class QuartzJob implements Serializable {
@NotNull(groups = {Update.class})
private Long id;
/**
* 定时器名称
*/
// 定时器名称
@Column(name = "job_name")
private String jobName;
/**
* Bean名称
*/
// Bean名称
@Column(name = "bean_name")
@NotBlank
private String beanName;
/**
* 方法名称
*/
// 方法名称
@Column(name = "method_name")
@NotBlank
private String methodName;
/**
* 参数
*/
// 参数
@Column(name = "params")
private String params;
/**
* cron表达式
*/
// cron表达式
@Column(name = "cron_expression")
@NotBlank
private String cronExpression;
/**
* 状态
*/
// 状态
@Column(name = "is_pause")
private Boolean isPause = false;
/**
* 备注
*/
// 备注
@Column(name = "remark")
@NotBlank
private String remark;
/**
* 创建日期
*/
// 创建日期
@UpdateTimestamp
@Column(name = "update_time")
private Timestamp updateTime;
......
......@@ -20,56 +20,38 @@ public class QuartzLog implements Serializable {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* 任务名称
*/
// 任务名称
@Column(name = "job_name")
private String jobName;
/**
* Bean名称
*/
// Bean名称
@Column(name = "baen_name")
private String beanName;
/**
* 方法名称
*/
// 方法名称
@Column(name = "method_name")
private String methodName;
/**
* 参数
*/
// 参数
@Column(name = "params")
private String params;
/**
* cron表达式
*/
// cron表达式
@Column(name = "cron_expression")
private String cronExpression;
/**
* 状态
*/
// 状态
@Column(name = "is_success")
private Boolean isSuccess;
/**
* 异常详细
*/
// 异常详细
@Column(name = "exception_detail",columnDefinition = "text")
private String exceptionDetail;
/**
* 耗时(毫秒)
*/
// 耗时(毫秒)
private Long time;
/**
* 创建日期
*/
// 创建日期
@CreationTimestamp
@Column(name = "create_time")
private Timestamp createTime;
......
......@@ -9,11 +9,11 @@ import java.util.List;
* @author Zheng Jie
* @date 2019-01-07
*/
public interface QuartzJobRepository extends JpaRepository<QuartzJob,Long>, JpaSpecificationExecutor {
public interface QuartzJobRepository extends JpaRepository<QuartzJob,Long>, JpaSpecificationExecutor<QuartzJob> {
/**
* 查询启用的任务
* @return
* @return List
*/
List<QuartzJob> findByIsPauseIsFalse();
}
......@@ -8,6 +8,6 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2019-01-07
*/
public interface QuartzLogRepository extends JpaRepository<QuartzLog,Long>, JpaSpecificationExecutor {
public interface QuartzLogRepository extends JpaRepository<QuartzLog,Long>, JpaSpecificationExecutor<QuartzLog> {
}
package me.zhengjie.modules.quartz.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.quartz.domain.QuartzJob;
import me.zhengjie.modules.quartz.service.QuartzJobService;
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -20,39 +21,47 @@ import org.springframework.web.bind.annotation.*;
*/
@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "系统:定时任务管理")
@RequestMapping("/api/jobs")
public class QuartzJobController {
private static final String ENTITY_NAME = "quartzJob";
@Autowired
private QuartzJobService quartzJobService;
private final QuartzJobService quartzJobService;
public QuartzJobController(QuartzJobService quartzJobService) {
this.quartzJobService = quartzJobService;
}
@Log("查询定时任务")
@GetMapping(value = "/jobs")
@ApiOperation("查询定时任务")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_SELECT')")
public ResponseEntity getJobs(JobQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK);
}
@GetMapping(value = "/jobLogs")
@ApiOperation("查询任务执行日志")
@GetMapping(value = "/logs")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_SELECT')")
public ResponseEntity getJobLogs(JobQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK);
return new ResponseEntity<>(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK);
}
@Log("新增定时任务")
@PostMapping(value = "/jobs")
@ApiOperation("新增定时任务")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_CREATE')")
public ResponseEntity create(@Validated @RequestBody QuartzJob resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(quartzJobService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(quartzJobService.create(resources),HttpStatus.CREATED);
}
@Log("修改定时任务")
@PutMapping(value = "/jobs")
@ApiOperation("修改定时任务")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_EDIT')")
public ResponseEntity update(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){
quartzJobService.update(resources);
......@@ -60,7 +69,8 @@ public class QuartzJobController {
}
@Log("更改定时任务状态")
@PutMapping(value = "/jobs/{id}")
@ApiOperation("更改定时任务状态")
@PutMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_EDIT')")
public ResponseEntity updateIsPause(@PathVariable Long id){
quartzJobService.updateIsPause(quartzJobService.findById(id));
......@@ -68,7 +78,8 @@ public class QuartzJobController {
}
@Log("执行定时任务")
@PutMapping(value = "/jobs/exec/{id}")
@ApiOperation("执行定时任务")
@PutMapping(value = "/exec/{id}")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_EDIT')")
public ResponseEntity execution(@PathVariable Long id){
quartzJobService.execution(quartzJobService.findById(id));
......@@ -76,7 +87,8 @@ public class QuartzJobController {
}
@Log("删除定时任务")
@DeleteMapping(value = "/jobs/{id}")
@ApiOperation("删除定时任务")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','JOB_ALL','JOB_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
quartzJobService.delete(quartzJobService.findById(id));
......
package me.zhengjie.modules.quartz.service;
import me.zhengjie.modules.quartz.domain.QuartzJob;
import me.zhengjie.modules.quartz.domain.QuartzLog;
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
/**
* @author Zheng Jie
* @date 2019-01-07
*/
@CacheConfig(cacheNames = "quartzJob")
public interface QuartzJobService {
/**
* queryAll quartzJob
* @param criteria
* @param pageable
* @return
*/
@Cacheable
Object queryAll(JobQueryCriteria criteria, Pageable pageable);
/**
* queryAll quartzLog
* @param criteria
* @param pageable
* @return
*/
Object queryAllLog(JobQueryCriteria criteria, Pageable pageable);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
QuartzJob create(QuartzJob resources);
/**
* update
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
void update(QuartzJob resources);
/**
* del
* @param quartzJob
*/
@CacheEvict(allEntries = true)
void delete(QuartzJob quartzJob);
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
QuartzJob findById(Long id);
/**
* 更改定时任务状态
* @param quartzJob
* @param quartzJob /
*/
@CacheEvict(allEntries = true)
void updateIsPause(QuartzJob quartzJob);
/**
* 立即执行定时任务
* @param quartzJob
* @param quartzJob /
*/
void execution(QuartzJob quartzJob);
}
......@@ -11,31 +11,37 @@ import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* @author Zheng Jie
* @date 2019-01-07
*/
@Service(value = "quartzJobService")
@CacheConfig(cacheNames = "quartzJob")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class QuartzJobServiceImpl implements QuartzJobService {
@Autowired
private QuartzJobRepository quartzJobRepository;
private final QuartzJobRepository quartzJobRepository;
@Autowired
private QuartzLogRepository quartzLogRepository;
private final QuartzLogRepository quartzLogRepository;
@Autowired
private QuartzManage quartzManage;
private final QuartzManage quartzManage;
public QuartzJobServiceImpl(QuartzJobRepository quartzJobRepository, QuartzLogRepository quartzLogRepository, QuartzManage quartzManage) {
this.quartzJobRepository = quartzJobRepository;
this.quartzLogRepository = quartzLogRepository;
this.quartzManage = quartzManage;
}
@Override
@Cacheable
public Object queryAll(JobQueryCriteria criteria, Pageable pageable){
return PageUtil.toPage(quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
}
......@@ -46,13 +52,15 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@Cacheable(key = "#p0")
public QuartzJob findById(Long id) {
Optional<QuartzJob> quartzJob = quartzJobRepository.findById(id);
ValidationUtil.isNull(quartzJob,"QuartzJob","id",id);
return quartzJob.get();
QuartzJob quartzJob = quartzJobRepository.findById(id).orElseGet(QuartzJob::new);
ValidationUtil.isNull(quartzJob.getId(),"QuartzJob","id",id);
return quartzJob;
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public QuartzJob create(QuartzJob resources) {
if (!CronExpression.isValidExpression(resources.getCronExpression())){
......@@ -64,6 +72,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void update(QuartzJob resources) {
if(resources.getId().equals(1L)){
......@@ -77,6 +86,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@CacheEvict(allEntries = true)
public void updateIsPause(QuartzJob quartzJob) {
if(quartzJob.getId().equals(1L)){
throw new BadRequestException("该任务不可操作");
......@@ -100,6 +110,7 @@ public class QuartzJobServiceImpl implements QuartzJobService {
}
@Override
@CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class)
public void delete(QuartzJob quartzJob) {
if(quartzJob.getId().equals(1L)){
......
package me.zhengjie.modules.quartz.task;
import me.zhengjie.modules.monitor.service.VisitsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
......@@ -11,8 +10,11 @@ import org.springframework.stereotype.Component;
@Component
public class VisitsTask {
@Autowired
private VisitsService visitsService;
private final VisitsService visitsService;
public VisitsTask(VisitsService visitsService) {
this.visitsService = visitsService;
}
public void run(){
visitsService.save();
......
......@@ -17,7 +17,7 @@ import java.util.concurrent.Future;
/**
* 参考人人开源,https://gitee.com/renrenio/renren-security
* @author
* @author /
* @date 2019-01-07
*/
@Async
......@@ -32,9 +32,8 @@ public class ExecutionJob extends QuartzJobBean {
protected void executeInternal(JobExecutionContext context) {
QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);
// 获取spring bean
QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean("quartzLogRepository");
QuartzJobService quartzJobService = SpringContextHolder.getBean("quartzJobService");
QuartzManage quartzManage = SpringContextHolder.getBean("quartzManage");
QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean(QuartzLogRepository.class);
QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class);
QuartzLog log = new QuartzLog();
log.setJobName(quartzJob.getJobName());
......
......@@ -56,8 +56,7 @@ public class QuartzManage {
/**
* 更新job cron表达式
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void updateJobCron(QuartzJob quartzJob){
try {
......@@ -88,8 +87,7 @@ public class QuartzManage {
/**
* 删除一个job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void deleteJob(QuartzJob quartzJob){
try {
......@@ -104,8 +102,7 @@ public class QuartzManage {
/**
* 恢复一个job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void resumeJob(QuartzJob quartzJob){
try {
......@@ -124,8 +121,7 @@ public class QuartzManage {
/**
* 立即执行job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void runAJobNow(QuartzJob quartzJob){
try {
......@@ -146,8 +142,7 @@ public class QuartzManage {
/**
* 暂停一个job
* @param quartzJob
* @throws SchedulerException
* @param quartzJob /
*/
public void pauseJob(QuartzJob quartzJob){
try {
......
package me.zhengjie.modules.quartz.utils;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
......@@ -10,7 +9,7 @@ import java.util.concurrent.Callable;
/**
* 执行定时任务
* @author
* @author /
*/
@Slf4j
public class QuartzRunnable implements Callable {
......
......@@ -25,23 +25,21 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
private final JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
private final JwtUserDetailsService jwtUserDetailsService;
/**
* 自定义基于JWT的安全过滤器
*/
@Autowired
JwtAuthorizationTokenFilter authenticationTokenFilter;
// 自定义基于JWT的安全过滤器
private final JwtAuthorizationTokenFilter authenticationTokenFilter;
@Value("${jwt.header}")
private String tokenHeader;
@Value("${jwt.auth.path}")
private String loginPath;
public SecurityConfig(JwtAuthenticationEntryPoint unauthorizedHandler, JwtUserDetailsService jwtUserDetailsService, JwtAuthorizationTokenFilter authenticationTokenFilter) {
this.unauthorizedHandler = unauthorizedHandler;
this.jwtUserDetailsService = jwtUserDetailsService;
this.authenticationTokenFilter = authenticationTokenFilter;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
......@@ -70,6 +68,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
String loginPath = "login";
httpSecurity
// 禁用 CSRF
......@@ -91,7 +90,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/**/*.js"
).anonymous()
.antMatchers( HttpMethod.POST,"/auth/"+loginPath).anonymous()
.antMatchers( HttpMethod.POST,"/auth/"+ loginPath).anonymous()
.antMatchers("/auth/vCode").anonymous()
// 支付宝回调
.antMatchers("/api/aliPay/return").anonymous()
......
......@@ -2,6 +2,8 @@ package me.zhengjie.modules.security.rest;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
......@@ -15,7 +17,6 @@ import me.zhengjie.utils.EncryptUtils;
import me.zhengjie.modules.security.utils.JwtTokenUtil;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
......@@ -23,7 +24,6 @@ import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
......@@ -34,29 +34,28 @@ import java.io.IOException;
*/
@Slf4j
@RestController
@RequestMapping("auth")
@RequestMapping("/auth")
@Api(tags = "系统:系统授权接口")
public class AuthenticationController {
@Value("${jwt.header}")
private String tokenHeader;
@Autowired
private JwtTokenUtil jwtTokenUtil;
private final JwtTokenUtil jwtTokenUtil;
@Autowired
private RedisService redisService;
private final RedisService redisService;
@Autowired
@Qualifier("jwtUserDetailsService")
private UserDetailsService userDetailsService;
private final UserDetailsService userDetailsService;
public AuthenticationController(JwtTokenUtil jwtTokenUtil, RedisService redisService, @Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService) {
this.jwtTokenUtil = jwtTokenUtil;
this.redisService = redisService;
this.userDetailsService = userDetailsService;
}
/**
* 登录授权
* @param authorizationUser
* @return
*/
@Log("用户登录")
@PostMapping(value = "${jwt.auth.path}")
@ApiOperation("登录授权")
@PostMapping(value = "/login")
public ResponseEntity login(@Validated @RequestBody AuthorizationUser authorizationUser){
// 查询验证码
......@@ -86,21 +85,16 @@ public class AuthenticationController {
return ResponseEntity.ok(new AuthenticationInfo(token,jwtUser));
}
/**
* 获取用户信息
* @return
*/
@GetMapping(value = "${jwt.auth.account}")
@ApiOperation("获取用户信息")
@GetMapping(value = "/info")
public ResponseEntity getUserInfo(){
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
return ResponseEntity.ok(jwtUser);
}
/**
* 获取验证码
*/
@GetMapping(value = "vCode")
public ImgResult getCode(HttpServletResponse response) throws IOException {
@ApiOperation("获取验证码")
@GetMapping(value = "/vCode")
public ImgResult getCode() throws IOException {
//生成随机字串
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
......
......@@ -18,9 +18,7 @@ public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Se
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
/**
* 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
*/
// 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException==null?"Unauthorized":authException.getMessage());
}
}
......@@ -3,7 +3,6 @@ package me.zhengjie.modules.security.service;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.service.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.GrantedAuthority;
......@@ -17,13 +16,16 @@ import java.util.stream.Collectors;
@CacheConfig(cacheNames = "role")
public class JwtPermissionService {
@Autowired
private RoleRepository roleRepository;
private final RoleRepository roleRepository;
public JwtPermissionService(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
/**
* key的名称如有修改,请同步修改 UserServiceImpl 中的 update 方法
* @param user
* @return
* @param user 用户信息
* @return Collection
*/
@Cacheable(key = "'loadPermissionByUser:' + #p0.username")
public Collection<GrantedAuthority> mapToGrantedAuthorities(UserDTO user) {
......
......@@ -4,7 +4,6 @@ import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
......@@ -20,11 +19,14 @@ import java.util.Optional;
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
private final UserService userService;
@Autowired
private JwtPermissionService permissionService;
private final JwtPermissionService permissionService;
public JwtUserDetailsService(UserService userService, JwtPermissionService permissionService) {
this.userService = userService;
this.permissionService = permissionService;
}
@Override
public UserDetails loadUserByUsername(String username){
......
......@@ -31,15 +31,15 @@ public class JwtTokenUtil implements Serializable {
return getClaimFromToken(token, Claims::getSubject);
}
public Date getIssuedAtDateFromToken(String token) {
private Date getIssuedAtDateFromToken(String token) {
return getClaimFromToken(token, Claims::getIssuedAt);
}
public Date getExpirationDateFromToken(String token) {
private Date getExpirationDateFromToken(String token) {
return getClaimFromToken(token, Claims::getExpiration);
}
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
private <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
final Claims claims = getAllClaimsFromToken(token);
return claimsResolver.apply(claims);
}
......
package me.zhengjie.modules.security.utils;
import me.zhengjie.utils.StringUtils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
......@@ -20,26 +22,27 @@ import javax.imageio.ImageIO;
public class VerifyCodeUtils{
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
* @return 验证码
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
* @return 验证码
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
private static String generateVerifyCode(int verifySize, String sources){
if(StringUtils.isBlank(sources)){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
......@@ -53,11 +56,11 @@ public class VerifyCodeUtils{
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
* @param w /
* @param h /
* @param os /
* @param code /
* @throws IOException /
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
......@@ -157,33 +160,24 @@ public class VerifyCodeUtils{
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
......@@ -192,11 +186,9 @@ public class VerifyCodeUtils{
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
......
......@@ -19,18 +19,12 @@ import java.util.Set;
@Table(name="dept")
public class Dept implements Serializable {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(groups = Update.class)
private Long id;
/**
* 名称
*/
@Column(name = "name",nullable = false)
@NotBlank
private String name;
......@@ -38,9 +32,6 @@ public class Dept implements Serializable {
@NotNull
private Boolean enabled;
/**
* 上级部门
*/
@Column(name = "pid",nullable = false)
@NotNull
private Long pid;
......
......@@ -22,16 +22,10 @@ public class Dict implements Serializable {
@NotNull(groups = Update.class)
private Long id;
/**
* 字典名称
*/
@Column(name = "name",nullable = false,unique = true)
@NotBlank
private String name;
/**
* 描述
*/
@Column(name = "remark")
private String remark;
......
......@@ -20,27 +20,19 @@ public class DictDetail implements Serializable {
@NotNull(groups = Update.class)
private Long id;
/**
* 字典标签
*/
// 字典标签
@Column(name = "label",nullable = false)
private String label;
/**
* 字典值
*/
// 字典值
@Column(name = "value",nullable = false)
private String value;
/**
* 排序
*/
// 排序
@Column(name = "sort")
private String sort = "999";
/**
* 字典id
*/
// 字典id
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "dict_id")
private Dict dict;
......
......@@ -19,18 +19,12 @@ import java.io.Serializable;
@Table(name="job")
public class Job implements Serializable {
/**
* ID
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@NotNull(groups = Update.class)
private Long id;
/**
* 名称
*/
@Column(name = "name",nullable = false)
@NotBlank
private String name;
......@@ -39,9 +33,6 @@ public class Job implements Serializable {
@NotNull
private Long sort;
/**
* 状态
*/
@Column(name = "enabled",nullable = false)
@NotNull
private Boolean enabled;
......@@ -50,9 +41,6 @@ public class Job implements Serializable {
@JoinColumn(name = "dept_id")
private Dept dept;
/**
* 创建日期
*/
@Column(name = "create_time")
@CreationTimestamp
private Timestamp createTime;
......
......@@ -51,15 +51,11 @@ public class Menu implements Serializable {
@Column(columnDefinition = "bit(1) default 0")
private Boolean hidden;
/**
* 上级菜单ID
*/
// 上级菜单ID
@Column(name = "pid",nullable = false)
private Long pid;
/**
* 是否为外链 true/false
*/
// 是否为外链 true/false
@Column(name = "i_frame")
private Boolean iFrame;
......
......@@ -29,9 +29,7 @@ public class Permission implements Serializable{
@NotBlank
private String name;
/**
* 上级类目
*/
// 上级类目
@NotNull
@Column(name = "pid",nullable = false)
private Long pid;
......
......@@ -4,7 +4,6 @@ import me.zhengjie.modules.system.domain.Dept;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Set;
......@@ -12,13 +11,8 @@ import java.util.Set;
* @author Zheng Jie
* @date 2019-03-25
*/
public interface DeptRepository extends JpaRepository<Dept, Long>, JpaSpecificationExecutor {
public interface DeptRepository extends JpaRepository<Dept, Long>, JpaSpecificationExecutor<Dept> {
/**
* findByPid
* @param id
* @return
*/
List<Dept> findByPid(Long id);
@Query(value = "select name from dept where id = ?1",nativeQuery = true)
......
......@@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2019-04-10
*/
public interface DictDetailRepository extends JpaRepository<DictDetail, Long>, JpaSpecificationExecutor {
public interface DictDetailRepository extends JpaRepository<DictDetail, Long>, JpaSpecificationExecutor<DictDetail> {
}
\ No newline at end of file
......@@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2019-04-10
*/
public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificationExecutor {
public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificationExecutor<Dict> {
}
\ No newline at end of file
......@@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @author Zheng Jie
* @date 2019-03-29
*/
public interface JobRepository extends JpaRepository<Job, Long>, JpaSpecificationExecutor {
public interface JobRepository extends JpaRepository<Job, Long>, JpaSpecificationExecutor<Job> {
}
\ No newline at end of file
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* @author Zheng Jie
* @date 2018-12-17
*/
public interface MenuRepository extends JpaRepository<Menu, Long>, JpaSpecificationExecutor {
public interface MenuRepository extends JpaRepository<Menu, Long>, JpaSpecificationExecutor<Menu> {
/**
* findByName
* @param name
* @return
*/
Menu findByName(String name);
/**
* findByName
* @param name
* @return
*/
Menu findByComponentName(String name);
/**
* findByPid
* @param pid
* @return
*/
List<Menu> findByPid(long pid);
LinkedHashSet<Menu> findByRoles_IdOrderBySortAsc(Long id);
......
......@@ -9,19 +9,9 @@ import java.util.List;
* @author Zheng Jie
* @date 2018-12-03
*/
public interface PermissionRepository extends JpaRepository<Permission, Long>, JpaSpecificationExecutor {
public interface PermissionRepository extends JpaRepository<Permission, Long>, JpaSpecificationExecutor<Permission> {
/**
* findByName
* @param name
* @return
*/
Permission findByName(String name);
/**
* findByPid
* @param pid
* @return
*/
List<Permission> findByPid(long pid);
}
......@@ -5,20 +5,14 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.Set;
/**
* @author Zheng Jie
* @date 2018-12-03
*/
public interface RoleRepository extends JpaRepository<Role, Long>, JpaSpecificationExecutor {
public interface RoleRepository extends JpaRepository<Role, Long>, JpaSpecificationExecutor<Role> {
/**
* findByName
* @param name
* @return
*/
Role findByName(String name);
Set<Role> findByUsers_Id(Long id);
......
......@@ -4,12 +4,10 @@ import me.zhengjie.modules.system.domain.UserAvatar;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.Date;
/**
* @author Zheng Jie
* @date 2018-11-22
*/
public interface UserAvatarRepository extends JpaRepository<UserAvatar, Long>, JpaSpecificationExecutor {
public interface UserAvatarRepository extends JpaRepository<UserAvatar, Long>, JpaSpecificationExecutor<UserAvatar> {
}
package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.Date;
import java.util.List;
/**
* @author Zheng Jie
* @date 2018-11-22
*/
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor {
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
/**
* findByUsername
* @param username
* @return
*/
User findByUsername(String username);
/**
* findByEmail
* @param email
* @return
*/
User findByEmail(String email);
/**
* 修改密码
* @param username
* @param pass
*/
@Modifying
@Query(value = "update user set password = ?2 , last_password_reset_time = ?3 where username = ?1",nativeQuery = true)
void updatePass(String username, String pass, Date lastPasswordResetTime);
/**
* 修改头像
* @param username
* @param url
*/
@Modifying
@Query(value = "update user set avatar = ?2 where username = ?1",nativeQuery = true)
void updateAvatar(String username, String url);
/**
* 修改邮箱
* @param username
* @param email
*/
@Modifying
@Query(value = "update user set email = ?2 where username = ?1",nativeQuery = true)
void updateEmail(String username, String email);
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.DataScope;
import me.zhengjie.exception.BadRequestException;
......@@ -8,7 +10,6 @@ import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import me.zhengjie.modules.system.service.dto.DeptQueryCriteria;
import me.zhengjie.utils.ThrowableUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
......@@ -21,39 +22,46 @@ import java.util.List;
* @date 2019-03-25
*/
@RestController
@RequestMapping("api")
@Api(tags = "系统:部门管理")
@RequestMapping("/api/dept")
public class DeptController {
@Autowired
private DeptService deptService;
private final DeptService deptService;
@Autowired
private DataScope dataScope;
private final DataScope dataScope;
private static final String ENTITY_NAME = "dept";
public DeptController(DeptService deptService, DataScope dataScope) {
this.deptService = deptService;
this.dataScope = dataScope;
}
@Log("查询部门")
@GetMapping(value = "/dept")
@ApiOperation("查询部门")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_SELECT','DEPT_ALL','DEPT_SELECT')")
public ResponseEntity getDepts(DeptQueryCriteria criteria){
// 数据权限
criteria.setIds(dataScope.getDeptIds());
List<DeptDTO> deptDTOS = deptService.queryAll(criteria);
return new ResponseEntity(deptService.buildTree(deptDTOS),HttpStatus.OK);
return new ResponseEntity<>(deptService.buildTree(deptDTOS),HttpStatus.OK);
}
@Log("新增部门")
@PostMapping(value = "/dept")
@ApiOperation("新增部门")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','DEPT_ALL','DEPT_CREATE')")
public ResponseEntity create(@Validated @RequestBody Dept resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(deptService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(deptService.create(resources),HttpStatus.CREATED);
}
@Log("修改部门")
@PutMapping(value = "/dept")
@ApiOperation("修改部门")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','DEPT_ALL','DEPT_EDIT')")
public ResponseEntity update(@Validated(Dept.Update.class) @RequestBody Dept resources){
deptService.update(resources);
......@@ -61,7 +69,8 @@ public class DeptController {
}
@Log("删除部门")
@DeleteMapping(value = "/dept/{id}")
@ApiOperation("删除部门")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','DEPT_ALL','DEPT_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
try {
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Dict;
......@@ -17,34 +19,41 @@ import org.springframework.web.bind.annotation.*;
* @author Zheng Jie
* @date 2019-04-10
*/
@Api(tags = "系统:字典管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/dict")
public class DictController {
@Autowired
private DictService dictService;
private final DictService dictService;
private static final String ENTITY_NAME = "dict";
public DictController(DictService dictService) {
this.dictService = dictService;
}
@Log("查询字典")
@GetMapping(value = "/dict")
@ApiOperation("查询字典")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_SELECT')")
public ResponseEntity getDicts(DictQueryCriteria resources, Pageable pageable){
return new ResponseEntity(dictService.queryAll(resources,pageable),HttpStatus.OK);
return new ResponseEntity<>(dictService.queryAll(resources,pageable),HttpStatus.OK);
}
@Log("新增字典")
@PostMapping(value = "/dict")
@ApiOperation("新增字典")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_CREATE')")
public ResponseEntity create(@Validated @RequestBody Dict resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(dictService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(dictService.create(resources),HttpStatus.CREATED);
}
@Log("修改字典")
@PutMapping(value = "/dict")
@ApiOperation("修改字典")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_EDIT')")
public ResponseEntity update(@Validated(Dict.Update.class) @RequestBody Dict resources){
dictService.update(resources);
......@@ -52,7 +61,8 @@ public class DictController {
}
@Log("删除字典")
@DeleteMapping(value = "/dict/{id}")
@ApiOperation("删除字典")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
dictService.delete(id);
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.DictDetail;
......@@ -25,47 +27,55 @@ import java.util.stream.Collectors;
* @date 2019-04-10
*/
@RestController
@RequestMapping("api")
@Api(tags = "系统:字典详情管理")
@RequestMapping("/api/dictDetail")
public class DictDetailController {
@Autowired
private DictDetailService dictDetailService;
private final DictDetailService dictDetailService;
private static final String ENTITY_NAME = "dictDetail";
public DictDetailController(DictDetailService dictDetailService) {
this.dictDetailService = dictDetailService;
}
@Log("查询字典详情")
@GetMapping(value = "/dictDetail")
@ApiOperation("查询字典详情")
@GetMapping
public ResponseEntity getDictDetails(DictDetailQueryCriteria criteria,
@PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
String[] names = criteria.getDictName().split(",");
return new ResponseEntity(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(dictDetailService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("查询多个字典详情")
@GetMapping(value = "/dictDetail/map")
@ApiOperation("查询多个字典详情")
@GetMapping(value = "/map")
public ResponseEntity getDictDetailMaps(DictDetailQueryCriteria criteria,
@PageableDefault(value = 10, sort = {"sort"}, direction = Sort.Direction.ASC) Pageable pageable){
String[] names = criteria.getDictName().split(",");
Map map = new HashMap(names.length);
Map<String,Object> map = new HashMap<>(names.length);
for (String name : names) {
criteria.setDictName(name);
map.put(name,dictDetailService.queryAll(criteria,pageable).get("content"));
}
return new ResponseEntity(map,HttpStatus.OK);
return new ResponseEntity<>(map,HttpStatus.OK);
}
@Log("新增字典详情")
@PostMapping(value = "/dictDetail")
@ApiOperation("新增字典详情")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_CREATE')")
public ResponseEntity create(@Validated @RequestBody DictDetail resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(dictDetailService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(dictDetailService.create(resources),HttpStatus.CREATED);
}
@Log("修改字典详情")
@PutMapping(value = "/dictDetail")
@ApiOperation("修改字典详情")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_EDIT')")
public ResponseEntity update(@Validated(DictDetail.Update.class) @RequestBody DictDetail resources){
dictDetailService.update(resources);
......@@ -73,7 +83,8 @@ public class DictDetailController {
}
@Log("删除字典详情")
@DeleteMapping(value = "/dictDetail/{id}")
@ApiOperation("删除字典详情")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','DICT_ALL','DICT_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
dictDetailService.delete(id);
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.DataScope;
import me.zhengjie.exception.BadRequestException;
......@@ -21,40 +23,47 @@ import java.util.Set;
* @author Zheng Jie
* @date 2019-03-29
*/
@Api(tags = "系统:岗位管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/job")
public class JobController {
@Autowired
private JobService jobService;
private final JobService jobService;
@Autowired
private DataScope dataScope;
private final DataScope dataScope;
private static final String ENTITY_NAME = "job";
public JobController(JobService jobService, DataScope dataScope) {
this.jobService = jobService;
this.dataScope = dataScope;
}
@Log("查询岗位")
@GetMapping(value = "/job")
@ApiOperation("查询岗位")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_SELECT','USER_ALL','USER_SELECT')")
public ResponseEntity getJobs(JobQueryCriteria criteria,
Pageable pageable){
// 数据权限
criteria.setDeptIds(dataScope.getDeptIds());
return new ResponseEntity(jobService.queryAll(criteria, pageable),HttpStatus.OK);
return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK);
}
@Log("新增岗位")
@PostMapping(value = "/job")
@ApiOperation("新增岗位")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_CREATE')")
public ResponseEntity create(@Validated @RequestBody Job resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(jobService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(jobService.create(resources),HttpStatus.CREATED);
}
@Log("修改岗位")
@PutMapping(value = "/job")
@ApiOperation("修改岗位")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_EDIT')")
public ResponseEntity update(@Validated(Job.Update.class) @RequestBody Job resources){
jobService.update(resources);
......@@ -62,7 +71,8 @@ public class JobController {
}
@Log("删除岗位")
@DeleteMapping(value = "/job/{id}")
@ApiOperation("删除岗位")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','USERJOB_ALL','USERJOB_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
try {
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.exception.BadRequestException;
......@@ -10,7 +12,6 @@ import me.zhengjie.modules.system.service.dto.MenuDTO;
import me.zhengjie.modules.system.service.dto.MenuQueryCriteria;
import me.zhengjie.modules.system.service.dto.UserDTO;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
......@@ -24,63 +25,63 @@ import java.util.Set;
* @author Zheng Jie
* @date 2018-12-03
*/
@Api(tags = "系统:菜单管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/menus")
public class MenuController {
@Autowired
private MenuService menuService;
private final MenuService menuService;
@Autowired
private UserService userService;
private final UserService userService;
@Autowired
private RoleService roleService;
private final RoleService roleService;
private static final String ENTITY_NAME = "menu";
/**
* 构建前端路由所需要的菜单
* @return
*/
@GetMapping(value = "/menus/build")
public MenuController(MenuService menuService, UserService userService, RoleService roleService) {
this.menuService = menuService;
this.userService = userService;
this.roleService = roleService;
}
@ApiOperation("获取菜单树")
@GetMapping(value = "/build")
public ResponseEntity buildMenus(){
UserDTO user = userService.findByName(SecurityUtils.getUsername());
List<MenuDTO> menuDTOList = menuService.findByRoles(roleService.findByUsers_Id(user.getId()));
List<MenuDTO> menuDTOTree = (List<MenuDTO>)menuService.buildTree(menuDTOList).get("content");
return new ResponseEntity(menuService.buildMenus(menuDTOTree),HttpStatus.OK);
return new ResponseEntity<>(menuService.buildMenus((List<MenuDTO>) menuService.buildTree(menuDTOList).get("content")),HttpStatus.OK);
}
/**
* 返回全部的菜单
* @return
*/
@GetMapping(value = "/menus/tree")
@ApiOperation("返回全部的菜单")
@GetMapping(value = "/tree")
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_CREATE','MENU_EDIT','ROLES_SELECT','ROLES_ALL')")
public ResponseEntity getMenuTree(){
return new ResponseEntity(menuService.getMenuTree(menuService.findByPid(0L)),HttpStatus.OK);
return new ResponseEntity<>(menuService.getMenuTree(menuService.findByPid(0L)),HttpStatus.OK);
}
@Log("查询菜单")
@GetMapping(value = "/menus")
@ApiOperation("查询菜单")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_SELECT')")
public ResponseEntity getMenus(MenuQueryCriteria criteria){
List<MenuDTO> menuDTOList = menuService.queryAll(criteria);
return new ResponseEntity(menuService.buildTree(menuDTOList),HttpStatus.OK);
return new ResponseEntity<>(menuService.buildTree(menuDTOList),HttpStatus.OK);
}
@Log("新增菜单")
@PostMapping(value = "/menus")
@ApiOperation("新增菜单")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_CREATE')")
public ResponseEntity create(@Validated @RequestBody Menu resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(menuService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(menuService.create(resources),HttpStatus.CREATED);
}
@Log("修改菜单")
@PutMapping(value = "/menus")
@ApiOperation("修改菜单")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_EDIT')")
public ResponseEntity update(@Validated(Menu.Update.class) @RequestBody Menu resources){
menuService.update(resources);
......@@ -88,7 +89,8 @@ public class MenuController {
}
@Log("删除菜单")
@DeleteMapping(value = "/menus/{id}")
@ApiOperation("删除菜单")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
List<Menu> menuList = menuService.findByPid(id);
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.system.domain.Permission;
import me.zhengjie.exception.BadRequestException;
......@@ -7,13 +9,11 @@ import me.zhengjie.modules.system.service.PermissionService;
import me.zhengjie.modules.system.service.dto.PermissionDTO;
import me.zhengjie.modules.system.service.dto.PermissionQueryCriteria;
import me.zhengjie.modules.system.service.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
......@@ -22,48 +22,52 @@ import java.util.Set;
* @author Zheng Jie
* @date 2018-12-03
*/
@Api(tags = "系统:权限管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/permissions")
public class PermissionController {
@Autowired
private PermissionService permissionService;
private final PermissionService permissionService;
@Autowired
private PermissionMapper permissionMapper;
private final PermissionMapper permissionMapper;
private static final String ENTITY_NAME = "permission";
/**
* 返回全部的权限,新增角色时下拉选择
* @return
*/
@GetMapping(value = "/permissions/tree")
public PermissionController(PermissionService permissionService, PermissionMapper permissionMapper) {
this.permissionService = permissionService;
this.permissionMapper = permissionMapper;
}
@ApiOperation("返回全部的权限,新增角色时下拉选择")
@GetMapping(value = "/tree")
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_CREATE','PERMISSION_EDIT','ROLES_SELECT','ROLES_ALL')")
public ResponseEntity getTree(){
return new ResponseEntity(permissionService.getPermissionTree(permissionService.findByPid(0L)),HttpStatus.OK);
return new ResponseEntity<>(permissionService.getPermissionTree(permissionService.findByPid(0L)),HttpStatus.OK);
}
@Log("查询权限")
@GetMapping(value = "/permissions")
@ApiOperation("查询权限")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_SELECT')")
public ResponseEntity getPermissions(PermissionQueryCriteria criteria){
List<PermissionDTO> permissionDTOS = permissionService.queryAll(criteria);
return new ResponseEntity(permissionService.buildTree(permissionDTOS),HttpStatus.OK);
return new ResponseEntity<>(permissionService.buildTree(permissionDTOS),HttpStatus.OK);
}
@Log("新增权限")
@PostMapping(value = "/permissions")
@ApiOperation("新增权限")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_CREATE')")
public ResponseEntity create(@Validated @RequestBody Permission resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(permissionService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(permissionService.create(resources),HttpStatus.CREATED);
}
@Log("修改权限")
@PutMapping(value = "/permissions")
@ApiOperation("修改权限")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_EDIT')")
public ResponseEntity update(@Validated(Permission.Update.class) @RequestBody Permission resources){
permissionService.update(resources);
......@@ -71,7 +75,8 @@ public class PermissionController {
}
@Log("删除权限")
@DeleteMapping(value = "/permissions/{id}")
@ApiOperation("删除权限")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','PERMISSION_ALL','PERMISSION_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
List<Permission> permissions = permissionService.findByPid(id);
......
package me.zhengjie.modules.system.rest;
import cn.hutool.core.lang.Dict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.exception.BadRequestException;
......@@ -9,15 +11,12 @@ import me.zhengjie.modules.system.service.dto.RoleQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDTO;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ThrowableUtil;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Collections;
......@@ -28,61 +27,62 @@ import java.util.stream.Collectors;
* @author Zheng Jie
* @date 2018-12-03
*/
@Api(tags = "系统:角色管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/roles")
public class RoleController {
@Autowired
private RoleService roleService;
private final RoleService roleService;
private static final String ENTITY_NAME = "role";
/**
* 获取单个role
* @param id
* @return
*/
@GetMapping(value = "/roles/{id}")
public RoleController(RoleService roleService) {
this.roleService = roleService;
}
@ApiOperation("获取单个role")
@GetMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_SELECT')")
public ResponseEntity getRoles(@PathVariable Long id){
return new ResponseEntity(roleService.findById(id), HttpStatus.OK);
return new ResponseEntity<>(roleService.findById(id), HttpStatus.OK);
}
/**
* 返回全部的角色,新增用户时下拉选择
* @return
*/
@GetMapping(value = "/roles/all")
@ApiOperation("返回全部的角色")
@GetMapping(value = "/all")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','USER_ALL','USER_CREATE','USER_EDIT')")
public ResponseEntity getAll(@PageableDefault(value = 2000, sort = {"level"}, direction = Sort.Direction.ASC) Pageable pageable){
return new ResponseEntity(roleService.queryAll(pageable),HttpStatus.OK);
return new ResponseEntity<>(roleService.queryAll(pageable),HttpStatus.OK);
}
@Log("查询角色")
@GetMapping(value = "/roles")
@ApiOperation("查询角色")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_SELECT')")
public ResponseEntity getRoles(RoleQueryCriteria criteria, Pageable pageable){
return new ResponseEntity(roleService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(roleService.queryAll(criteria,pageable),HttpStatus.OK);
}
@GetMapping(value = "/roles/level")
@ApiOperation("获取用户级别")
@GetMapping(value = "/level")
public ResponseEntity getLevel(){
List<Integer> levels = roleService.findByUsers_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList());
return new ResponseEntity(Dict.create().set("level", Collections.min(levels)),HttpStatus.OK);
return new ResponseEntity<>(Dict.create().set("level", Collections.min(levels)),HttpStatus.OK);
}
@Log("新增角色")
@PostMapping(value = "/roles")
@ApiOperation("新增角色")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_CREATE')")
public ResponseEntity create(@Validated @RequestBody Role resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
return new ResponseEntity(roleService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(roleService.create(resources),HttpStatus.CREATED);
}
@Log("修改角色")
@PutMapping(value = "/roles")
@ApiOperation("修改角色")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_EDIT')")
public ResponseEntity update(@Validated(Role.Update.class) @RequestBody Role resources){
roleService.update(resources);
......@@ -90,7 +90,8 @@ public class RoleController {
}
@Log("修改角色权限")
@PutMapping(value = "/roles/permission")
@ApiOperation("修改角色权限")
@PutMapping(value = "/permission")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_EDIT')")
public ResponseEntity updatePermission(@RequestBody Role resources){
roleService.updatePermission(resources,roleService.findById(resources.getId()));
......@@ -98,7 +99,8 @@ public class RoleController {
}
@Log("修改角色菜单")
@PutMapping(value = "/roles/menu")
@ApiOperation("修改角色菜单")
@PutMapping(value = "/menu")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_EDIT')")
public ResponseEntity updateMenu(@RequestBody Role resources){
roleService.updateMenu(resources,roleService.findById(resources.getId()));
......@@ -106,7 +108,8 @@ public class RoleController {
}
@Log("删除角色")
@DeleteMapping(value = "/roles/{id}")
@ApiOperation("删除角色")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','ROLES_ALL','ROLES_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
try {
......
package me.zhengjie.modules.system.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.zhengjie.aop.log.Log;
import me.zhengjie.config.DataScope;
import me.zhengjie.domain.Picture;
import me.zhengjie.domain.VerificationCode;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.BadRequestException;
......@@ -11,11 +12,9 @@ import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.RoleSmallDTO;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
import me.zhengjie.service.PictureService;
import me.zhengjie.service.VerificationCodeService;
import me.zhengjie.utils.*;
import me.zhengjie.modules.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
......@@ -35,37 +34,40 @@ import java.util.stream.Collectors;
* @author Zheng Jie
* @date 2018-11-23
*/
@Api(tags = "系统:用户管理")
@RestController
@RequestMapping("api")
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
private final UserService userService;
@Autowired
private PictureService pictureService;
private final DataScope dataScope;
@Autowired
private DataScope dataScope;
private final DeptService deptService;
@Autowired
private DeptService deptService;
private final RoleService roleService;
@Autowired
private RoleService roleService;
private final VerificationCodeService verificationCodeService;
@Autowired
private VerificationCodeService verificationCodeService;
public UserController(UserService userService, DataScope dataScope, DeptService deptService, RoleService roleService, VerificationCodeService verificationCodeService) {
this.userService = userService;
this.dataScope = dataScope;
this.deptService = deptService;
this.roleService = roleService;
this.verificationCodeService = verificationCodeService;
}
@Log("导出用户数据")
@GetMapping(value = "/users/download")
@ApiOperation("导出用户数据")
@GetMapping(value = "/download")
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_SELECT')")
public void update(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
userService.download(userService.queryAll(criteria), response);
}
@Log("查询用户")
@GetMapping(value = "/users")
@ApiOperation("查询用户")
@GetMapping
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_SELECT')")
public ResponseEntity getUsers(UserQueryCriteria criteria, Pageable pageable){
Set<Long> deptSet = new HashSet<>();
......@@ -89,27 +91,29 @@ public class UserController {
// 若无交集,则代表无数据权限
criteria.setDeptIds(result);
if(result.size() == 0){
return new ResponseEntity(PageUtil.toPage(null,0),HttpStatus.OK);
} else return new ResponseEntity(userService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(PageUtil.toPage(null,0),HttpStatus.OK);
} else return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
// 否则取并集
} else {
result.addAll(deptSet);
result.addAll(deptIds);
criteria.setDeptIds(result);
return new ResponseEntity(userService.queryAll(criteria,pageable),HttpStatus.OK);
return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
}
}
@Log("新增用户")
@PostMapping(value = "/users")
@ApiOperation("新增用户")
@PostMapping
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_CREATE')")
public ResponseEntity create(@Validated @RequestBody User resources){
checkLevel(resources);
return new ResponseEntity(userService.create(resources),HttpStatus.CREATED);
return new ResponseEntity<>(userService.create(resources),HttpStatus.CREATED);
}
@Log("修改用户")
@PutMapping(value = "/users")
@ApiOperation("修改用户")
@PutMapping
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_EDIT')")
public ResponseEntity update(@Validated(User.Update.class) @RequestBody User resources){
checkLevel(resources);
......@@ -118,7 +122,8 @@ public class UserController {
}
@Log("删除用户")
@DeleteMapping(value = "/users/{id}")
@ApiOperation("删除用户")
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyRole('ADMIN','USER_ALL','USER_DELETE')")
public ResponseEntity delete(@PathVariable Long id){
Integer currentLevel = Collections.min(roleService.findByUsers_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
......@@ -131,12 +136,8 @@ public class UserController {
return new ResponseEntity(HttpStatus.OK);
}
/**
* 修改密码
* @param user
* @return
*/
@PostMapping(value = "/users/updatePass")
@ApiOperation("修改密码")
@PostMapping(value = "/updatePass")
public ResponseEntity updatePass(@RequestBody UserPassVo user){
UserDetails userDetails = SecurityUtils.getUserDetails();
if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getOldPass()))){
......@@ -149,25 +150,16 @@ public class UserController {
return new ResponseEntity(HttpStatus.OK);
}
/**
* 修改头像
* @param file
* @return
*/
@PostMapping(value = "/users/updateAvatar")
@ApiOperation("修改头像")
@PostMapping(value = "/updateAvatar")
public ResponseEntity updateAvatar(@RequestParam MultipartFile file){
userService.updateAvatar(file);
return new ResponseEntity(HttpStatus.OK);
}
/**
* 修改邮箱
* @param user
* @param user
* @return
*/
@Log("修改邮箱")
@PostMapping(value = "/users/updateEmail/{code}")
@ApiOperation("修改邮箱")
@PostMapping(value = "/updateEmail/{code}")
public ResponseEntity updateEmail(@PathVariable String code,@RequestBody User user){
UserDetails userDetails = SecurityUtils.getUserDetails();
if(!userDetails.getPassword().equals(EncryptUtils.encryptPassword(user.getPassword()))){
......@@ -183,7 +175,7 @@ public class UserController {
/**
* 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
* @param resources
* @param resources /
*/
private void checkLevel(User resources) {
Integer currentLevel = Collections.min(roleService.findByUsers_Id(SecurityUtils.getUserId()).stream().map(RoleSmallDTO::getLevel).collect(Collectors.toList()));
......
......@@ -3,10 +3,6 @@ package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.dto.DeptDTO;
import me.zhengjie.modules.system.service.dto.DeptQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
import java.util.Set;
......@@ -14,61 +10,20 @@ import java.util.Set;
* @author Zheng Jie
* @date 2019-03-25
*/
@CacheConfig(cacheNames = "dept")
public interface DeptService {
/**
* queryAll
* @param criteria
* @return
*/
@Cacheable
List<DeptDTO> queryAll(DeptQueryCriteria criteria);
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
DeptDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
DeptDTO create(Dept resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Dept resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
/**
* buildTree
* @param deptDTOS
* @return
*/
@Cacheable
Object buildTree(List<DeptDTO> deptDTOS);
/**
* findByPid
* @param pid
* @return
*/
@Cacheable
List<Dept> findByPid(long pid);
Set<Dept> findByRoleIds(Long id);
......
......@@ -3,50 +3,22 @@ package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import java.util.Map;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
@CacheConfig(cacheNames = "dictDetail")
public interface DictDetailService {
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
DictDetailDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
DictDetailDTO create(DictDetail resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(DictDetail resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
@Cacheable
Map queryAll(DictDetailQueryCriteria criteria, Pageable pageable);
}
\ No newline at end of file
......@@ -3,54 +3,21 @@ package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.dto.DictDTO;
import me.zhengjie.modules.system.service.dto.DictQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
@CacheConfig(cacheNames = "dict")
public interface DictService {
/**
* 查询
* @param dict
* @param pageable
* @return
*/
@Cacheable
Object queryAll(DictQueryCriteria dict, Pageable pageable);
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
DictDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
DictDTO create(Dict resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Dict resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
}
\ No newline at end of file
......@@ -3,53 +3,21 @@ package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.dto.JobDTO;
import me.zhengjie.modules.system.service.dto.JobQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
/**
* @author Zheng Jie
* @date 2019-03-29
*/
@CacheConfig(cacheNames = "job")
public interface JobService {
/**
* findById
* @param id
* @return
*/
@Cacheable(key = "#p0")
JobDTO findById(Long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
JobDTO create(Job resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Job resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
/**
* queryAll
* @param criteria
* @param pageable
* @return
*/
Object queryAll(JobQueryCriteria criteria, Pageable pageable);
}
\ No newline at end of file
......@@ -4,9 +4,6 @@ import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.service.dto.MenuDTO;
import me.zhengjie.modules.system.service.dto.MenuQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
import java.util.Map;
import java.util.Set;
......@@ -15,90 +12,29 @@ import java.util.Set;
* @author Zheng Jie
* @date 2018-12-17
*/
@CacheConfig(cacheNames = "menu")
public interface MenuService {
/**
* queryAll
* @param criteria
* @return
*/
@Cacheable
List<MenuDTO> queryAll(MenuQueryCriteria criteria);
/**
* get
* @param id
* @return
*/
@Cacheable(key = "#p0")
MenuDTO findById(long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
MenuDTO create(Menu resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Menu resources);
/**
* getDeleteMenus
* @param menuList
* @param menuSet
* @return
*/
Set<Menu> getDeleteMenus(List<Menu> menuList, Set<Menu> menuSet);
/**
* permission tree
* @return
*/
@Cacheable(key = "'tree'")
Object getMenuTree(List<Menu> menus);
/**
* findByPid
* @param pid
* @return
*/
@Cacheable(key = "'pid:'+#p0")
List<Menu> findByPid(long pid);
/**
* build Tree
* @param menuDTOS
* @return
*/
Map buildTree(List<MenuDTO> menuDTOS);
Map<String,Object> buildTree(List<MenuDTO> menuDTOS);
/**
* findByRoles
* @param roles
* @return
*/
List<MenuDTO> findByRoles(List<RoleSmallDTO> roles);
/**
* buildMenus
* @param byRoles
* @return
*/
Object buildMenus(List<MenuDTO> byRoles);
Menu findOne(Long id);
/**
* delete
* @param menuSet
*/
@CacheEvict(allEntries = true)
void delete(Set<Menu> menuSet);
}
......@@ -3,10 +3,6 @@ package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Permission;
import me.zhengjie.modules.system.service.dto.PermissionDTO;
import me.zhengjie.modules.system.service.dto.PermissionQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.List;
import java.util.Set;
......@@ -14,68 +10,22 @@ import java.util.Set;
* @author Zheng Jie
* @date 2018-12-08
*/
@CacheConfig(cacheNames = "permission")
public interface PermissionService {
/**
* get
* @param id
* @return
*/
@Cacheable(key = "#p0")
PermissionDTO findById(long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
PermissionDTO create(Permission resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Permission resources);
/**
* delete
* @param permissions
*/
@CacheEvict(allEntries = true)
void delete(Set<Permission> permissions);
/**
* permission tree
* @return
*/
@Cacheable(key = "'tree'")
Object getPermissionTree(List<Permission> permissions);
/**
* findByPid
* @param pid
* @return
*/
@Cacheable(key = "'pid:'+#p0")
List<Permission> findByPid(long pid);
/**
* build Tree
* @param permissionDTOS
* @return
*/
@Cacheable
Object buildTree(List<PermissionDTO> permissionDTOS);
/**
* queryAll
* @param criteria
* @return
*/
@Cacheable
List<PermissionDTO> queryAll(PermissionQueryCriteria criteria);
Set<Permission> getDeletePermission(List<Permission> permissions, Set<Permission> permissionSet);
......
......@@ -4,11 +4,7 @@ import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.service.dto.RoleDTO;
import me.zhengjie.modules.system.service.dto.RoleQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDTO;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Set;
......@@ -16,95 +12,31 @@ import java.util.Set;
* @author Zheng Jie
* @date 2018-12-03
*/
@CacheConfig(cacheNames = "role")
public interface RoleService {
/**
* get
* @param id
* @return
*/
@Cacheable(key = "#p0")
RoleDTO findById(long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
RoleDTO create(Role resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(Role resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
/**
* key的名称如有修改,请同步修改 UserServiceImpl 中的 update 方法
* findByUsers_Id
* @param id
* @return
*/
@Cacheable(key = "'findByUsers_Id:' + #p0")
List<RoleSmallDTO> findByUsers_Id(Long id);
@Cacheable
Integer findByRoles(Set<Role> roles);
/**
* updatePermission
* @param resources
* @param roleDTO
*/
@CacheEvict(allEntries = true)
void updatePermission(Role resources, RoleDTO roleDTO);
/**
* updateMenu
* @param resources
* @param roleDTO
*/
@CacheEvict(allEntries = true)
void updateMenu(Role resources, RoleDTO roleDTO);
@CacheEvict(allEntries = true)
void untiedMenu(Long id);
/**
* queryAll
* @param pageable
* @return
*/
@Cacheable
Object queryAll(Pageable pageable);
/**
* queryAll
* @param pageable
* @param criteria
* @return
*/
@Cacheable
Object queryAll(RoleQueryCriteria criteria, Pageable pageable);
/**
* queryAll
* @param criteria
* @return
*/
@Cacheable
List<RoleDTO> queryAll(RoleQueryCriteria criteria);
@CacheEvict(allEntries = true)
void untiedPermission(Long id);
}
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.system.service.dto.UserDTO;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
......@@ -18,74 +13,26 @@ import java.util.List;
* @author Zheng Jie
* @date 2018-11-23
*/
@CacheConfig(cacheNames = "user")
public interface UserService {
/**
* get
* @param id
* @return
*/
@Cacheable(key = "#p0")
UserDTO findById(long id);
/**
* create
* @param resources
* @return
*/
@CacheEvict(allEntries = true)
UserDTO create(User resources);
/**
* update
* @param resources
*/
@CacheEvict(allEntries = true)
void update(User resources);
/**
* delete
* @param id
*/
@CacheEvict(allEntries = true)
void delete(Long id);
/**
* findByName
* @param userName
* @return
*/
@Cacheable(key = "'loadUserByUsername:'+#p0")
UserDTO findByName(String userName);
/**
* 修改密码
* @param username
* @param encryptPassword
*/
@CacheEvict(allEntries = true)
void updatePass(String username, String encryptPassword);
/**
* 修改头像
* @param file
*/
@CacheEvict(allEntries = true)
void updateAvatar(MultipartFile file);
/**
* 修改邮箱
* @param username
* @param email
*/
@CacheEvict(allEntries = true)
void updateEmail(String username, String email);
@Cacheable
Object queryAll(UserQueryCriteria criteria, Pageable pageable);
@Cacheable
List<UserDTO> queryAll(UserQueryCriteria criteria);
void download(List<UserDTO> queryAll, HttpServletResponse response) throws IOException;
......
......@@ -15,22 +15,16 @@ import java.util.List;
@Data
public class DeptDTO implements Serializable {
/**
* ID
*/
// ID
private Long id;
/**
* 名称
*/
// 名称
private String name;
@NotNull
private Boolean enabled;
/**
* 上级部门
*/
// 上级部门
private Long pid;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
......
......@@ -10,13 +10,7 @@ import java.io.Serializable;
@Data
public class DeptSmallDTO implements Serializable {
/**
* ID
*/
private Long id;
/**
* 名称
*/
private String name;
}
\ No newline at end of file
......@@ -12,13 +12,7 @@ public class DictDTO implements Serializable {
private Long id;
/**
* 字典名称
*/
private String name;
/**
* 描述
*/
private String remark;
}
......@@ -12,18 +12,9 @@ public class DictDetailDTO implements Serializable {
private Long id;
/**
* 字典标签
*/
private String label;
/**
* 字典值
*/
private String value;
/**
* 排序
*/
private String sort;
}
\ No newline at end of file
......@@ -16,33 +16,18 @@ import java.io.Serializable;
@NoArgsConstructor
public class JobDTO implements Serializable {
/**
* ID
*/
private Long id;
private Long sort;
/**
* 名称
*/
private String name;
/**
* 状态
*/
private Boolean enabled;
private DeptDTO dept;
/**
* 如果分公司存在相同部门,则显示上级部门名称
*/
private String deptSuperiorName;
/**
* 创建日期
*/
private Timestamp createTime;
public JobDTO(String name, Boolean enabled) {
......
......@@ -12,13 +12,7 @@ import java.io.Serializable;
@NoArgsConstructor
public class JobSmallDTO implements Serializable {
/**
* ID
*/
private Long id;
/**
* 名称
*/
private String name;
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册