🎨 代码优化

🎨 代码优化
This commit is contained in:
ronger 2022-01-13 20:55:05 +08:00 committed by GitHub
commit 9e07b7d0be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 76 additions and 80 deletions

View File

@ -1,5 +1,6 @@
package com.rymcu.forest.config; package com.rymcu.forest.config;
import com.rymcu.forest.util.Utils;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Aspect;
@ -48,14 +49,12 @@ public class WebLogAspect {
// 接收到请求记录请求内容 // 接收到请求记录请求内容
logger.info("WebLogAspect.doBefore()"); logger.info("WebLogAspect.doBefore()");
ServletRequestAttributes attributes = ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest(); HttpServletRequest request = attributes.getRequest();
// 记录下请求内容 // 记录下请求内容
logger.info("URL : " + request.getRequestURL().toString()); logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr()); logger.info("IP : " + Utils.getIpAddress(request));
logger.info( logger.info(
"CLASS_METHOD : " "CLASS_METHOD : "
+ joinPoint.getSignature().getDeclaringTypeName() + joinPoint.getSignature().getDeclaringTypeName()

View File

@ -37,19 +37,20 @@ public class Utils {
String plain = Encodes.unescapeHtml(plainPassword); String plain = Encodes.unescapeHtml(plainPassword);
byte[] salt = Digests.generateSalt(SALT_SIZE); byte[] salt = Digests.generateSalt(SALT_SIZE);
byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS); byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword); return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
} }
/** /**
*一般检查工具密码比对 add by xlf 2018-11-8 * 一般检查工具密码比对 add by xlf 2018-11-8
*
* @param pwd * @param pwd
* @param enpwd 加密的密码 * @param enpwd 加密的密码
* @return * @return
*/ */
public static boolean comparePwd(String pwd,String enpwd){ public static boolean comparePwd(String pwd, String enpwd) {
byte[] salt = Encodes.decodeHex(enpwd.substring(0,16)); byte[] salt = Encodes.decodeHex(enpwd.substring(0, 16));
byte[] hashPassword = Digests.sha1(pwd.getBytes(), salt, HASH_INTERATIONS); byte[] hashPassword = Digests.sha1(pwd.getBytes(), salt, HASH_INTERATIONS);
return enpwd.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword)); return enpwd.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
} }
public static User getCurrentUser() { public static User getCurrentUser() {
@ -57,33 +58,34 @@ public class Utils {
} }
public static Session getSession() { public static Session getSession() {
try{ try {
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession(false); Session session = subject.getSession(false);
if (session == null){ if (session == null) {
session = subject.getSession(); session = subject.getSession();
} }
if (session != null){ if (session != null) {
return session; return session;
} }
subject.logout(); subject.logout();
}catch (InvalidSessionException e){ } catch (InvalidSessionException e) {
} }
return null; return null;
} }
public static Integer genCode() { public static Integer genCode() {
Integer code = (int)((Math.random()*9+1)*100000); Integer code = (int) ((Math.random() * 9 + 1) * 100000);
return code; return code;
} }
/** /**
* 获取配置文件内属性 * 获取配置文件内属性
*
* @param key 键值 * @param key 键值
* @return 属性值 * @return 属性值
* */ */
public static String getProperty(String key){ public static String getProperty(String key) {
return env.getProperty(key); return env.getProperty(key);
} }
@ -99,24 +101,24 @@ public class Utils {
LocalDate today = LocalDate.now(); LocalDate today = LocalDate.now();
Period p = Period.between(oldLocalDate, today); Period p = Period.between(oldLocalDate, today);
if(p.getYears() > 0){ if (p.getYears() > 0) {
timeAgo = p.getYears()+" 年前 "; timeAgo = p.getYears() + " 年前 ";
}else if(p.getMonths() > 0){ } else if (p.getMonths() > 0) {
timeAgo = p.getMonths()+" 月前 "; timeAgo = p.getMonths() + " 月前 ";
}else if(p.getDays() > 0){ } else if (p.getDays() > 0) {
timeAgo = p.getDays()+" 天前 "; timeAgo = p.getDays() + " 天前 ";
}else { } else {
long to = System.currentTimeMillis(); long to = System.currentTimeMillis();
long from = date.getTime(); long from = date.getTime();
int hours = (int) ((to - from)/(1000 * 60 * 60)); int hours = (int) ((to - from) / (1000 * 60 * 60));
if(hours > 0){ if (hours > 0) {
timeAgo = hours+" 小时前 "; timeAgo = hours + " 小时前 ";
}else { } else {
int minutes = (int) ((to - from)/(1000 * 60)); int minutes = (int) ((to - from) / (1000 * 60));
if(minutes == 0){ if (minutes == 0) {
timeAgo = " 刚刚 "; timeAgo = " 刚刚 ";
}else { } else {
timeAgo = minutes+" 分钟前 "; timeAgo = minutes + " 分钟前 ";
} }
} }
} }
@ -125,13 +127,13 @@ public class Utils {
public static Map getPagination(PageInfo pageInfo) { public static Map getPagination(PageInfo pageInfo) {
Map pagination = new HashMap(3); Map pagination = new HashMap(3);
pagination.put("pageSize",pageInfo.getPageSize()); pagination.put("pageSize", pageInfo.getPageSize());
pagination.put("total",pageInfo.getTotal()); pagination.put("total", pageInfo.getTotal());
pagination.put("currentPage",pageInfo.getPageNum()); pagination.put("currentPage", pageInfo.getPageNum());
return pagination; return pagination;
} }
public static void main(String[] args){ public static void main(String[] args) {
String s = entryptPassword("admin"); String s = entryptPassword("admin");
System.out.println(s); System.out.println(s);
} }
@ -140,9 +142,9 @@ public class Utils {
Map map = new HashMap(2); Map map = new HashMap(2);
map.put("articles", pageInfo.getList()); map.put("articles", pageInfo.getList());
Map pagination = new HashMap(4); Map pagination = new HashMap(4);
pagination.put("pageSize",pageInfo.getPageSize()); pagination.put("pageSize", pageInfo.getPageSize());
pagination.put("total",pageInfo.getTotal()); pagination.put("total", pageInfo.getTotal());
pagination.put("currentPage",pageInfo.getPageNum()); pagination.put("currentPage", pageInfo.getPageNum());
map.put("pagination", pagination); map.put("pagination", pagination);
return map; return map;
} }
@ -151,9 +153,9 @@ public class Utils {
Map map = new HashMap(2); Map map = new HashMap(2);
map.put("users", pageInfo.getList()); map.put("users", pageInfo.getList());
Map pagination = new HashMap(4); Map pagination = new HashMap(4);
pagination.put("pageSize",pageInfo.getPageSize()); pagination.put("pageSize", pageInfo.getPageSize());
pagination.put("total",pageInfo.getTotal()); pagination.put("total", pageInfo.getTotal());
pagination.put("currentPage",pageInfo.getPageNum()); pagination.put("currentPage", pageInfo.getPageNum());
map.put("pagination", pagination); map.put("pagination", pagination);
return map; return map;
} }
@ -162,9 +164,9 @@ public class Utils {
Map map = new HashMap(2); Map map = new HashMap(2);
map.put("portfolios", pageInfo.getList()); map.put("portfolios", pageInfo.getList());
Map pagination = new HashMap(4); Map pagination = new HashMap(4);
pagination.put("pageSize",pageInfo.getPageSize()); pagination.put("pageSize", pageInfo.getPageSize());
pagination.put("total",pageInfo.getTotal()); pagination.put("total", pageInfo.getTotal());
pagination.put("currentPage",pageInfo.getPageNum()); pagination.put("currentPage", pageInfo.getPageNum());
map.put("pagination", pagination); map.put("pagination", pagination);
return map; return map;
} }
@ -173,9 +175,9 @@ public class Utils {
Map map = new HashMap(2); Map map = new HashMap(2);
map.put("notifications", pageInfo.getList()); map.put("notifications", pageInfo.getList());
Map pagination = new HashMap(4); Map pagination = new HashMap(4);
pagination.put("pageSize",pageInfo.getPageSize()); pagination.put("pageSize", pageInfo.getPageSize());
pagination.put("total",pageInfo.getTotal()); pagination.put("total", pageInfo.getTotal());
pagination.put("currentPage",pageInfo.getPageNum()); pagination.put("currentPage", pageInfo.getPageNum());
map.put("pagination", pagination); map.put("pagination", pagination);
return map; return map;
} }
@ -202,16 +204,16 @@ public class Utils {
ip = ip.substring(0, ip.indexOf(",")).trim(); ip = ip.substring(0, ip.indexOf(",")).trim();
} }
return ip; return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
} }
public static Map getNotificationDTOsGlobalResult(PageInfo<NotificationDTO> pageInfo) { public static Map getNotificationDTOsGlobalResult(PageInfo<NotificationDTO> pageInfo) {
Map map = new HashMap(2); Map map = new HashMap(2);
map.put("notifications", pageInfo.getList()); map.put("notifications", pageInfo.getList());
Map pagination = new HashMap(4); Map pagination = new HashMap(4);
pagination.put("pageSize",pageInfo.getPageSize()); pagination.put("pageSize", pageInfo.getPageSize());
pagination.put("total",pageInfo.getTotal()); pagination.put("total", pageInfo.getTotal());
pagination.put("currentPage",pageInfo.getPageNum()); pagination.put("currentPage", pageInfo.getPageNum());
map.put("pagination", pagination); map.put("pagination", pagination);
return map; return map;
} }

View File

@ -115,11 +115,7 @@ public class UploadController {
if (multipartFile == null) { if (multipartFile == null) {
return GlobalResultGenerator.genErrorResult("请选择要上传的文件"); return GlobalResultGenerator.genErrorResult("请选择要上传的文件");
} }
//todo 无法获取当前登录用户 TokenUser tokenUser = getTokenUser(request);
// User user = UserUtils.getCurrentUserByToken();
// if (Objects.isNull(user)) {
// throw new BaseApiException(ErrorCode.INVALID_TOKEN);
// }
Map data = new HashMap(2); Map data = new HashMap(2);
String md5 = DigestUtils.md5DigestAsHex(multipartFile.getInputStream()); String md5 = DigestUtils.md5DigestAsHex(multipartFile.getInputStream());
String fileUrl = forestFileService.getFileUrlByMd5(md5); String fileUrl = forestFileService.getFileUrlByMd5(md5);
@ -146,7 +142,7 @@ public class UploadController {
File saveFile = new File(savePath); File saveFile = new File(savePath);
try { try {
FileCopyUtils.copy(multipartFile.getBytes(), saveFile); FileCopyUtils.copy(multipartFile.getBytes(), saveFile);
forestFileService.insertForestFile(fileUrl, savePath, md5, 1); forestFileService.insertForestFile(fileUrl, savePath, md5, tokenUser.getIdUser());
data.put("url", fileUrl); data.put("url", fileUrl);
} catch (IOException e) { } catch (IOException e) {
data.put("message", "上传失败!"); data.put("message", "上传失败!");
@ -158,11 +154,7 @@ public class UploadController {
@PostMapping("/file/batch") @PostMapping("/file/batch")
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public GlobalResult batchFileUpload(@RequestParam(value = "file[]", required = false) MultipartFile[] multipartFiles, @RequestParam(defaultValue = "1") Integer type, HttpServletRequest request) throws BaseApiException { public GlobalResult batchFileUpload(@RequestParam(value = "file[]", required = false) MultipartFile[] multipartFiles, @RequestParam(defaultValue = "1") Integer type, HttpServletRequest request) throws BaseApiException {
//todo 无法获取当前登录用户 TokenUser tokenUser = getTokenUser(request);
// User user = UserUtils.getCurrentUserByToken();
// if (Objects.isNull(user)) {
// throw new BaseApiException(ErrorCode.INVALID_TOKEN);
// }
String typePath = getTypePath(type); String typePath = getTypePath(type);
//图片存储路径 //图片存储路径
String ctxHeadPicPath = env.getProperty("resource.pic-path"); String ctxHeadPicPath = env.getProperty("resource.pic-path");
@ -173,7 +165,7 @@ public class UploadController {
} }
String localPath = Utils.getProperty("resource.file-path") + "/" + typePath + "/"; String localPath = Utils.getProperty("resource.file-path") + "/" + typePath + "/";
Map succMap = new HashMap(10); Map successMap = new HashMap(16);
Set errFiles = new HashSet(); Set errFiles = new HashSet();
for (int i = 0, len = multipartFiles.length; i < len; i++) { for (int i = 0, len = multipartFiles.length; i < len; i++) {
@ -187,14 +179,14 @@ public class UploadController {
String md5 = DigestUtils.md5DigestAsHex(in); String md5 = DigestUtils.md5DigestAsHex(in);
String fileUrl = forestFileService.getFileUrlByMd5(md5); String fileUrl = forestFileService.getFileUrlByMd5(md5);
if (StringUtils.isNotEmpty(fileUrl)) { if (StringUtils.isNotEmpty(fileUrl)) {
succMap.put(orgName, fileUrl); successMap.put(orgName, fileUrl);
continue; continue;
} }
fileUrl = localPath + fileName; fileUrl = localPath + fileName;
FileCopyUtils.copy(in, out); FileCopyUtils.copy(in, out);
forestFileService.insertForestFile(fileUrl, savePath, md5, 1); forestFileService.insertForestFile(fileUrl, savePath, md5, tokenUser.getIdUser());
succMap.put(orgName, localPath + fileName); successMap.put(orgName, localPath + fileName);
} catch (IOException e) { } catch (IOException e) {
errFiles.add(orgName); errFiles.add(orgName);
} }
@ -203,34 +195,37 @@ public class UploadController {
} }
Map data = new HashMap(2); Map data = new HashMap(2);
data.put("errFiles", errFiles); data.put("errFiles", errFiles);
data.put("succMap", succMap); data.put("succMap", successMap);
return GlobalResultGenerator.genSuccessResult(data); return GlobalResultGenerator.genSuccessResult(data);
} }
private TokenUser getTokenUser(HttpServletRequest request) throws BaseApiException {
String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
if (StringUtils.isBlank(authHeader)) {
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
return UserUtils.getTokenUser(authHeader);
}
@GetMapping("/simple/token") @GetMapping("/simple/token")
public GlobalResult uploadSimpleToken(HttpServletRequest request) throws BaseApiException { public GlobalResult uploadSimpleToken(HttpServletRequest request) throws BaseApiException {
String authHeader = request.getHeader(JwtConstants.AUTHORIZATION); return getUploadToken(request, UPLOAD_SIMPLE_URL);
if (StringUtils.isBlank(authHeader)) {
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
TokenUser tokenUser = UserUtils.getTokenUser(authHeader);
Map map = new HashMap(2);
map.put("uploadToken", tokenUser.getToken());
map.put("uploadURL", UPLOAD_SIMPLE_URL);
map.put("linkToImageURL", LINK_TO_IMAGE_URL);
return GlobalResultGenerator.genSuccessResult(map);
} }
@GetMapping("/token") @GetMapping("/token")
public GlobalResult uploadToken(HttpServletRequest request) throws BaseApiException { public GlobalResult uploadToken(HttpServletRequest request) throws BaseApiException {
return getUploadToken(request, UPLOAD_URL);
}
private GlobalResult getUploadToken(HttpServletRequest request, String uploadUrl) throws BaseApiException {
String authHeader = request.getHeader(JwtConstants.AUTHORIZATION); String authHeader = request.getHeader(JwtConstants.AUTHORIZATION);
if (StringUtils.isBlank(authHeader)) { if (StringUtils.isBlank(authHeader)) {
throw new BaseApiException(ErrorCode.UNAUTHORIZED); throw new BaseApiException(ErrorCode.UNAUTHORIZED);
} }
TokenUser tokenUser = UserUtils.getTokenUser(authHeader); TokenUser tokenUser = UserUtils.getTokenUser(authHeader);
Map map = new HashMap(2); Map map = new HashMap(4);
map.put("uploadToken", tokenUser.getToken()); map.put("uploadToken", tokenUser.getToken());
map.put("uploadURL", UPLOAD_URL); map.put("uploadURL", uploadUrl);
map.put("linkToImageURL", LINK_TO_IMAGE_URL); map.put("linkToImageURL", LINK_TO_IMAGE_URL);
return GlobalResultGenerator.genSuccessResult(map); return GlobalResultGenerator.genSuccessResult(map);
} }