调整代码接口 以及 完善接口

This commit is contained in:
TinyAnts
2022-04-01 18:35:13 +08:00
parent 962a37ee2a
commit 7ca0904698
57 changed files with 1355 additions and 575 deletions

View File

@@ -1,6 +1,5 @@
package com.hxkj.admin;
import com.github.yulichang.injector.MPJSqlInjector;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -16,7 +15,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@ComponentScan(basePackages = {"com.hxkj"})
@MapperScan(basePackages = {"com.hxkj.*.mapper"})
@EnableTransactionManagement
@SpringBootApplication(exclude = {MPJSqlInjector.class, RedisRepositoriesAutoConfiguration.class})
@SpringBootApplication(exclude = {RedisRepositoriesAutoConfiguration.class})
public class LikeAdminApplication {
public static void main(String[] args) {

View File

@@ -6,7 +6,6 @@ import com.hxkj.admin.config.SystemConfig;
import com.hxkj.admin.service.ISystemAdminService;
import com.hxkj.admin.service.ISystemRoleMenuService;
import com.hxkj.common.core.AjaxResult;
import com.hxkj.common.entity.log.LogOperate;
import com.hxkj.common.enums.HttpEnum;
import com.hxkj.common.utils.RedisUtil;
import com.hxkj.common.utils.ToolsUtil;

View File

@@ -5,7 +5,7 @@ import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
public @interface Log {
/**
* 模块

View File

@@ -2,11 +2,13 @@ package com.hxkj.admin.config.aop;
import com.alibaba.fastjson.JSON;
import com.hxkj.admin.LikeAdminThreadLocal;
import com.hxkj.common.entity.log.LogOperate;
import com.hxkj.common.mapper.log.LogOperateMapper;
import com.hxkj.common.entity.system.SystemLogOperate;
import com.hxkj.common.mapper.system.SystemLogOperateMapper;
import com.hxkj.common.utils.HttpUtil;
import com.hxkj.common.utils.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@@ -19,23 +21,22 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
@Aspect
@Component
public class LogAspect {
@Resource
LogOperateMapper logOperateMapper;
SystemLogOperateMapper systemLogOperateMapper;
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
private Long beginTime = 0L;
/**
* 声明切面点拦截那些类
*/
@Pointcut("@annotation(com.hxkj.admin.config.aop.LogAnnotation)")
@Pointcut("@annotation(com.hxkj.admin.config.aop.Log)")
private void pointCutMethodController() {}
/**
@@ -44,31 +45,37 @@ public class LogAspect {
@Around(value = "pointCutMethodController()")
public Object doAroundService(ProceedingJoinPoint joinPoint) throws Throwable {
// 开始时间
long beginTime = System.currentTimeMillis();
this.beginTime = System.currentTimeMillis();
// 执行方法
Object result = joinPoint.proceed();
// 执行结束
long endTime = System.currentTimeMillis();
// 执行时长
long takeTime = endTime - beginTime;
// 保存日志
recordLog(joinPoint, beginTime, endTime, takeTime);
recordLog(joinPoint, null);
// 返回结果
return result;
}
/**
* 记录日志信息
* @param joinPoint joinPoint
* @param startTime 开始时间(毫秒)
* @param endTime 结束时间(毫秒)
* @param takeTime 执行时长(毫秒)
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
private void recordLog(ProceedingJoinPoint joinPoint, long startTime, long endTime, long takeTime) {
@AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
recordLog(joinPoint, e);
}
/**
* 记录日志信息
*
* @param joinPointObj joinPoint
* @param e Exception 错误异常
*/
private void recordLog(Object joinPointObj, final Exception e) {
try {
long endTime = System.currentTimeMillis();
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (requestAttributes != null) {
// 取得请求对象
HttpServletRequest request = requestAttributes.getRequest();
@@ -76,9 +83,10 @@ public class LogAspect {
Integer adminId = LikeAdminThreadLocal.getAdminId();
// 获取日志注解
ProceedingJoinPoint joinPoint = (ProceedingJoinPoint) joinPointObj;
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
Log logAnnotation = method.getAnnotation(Log.class);
// 方法名称
String className = joinPoint.getTarget().getClass().getName();
@@ -96,8 +104,16 @@ public class LogAspect {
}
}
// 错误信息
String error = "";
int status = 1;
if (e != null) {
error = e.getMessage();
status = 2; // 1=成功, 2=失败
}
// 数据库日志
LogOperate model = new LogOperate();
SystemLogOperate model = new SystemLogOperate();
model.setAdminId(adminId);
model.setTitle(logAnnotation.title());
model.setIp(IpUtil.getIpAddress(request));
@@ -105,14 +121,17 @@ public class LogAspect {
model.setMethod(className + "." + methodName + "()");
model.setUrl(HttpUtil.route());
model.setArgs(params);
model.setStartTime(startTime / 1000);
model.setError(error);
model.setAddress(IpUtil.getRealAddressByIP(IpUtil.getIpAddress(request)));
model.setStatus(status);
model.setStartTime(this.beginTime / 1000);
model.setEndTime(endTime / 1000);
model.setTaskTime(takeTime);
model.setTaskTime(endTime - this.beginTime);
model.setCreateTime(System.currentTimeMillis() / 1000);
logOperateMapper.insert(model);
systemLogOperateMapper.insert(model);
}
} catch (Exception e) {
log.error("异常信息:{}", e.getMessage());
} catch (Exception ex) {
log.error("异常信息:{}", ex.getMessage());
}
}

View File

@@ -1,9 +1,9 @@
package com.hxkj.admin.controller;
import com.alibaba.fastjson.JSONArray;
import com.hxkj.admin.service.IAlbumService;
import com.hxkj.admin.validate.AlbumParam;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.validate.system.SystemAdminParam;
import com.hxkj.admin.vo.album.AlbumVo;
import com.hxkj.common.core.AjaxResult;
import com.hxkj.common.core.PageResult;
@@ -13,6 +13,9 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* 相册管理
*/
@RestController
@RequestMapping("/api/album")
public class AlbumController {
@@ -75,10 +78,10 @@ public class AlbumController {
* @author fzr
* @return Object
*/
@PostMapping("/cateList")
@GetMapping("/cateList")
public Object cateList(@RequestParam Map<String, String> params) {
iAlbumService.cateList(params);
return AjaxResult.success();
JSONArray jsonArray = iAlbumService.cateList(params);
return AjaxResult.success(jsonArray);
}
/**

View File

@@ -1,40 +1,32 @@
package com.hxkj.admin.controller;
import com.hxkj.admin.config.aop.LogAnnotation;
import com.hxkj.common.core.AjaxResult;
import com.hxkj.common.exception.OperateException;
import com.hxkj.common.plugin.sms.SmsDriver;
import com.hxkj.admin.service.IIndexService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
/**
* 主页管理
*/
@RestController
@RequestMapping("/api/index")
public class IndexController {
@Resource
IIndexService iIndexService;
@PostMapping("/aa")
@LogAnnotation(title = "小河")
public AjaxResult aa(@RequestBody Map<String, String> map) {
System.out.println("急急急");
System.out.println(map);
// try {
// Map<String, String> params = new LinkedHashMap<>();
// (new SmsDriver())
// .setMobile("15627119239")
// .setParam(params)
// .sendSms();
//
// return AjaxResult.success();
// } catch (OperateException e) {
// return AjaxResult.failed(e.getMsg());
// }
/**
* 控制台
*
* @author fzr
* @return Object
*/
@GetMapping("/console")
public Object console() {
iIndexService.console();
return null;
}

View File

@@ -17,6 +17,9 @@ import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 上传管理
*/
@RestController
@RequestMapping("/api/upload")
public class UploadController {
@@ -28,7 +31,7 @@ public class UploadController {
* 上传图片
*
* @author fzr
* @param request 请求 对象
* @param request 请求对象
* @return Object
*/
@PostMapping("/image")
@@ -75,7 +78,7 @@ public class UploadController {
try {
StorageDriver storageDriver = new StorageDriver();
Map<String, Object> map = storageDriver.upload(multipartFile, "video", AlbumEnum.IMAGE.getCode());
Map<String, Object> map = storageDriver.upload(multipartFile, "video", AlbumEnum.Video.getCode());
Map<String, String> album = new LinkedHashMap<>();
album.put("cid", request.getParameter("cid"));

View File

@@ -13,6 +13,9 @@ import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.*;
/**
* 缓存监控管理
*/
@RestController
@RequestMapping("/api/monitor")
public class CacheController {
@@ -27,8 +30,7 @@ public class CacheController {
* @return Object
*/
@GetMapping("/cache")
public Object info()
{
public Object info() {
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

View File

@@ -6,10 +6,12 @@ import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 服务监控管理
*/
@RestController
@RequestMapping("/api/monitor")
public class ServerController
{
public class ServerController {
/**
* 服务器信息
*
@@ -17,8 +19,7 @@ public class ServerController
* @return Object
*/
@GetMapping("/server")
public Object info()
{
public Object info() {
ServerResult server = new ServerResult();
return AjaxResult.success(server.copyTo());
}

View File

@@ -10,6 +10,9 @@ import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
/**
* 基础设置管理
*/
@RestController
@RequestMapping("/api/setting")
public class BasicsController {

View File

@@ -13,6 +13,9 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* 系统管理员管理
*/
@RestController
@RequestMapping("/api/system/admin")
public class SystemAdminController {

View File

@@ -0,0 +1,54 @@
package com.hxkj.admin.controller.system;
import com.hxkj.admin.service.ISystemLogServer;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.vo.system.LogLoginVo;
import com.hxkj.admin.vo.system.LogOperateVo;
import com.hxkj.common.core.AjaxResult;
import com.hxkj.common.core.PageResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
/**
* 系统日志管理
*/
@RestController
@RequestMapping("/api/system/log")
public class SystemLogController {
@Resource
ISystemLogServer iSystemLogServer;
/**
* 系统操作日志
*
* @author fzr
* @param params 搜索参数
* @return Object
*/
@GetMapping("/operate")
public Object operate(@Validated PageParam pageParam, @RequestParam Map<String, String> params) {
PageResult<LogOperateVo> list = iSystemLogServer.operate(pageParam, params);
return AjaxResult.success(list);
}
/**
* 系统登录日志
*
* @author fzr
* @param params 搜索参数
* @return Object
*/
@GetMapping("/login")
public Object login(@Validated PageParam pageParam, @RequestParam Map<String, String> params) {
PageResult<LogLoginVo> list = iSystemLogServer.login(pageParam, params);
return AjaxResult.success(list);
}
}

View File

@@ -15,6 +15,9 @@ import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 系统登录管理
*/
@RestController
@RequestMapping("/api/system")
public class SystemLoginController {

View File

@@ -12,6 +12,9 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* 系统菜单管理
*/
@RestController
@RequestMapping("/api/system/menu")
public class SystemMenuController {

View File

@@ -12,6 +12,9 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* 系统角色管理
*/
@RestController
@RequestMapping("/api/system/role")
public class SystemRoleController {

View File

@@ -4,16 +4,14 @@ import com.alibaba.fastjson.JSONArray;
import com.hxkj.admin.validate.AlbumParam;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.vo.album.AlbumVo;
import com.hxkj.common.basics.BaseService;
import com.hxkj.common.core.PageResult;
import com.hxkj.common.entity.Album;
import java.util.Map;
/**
* 相册服务类
*/
public interface IAlbumService extends BaseService<Album> {
public interface IAlbumService {
/**
* 文件列表

View File

@@ -0,0 +1,10 @@
package com.hxkj.admin.service;
/**
* 主页服务类
*/
public interface IIndexService {
void console();
}

View File

@@ -3,7 +3,6 @@ package com.hxkj.admin.service;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.validate.system.SystemAdminParam;
import com.hxkj.admin.vo.system.SystemAdminVo;
import com.hxkj.common.basics.BaseService;
import com.hxkj.common.core.PageResult;
import com.hxkj.common.entity.system.SystemAdmin;
@@ -12,7 +11,7 @@ import java.util.Map;
/**
* 系统管理员服务
*/
public interface ISystemAdminService extends BaseService<SystemAdmin> {
public interface ISystemAdminService {
/**
* 根据账号查找管理员

View File

@@ -0,0 +1,34 @@
package com.hxkj.admin.service;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.vo.system.LogLoginVo;
import com.hxkj.admin.vo.system.LogOperateVo;
import com.hxkj.common.core.PageResult;
import java.util.Map;
/**
* 系统日志服务类
*/
public interface ISystemLogServer {
/**
* 系统操作日志
*
* @author fzr
* @param pageParam 分页参数
* @param params 搜索参数
* @return PageResult<LogOperateVo>
*/
PageResult<LogOperateVo> operate(PageParam pageParam, Map<String, String> params);
/**
* 系统登录日志
*
* @param pageParam 分页参数
* @param params 搜索参数
* @return PageResult<LogLoginVo>
*/
PageResult<LogLoginVo> login(PageParam pageParam, Map<String, String> params);
}

View File

@@ -3,13 +3,11 @@ package com.hxkj.admin.service;
import com.alibaba.fastjson.JSONArray;
import com.hxkj.admin.validate.system.SystemMenuParam;
import com.hxkj.admin.vo.system.SystemMenuVo;
import com.hxkj.common.basics.BaseService;
import com.hxkj.common.entity.system.SystemMenu;
/**
* 系统菜单服务
*/
public interface ISystemMenuService extends BaseService<SystemMenu> {
public interface ISystemMenuService {
/**
* 根据角色获取菜单

View File

@@ -1,14 +1,11 @@
package com.hxkj.admin.service;
import com.hxkj.common.basics.BaseService;
import com.hxkj.common.entity.system.SystemRoleMenu;
import java.util.List;
/**
* 系统角色菜单服务
*/
public interface ISystemRoleMenuService extends BaseService<SystemRoleMenu> {
public interface ISystemRoleMenuService {
/**
* 根据角色ID获取菜单ID

View File

@@ -3,15 +3,13 @@ package com.hxkj.admin.service;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.validate.system.SystemRoleParam;
import com.hxkj.admin.vo.system.SystemRoleVo;
import com.hxkj.common.basics.BaseService;
import com.hxkj.common.core.PageResult;
import com.hxkj.common.entity.system.SystemRole;
import org.springframework.validation.annotation.Validated;
/**
* 系统角色服务
*/
public interface ISystemRoleService extends BaseService<SystemRole> {
public interface ISystemRoleService {
/**
* 根据id获取角色名称

View File

@@ -5,14 +5,11 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.hxkj.admin.LikeAdminThreadLocal;
import com.hxkj.admin.service.IAlbumService;
import com.hxkj.admin.validate.AlbumParam;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.vo.album.AlbumCateVo;
import com.hxkj.admin.vo.album.AlbumVo;
import com.hxkj.admin.vo.system.SystemMenuVo;
import com.hxkj.common.core.PageResult;
import com.hxkj.common.entity.Album;
import com.hxkj.common.entity.AlbumCate;
@@ -27,11 +24,15 @@ import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@Service
public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> implements IAlbumService {
public class IAlbumServiceImpl implements IAlbumService {
@Resource
AlbumMapper albumMapper;
@Resource
AlbumCateMapper albumCateMapper;
@@ -58,12 +59,12 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
.eq("is_delete", 0)
.orderByDesc("id");
this.setSearch(queryWrapper, params, new String[]{
albumMapper.setSearch(queryWrapper, params, new String[]{
"like:keyword:str",
"=:type:int"
});
IPage<Album> iPage = this.page(new Page<>(page, limit), queryWrapper);
IPage<Album> iPage = albumMapper.selectPage(new Page<>(page, limit), queryWrapper);
List<AlbumVo> albumVoArrayList = new ArrayList<>();
for (Album album : iPage.getRecords()) {
@@ -89,7 +90,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
*/
@Override
public void albumRename(Integer id, String name) {
Album album = this.getOne(new QueryWrapper<Album>()
Album album = albumMapper.selectOne(new QueryWrapper<Album>()
.select("id", "name")
.eq("id", id)
.eq("is_delete", 0));
@@ -98,7 +99,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
album.setName(name);
album.setUpdateTime(System.currentTimeMillis() / 1000);
this.updateById(album);
albumMapper.updateById(album);
}
/**
@@ -110,7 +111,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
*/
@Override
public void albumMove(Integer id, Integer cid) {
Album album = this.getOne(new QueryWrapper<Album>()
Album album = albumMapper.selectOne(new QueryWrapper<Album>()
.select("id", "name")
.eq("id", id)
.eq("is_delete", 0)
@@ -126,7 +127,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
album.setCid(cid);
album.setUpdateTime(System.currentTimeMillis() / 1000);
this.updateById(album);
albumMapper.updateById(album);
}
/**
@@ -138,9 +139,9 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
@Override
public Integer albumAdd(Map<String, String> params) {
Album album = new Album();
album.setCid(Integer.parseInt(params.getOrDefault("cid", "0")));
album.setAid(Integer.parseInt(params.getOrDefault("aid", "0")));
album.setUid(Integer.parseInt(params.getOrDefault("uid", "0")));
album.setCid(Integer.parseInt(params.get("cid") == null ? "0" : params.get("cid")));
album.setAid(Integer.parseInt(params.get("aid") == null ? "0" : params.get("aid")));
album.setUid(Integer.parseInt(params.get("uid") == null ? "0" : params.get("uid")));
album.setType(Integer.parseInt(params.get("type")));
album.setName(params.get("name"));
album.setExt(params.get("ext"));
@@ -148,7 +149,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
album.setSize(Long.parseLong(params.get("size")));
album.setCreateTime(System.currentTimeMillis() / 1000);
album.setUpdateTime(System.currentTimeMillis() / 1000);
this.save(album);
albumMapper.insert(album);
return album.getId();
}
@@ -160,7 +161,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
*/
@Override
public void albumDel(Integer id) {
Album album = this.getOne(new QueryWrapper<Album>()
Album album = albumMapper.selectOne(new QueryWrapper<Album>()
.select("id", "name")
.eq("id", id)
.eq("is_delete", 0)
@@ -170,7 +171,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
album.setIsDelete(1);
album.setDeleteTime(System.currentTimeMillis() / 1000);
this.updateById(album);
albumMapper.updateById(album);
}
/**
@@ -200,13 +201,14 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
List<AlbumCate> albumCateList = albumCateMapper.selectList(queryWrapper);
List<AlbumCateVo> lists = new ArrayList<>();
List<AlbumCateVo> lists = new LinkedList<>();
for (AlbumCate albumCate : albumCateList) {
AlbumCateVo vo = new AlbumCateVo();
BeanUtils.copyProperties(albumCate, vo);
vo.setCreateTime(TimeUtil.timestampToDate(albumCate.getCreateTime()));
vo.setUpdateTime(TimeUtil.timestampToDate(albumCate.getUpdateTime()));
lists.add(vo);
}
JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(lists));
@@ -268,7 +270,7 @@ public class IAlbumServiceImpl extends MPJBaseServiceImpl<AlbumMapper, Album> im
Assert.notNull(albumCate, "分类已不存在!");
Assert.isNull(this.getOne(new QueryWrapper<Album>()
Assert.isNull(albumMapper.selectOne(new QueryWrapper<Album>()
.select("id", "cid", "name")
.eq("cid", id)
.eq("is_delete", 0)

View File

@@ -0,0 +1,39 @@
package com.hxkj.admin.service.impl;
import com.hxkj.admin.service.IIndexService;
import com.hxkj.common.utils.TimeUtil;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;
import java.util.Map;
@Service
public class IIndexServiceImpl implements IIndexService {
@Override
public void console() {
Map<String, Object> console = new LinkedHashMap<>();
// 账号信息
Map<String, Object> version = new LinkedHashMap<>();
version.put("version", "1.0.0");
version.put("website", "www.likeshop.cn");
console.put("version", version);
// 今日数据
Map<String, Object> today = new LinkedHashMap<>();
today.put("todayVisits", 10);
today.put("totalVisits", 100);
today.put("todaySales", 30);
today.put("totalSales", 65);
today.put("todayUsers", 120);
today.put("totalUsers", 360);
console.put("today", today);
// 访客图表
Map<String, Object> visitor = new LinkedHashMap<>();
System.out.println(TimeUtil.daysAgoTime(8));
}
}

View File

@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.hxkj.admin.config.SystemConfig;
import com.hxkj.admin.service.ISystemAdminService;
import com.hxkj.admin.service.ISystemRoleService;
@@ -23,7 +22,10 @@ import javax.annotation.Resource;
import java.util.*;
@Service
public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMapper, SystemAdmin> implements ISystemAdminService {
public class ISystemAdminServiceImpl implements ISystemAdminService {
@Resource
SystemAdminMapper systemAdminMapper;
@Resource
ISystemRoleService iSystemRoleService;
@@ -37,7 +39,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
*/
@Override
public SystemAdmin findByUsername(String username) {
return this.getOne(new QueryWrapper<SystemAdmin>()
return systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.eq("username", username)
.last("limit 1"));
}
@@ -63,13 +65,13 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
.eq("is_delete", 0)
.orderByDesc("sort");
this.setSearch(queryWrapper, params, new String[]{
systemAdminMapper.setSearch(queryWrapper, params, new String[]{
"like:username:str",
"like:nickname:str",
"=:role:int"
});
IPage<SystemAdmin> iPage = this.page(new Page<>(page, limit), queryWrapper);
IPage<SystemAdmin> iPage = systemAdminMapper.selectPage(new Page<>(page, limit), queryWrapper);
List<SystemAdminVo> adminVoArrayList = new ArrayList<>();
for (SystemAdmin sysAdmin : iPage.getRecords()) {
@@ -96,7 +98,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
*/
@Override
public SystemAdminVo detail(Integer id) {
SystemAdmin sysAdmin = this.getOne(new QueryWrapper<SystemAdmin>()
SystemAdmin sysAdmin = systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(SystemAdmin.class, info->
!info.getColumn().equals("salt") &&
!info.getColumn().equals("password") &&
@@ -129,19 +131,19 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
@Override
public void add(SystemAdminParam systemAdminParam) {
String[] field = {"id", "username", "nickname"};
Assert.isNull(this.getOne(new QueryWrapper<SystemAdmin>()
Assert.isNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(field)
.eq("is_delete", 0)
.eq("username", systemAdminParam.getUsername())
.last("limit 1")), "账号已存在换一个吧!");
Assert.isNull(this.getOne(new QueryWrapper<SystemAdmin>()
Assert.isNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(field)
.eq("is_delete", 0)
.eq("nickname", systemAdminParam.getNickname())
.last("limit 1")), "昵称已存在换一个吧!");
Assert.notNull(iSystemRoleService.getById(systemAdminParam.getRole()), "角色不存在!");
Assert.notNull(iSystemRoleService.detail(systemAdminParam.getRole()), "角色不存在!");
String salt = ToolsUtil.randomString(5);
String pwd = ToolsUtil.makeMd5(systemAdminParam.getPassword().trim() + salt);
@@ -158,7 +160,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
model.setIsDisable(systemAdminParam.getIsDisable());
model.setCreateTime(System.currentTimeMillis() / 1000);
model.setUpdateTime(System.currentTimeMillis() / 1000);
this.save(model);
systemAdminMapper.insert(model);
}
/**
@@ -170,27 +172,27 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
@Override
public void edit(SystemAdminParam systemAdminParam) {
String[] field = {"id", "username", "nickname"};
Assert.notNull(this.getOne(new QueryWrapper<SystemAdmin>()
Assert.notNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(field)
.eq("id", systemAdminParam.getId())
.eq("is_delete", 0)
.last("limit 1")), "账号不存在了!");
Assert.isNull(this.getOne(new QueryWrapper<SystemAdmin>()
Assert.isNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(field)
.eq("is_delete", 0)
.eq("username", systemAdminParam.getUsername())
.ne("id", systemAdminParam.getId())
.last("limit 1")), "账号已存在换一个吧!");
Assert.isNull(this.getOne(new QueryWrapper<SystemAdmin>()
Assert.isNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(field)
.eq("is_delete", 0)
.eq("nickname", systemAdminParam.getNickname())
.ne("id", systemAdminParam.getId())
.last("limit 1")), "昵称已存在换一个吧!");
Assert.notNull(iSystemRoleService.getById(systemAdminParam.getRole()), "角色不存在!");
Assert.notNull(iSystemRoleService.detail(systemAdminParam.getRole()), "角色不存在!");
SystemAdmin model = new SystemAdmin();
model.setId(systemAdminParam.getId());
@@ -209,7 +211,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
model.setSalt(salt);
}
this.updateById(model);
systemAdminMapper.updateById(model);
this.cacheAdminUserByUid(systemAdminParam.getId());
if (systemAdminParam.getPassword() != null) {
@@ -226,7 +228,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
@Override
public void del(Integer id) {
String[] field = {"id", "username", "nickname"};
Assert.notNull(this.getOne(new QueryWrapper<SystemAdmin>()
Assert.notNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select(field)
.eq("id", id)
.eq("is_delete", 0)
@@ -238,7 +240,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
model.setId(id);
model.setIsDelete(1);
model.setDeleteTime(System.currentTimeMillis() / 1000);
this.updateById(model);
systemAdminMapper.updateById(model);
this.cacheAdminUserByUid(id);
}
@@ -247,7 +249,7 @@ public class ISystemAdminServiceImpl extends MPJBaseServiceImpl<SystemAdminMappe
*/
@Override
public void cacheAdminUserByUid(Integer id) {
SystemAdmin sysAdmin = this.getById(id);
SystemAdmin sysAdmin = systemAdminMapper.selectById(id);
Map<String, Object> user = new LinkedHashMap<>();
Map<String, Object> map = new LinkedHashMap<>();

View File

@@ -0,0 +1,115 @@
package com.hxkj.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.hxkj.admin.service.ISystemLogServer;
import com.hxkj.admin.validate.PageParam;
import com.hxkj.admin.vo.system.LogLoginVo;
import com.hxkj.admin.vo.system.LogOperateVo;
import com.hxkj.common.core.PageResult;
import com.hxkj.common.entity.system.SystemLogLogin;
import com.hxkj.common.entity.system.SystemLogOperate;
import com.hxkj.common.mapper.system.SystemLogLoginMapper;
import com.hxkj.common.mapper.system.SystemLogOperateMapper;
import com.hxkj.common.utils.StringUtil;
import com.hxkj.common.utils.TimeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@Service
public class ISystemLogServerImpl implements ISystemLogServer {
@Resource
SystemLogOperateMapper logOperateMapper;
@Resource
SystemLogLoginMapper logLoginMapper;
/**
* 系统操作日志
*
* @author fzr
* @param pageParam 分页参数
* @param params 搜索参数
* @return PageResult<LogOperateVo>
*/
@Override
public PageResult<LogOperateVo> operate(PageParam pageParam, Map<String, String> params) {
Integer pageNo = pageParam.getPageNo();
Integer pageSize = pageParam.getPageSize();
MPJQueryWrapper<SystemLogOperate> mpjQueryWrapper = new MPJQueryWrapper<SystemLogOperate>()
.selectAll(SystemLogOperate.class)
.select("sa.username,sa.nickname")
.leftJoin("ls_system_admin sa ON sa.id=t.admin_id")
.orderByDesc("id");
IPage<LogOperateVo> iPage = logOperateMapper.selectJoinPage(
new Page<>(pageNo, pageSize),
LogOperateVo.class,
mpjQueryWrapper);
logOperateMapper.setSearch(mpjQueryWrapper, params, new String[]{
"like:title:str",
"like:username:str",
"=:type:int",
"=:status:int",
"datetime:startTime-endTime@create_time:str"
});
for (LogOperateVo vo : iPage.getRecords()) {
vo.setTaskTime(vo.getTaskTime());
vo.setStartTime(TimeUtil.timestampToDate(vo.getStartTime()));
vo.setEndTime(TimeUtil.timestampToDate(vo.getEndTime()));
vo.setCreateTime(TimeUtil.timestampToDate(vo.getCreateTime()));
vo.setError(StringUtil.isNull(vo.getError()) ? "" : vo.getError());
}
return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
}
/**
* 系统登录日志
*
* @author fzr
* @param pageParam 分页参数
* @param params 搜索参数
* @return PageResult<LogLoginVo>
*/
@Override
public PageResult<LogLoginVo> login(PageParam pageParam, Map<String, String> params) {
Integer pageNo = pageParam.getPageNo();
Integer pageSize = pageParam.getPageSize();
QueryWrapper<SystemLogLogin> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
logLoginMapper.setSearch(queryWrapper, params, new String[]{
"like:username:str",
"=:status:int",
"datetime:startTime-endTime@create_time:str"
});
IPage<SystemLogLogin> iPage = logLoginMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);
List<LogLoginVo> voList = new LinkedList<>();
for (SystemLogLogin item : iPage.getRecords()) {
LogLoginVo vo = new LogLoginVo();
BeanUtils.copyProperties(item, vo);
vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
voList.add(vo);
}
return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), voList);
}
}

View File

@@ -5,24 +5,39 @@ import com.hxkj.admin.service.ISystemAdminService;
import com.hxkj.admin.service.ISystemLoginService;
import com.hxkj.admin.validate.system.SystemLoginParam;
import com.hxkj.common.entity.system.SystemAdmin;
import com.hxkj.common.entity.system.SystemLogLogin;
import com.hxkj.common.enums.HttpEnum;
import com.hxkj.common.exception.LoginException;
import com.hxkj.common.exception.OperateException;
import com.hxkj.common.utils.HttpUtil;
import com.hxkj.common.utils.RedisUtil;
import com.hxkj.common.utils.ToolsUtil;
import com.hxkj.common.mapper.system.SystemAdminMapper;
import com.hxkj.common.mapper.system.SystemLogLoginMapper;
import com.hxkj.common.utils.*;
import nl.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
@Service
public class ISystemLoginServiceImpl implements ISystemLoginService {
@Resource
SystemLogLoginMapper systemLogLoginMapper;
@Resource
SystemAdminMapper systemAdminMapper;
@Resource
ISystemAdminService iSystemAdminService;
private static final Logger log = LoggerFactory.getLogger(ISystemLoginServiceImpl.class);
/**
* 登录
*
@@ -37,23 +52,26 @@ public class ISystemLoginServiceImpl implements ISystemLoginService {
SystemAdmin sysAdmin = iSystemAdminService.findByUsername(username);
if (sysAdmin == null || sysAdmin.getIsDelete() == 1) {
this.recordLoginLog(0, systemLoginParam.getUsername(), HttpEnum.LOGIN_ACCOUNT_ERROR.getMsg());
throw new LoginException(HttpEnum.LOGIN_ACCOUNT_ERROR.getCode(), HttpEnum.LOGIN_ACCOUNT_ERROR.getMsg());
}
if (sysAdmin.getIsDisable() == 1) {
this.recordLoginLog(sysAdmin.getId(), systemLoginParam.getUsername(), HttpEnum.LOGIN_DISABLE_ERROR.getMsg());
throw new LoginException(HttpEnum.LOGIN_DISABLE_ERROR.getCode(), HttpEnum.LOGIN_DISABLE_ERROR.getMsg());
}
String newPWd = password + sysAdmin.getId() + sysAdmin.getSalt();
String md5Pwd = ToolsUtil.makeMd5(newPWd);
if (!md5Pwd.equals(sysAdmin.getPassword())) {
this.recordLoginLog(sysAdmin.getId(), systemLoginParam.getUsername(), HttpEnum.LOGIN_ACCOUNT_ERROR.getMsg());
throw new LoginException(HttpEnum.LOGIN_ACCOUNT_ERROR.getCode(), HttpEnum.LOGIN_ACCOUNT_ERROR.getMsg());
}
try {
sysAdmin.setLastLoginIp(HttpUtil.ip());
sysAdmin.setLastLoginTime(System.currentTimeMillis() / 1000);
iSystemAdminService.updateById(sysAdmin);
systemAdminMapper.updateById(sysAdmin);
String token = ToolsUtil.makeToken();
RedisUtil.set(SystemConfig.backstageTokenKey+token, sysAdmin.getId(), 7200);
@@ -61,8 +79,14 @@ public class ISystemLoginServiceImpl implements ISystemLoginService {
Map<String, Object> response = new LinkedHashMap<>();
response.put("token", token);
this.recordLoginLog(sysAdmin.getId(), systemLoginParam.getUsername(), "");
return response;
} catch (Exception e) {
Integer adminId = StringUtil.isNotNull(sysAdmin.getId()) ? sysAdmin.getId() : 0;
String error = StringUtil.isEmpty(e.getMessage()) ? "未知错误" : e.getMessage();
this.recordLoginLog(adminId, systemLoginParam.getUsername(), error);
throw new OperateException(e.getMessage());
}
}
@@ -78,4 +102,27 @@ public class ISystemLoginServiceImpl implements ISystemLoginService {
RedisUtil.del(SystemConfig.backstageTokenKey + token);
}
/**
* 记录登录日志
*/
private void recordLoginLog(Integer adminId, String username, String error) {
try {
HttpServletRequest request = Objects.requireNonNull(HttpUtil.obj());
final UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
SystemLogLogin model = new SystemLogLogin();
model.setAdminId(adminId);
model.setUsername(username);
model.setIp(HttpUtil.ip());
model.setAddress(IpUtil.getRealAddressByIP(HttpUtil.ip()));
model.setOs(userAgent.getOperatingSystem().getName());
model.setBrowser(userAgent.getBrowser().getName());
model.setStatus(StringUtil.isEmpty(error) ? 1 : 0);
model.setCreateTime(System.currentTimeMillis() / 1000);
systemLogLoginMapper.insert(model);
} catch (Exception e) {
log.error("记录登录日志异常 {}" + e.getMessage());
}
}
}

View File

@@ -3,7 +3,6 @@ package com.hxkj.admin.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.hxkj.admin.LikeAdminThreadLocal;
import com.hxkj.admin.config.SystemConfig;
import com.hxkj.admin.service.ISystemMenuService;
@@ -24,7 +23,10 @@ import java.util.Arrays;
import java.util.List;
@Service
public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper, SystemMenu> implements ISystemMenuService {
public class ISystemMenuServiceImpl implements ISystemMenuService {
@Resource
SystemMenuMapper systemMenuMapper;
@Resource
ISystemRoleMenuService iSystemRoleMenuService;
@@ -48,7 +50,7 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
queryWrapper.in("id", menuIds);
}
List<SystemMenu> systemMenus = this.list(queryWrapper);
List<SystemMenu> systemMenus = systemMenuMapper.selectList(queryWrapper);
List<SystemMenuVo> lists = new ArrayList<>();
for (SystemMenu systemMenu : systemMenus) {
SystemMenuVo vo = new SystemMenuVo();
@@ -74,7 +76,7 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
QueryWrapper<SystemMenu> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc(Arrays.asList("menu_sort", "id"));
List<SystemMenu> systemMenus = this.list(queryWrapper);
List<SystemMenu> systemMenus = systemMenuMapper.selectList(queryWrapper);
List<SystemMenuVo> lists = new ArrayList<>();
for (SystemMenu systemMenu : systemMenus) {
@@ -99,7 +101,7 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
*/
@Override
public SystemMenuVo detail(Integer id) {
SystemMenu systemMenu = this.getOne(new QueryWrapper<SystemMenu>().eq("id", id));
SystemMenu systemMenu = systemMenuMapper.selectOne(new QueryWrapper<SystemMenu>().eq("id", id));
Assert.notNull(systemMenu, "菜单已不存在!");
SystemMenuVo vo = new SystemMenuVo();
@@ -128,7 +130,7 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
model.setIsDisable(systemMenuParam.getIsDisable());
model.setCreateTime(System.currentTimeMillis() / 1000);
model.setUpdateTime(System.currentTimeMillis() / 1000);
this.save(model);
systemMenuMapper.insert(model);
}
/**
@@ -139,7 +141,7 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
*/
@Override
public void edit(SystemMenuParam systemMenuParam) {
SystemMenu model = this.getOne(new QueryWrapper<SystemMenu>().eq("id", systemMenuParam.getId()));
SystemMenu model = systemMenuMapper.selectOne(new QueryWrapper<SystemMenu>().eq("id", systemMenuParam.getId()));
Assert.notNull(model, "菜单已不存在!");
model.setMenuType(systemMenuParam.getMenuType());
@@ -150,7 +152,7 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
model.setPid(systemMenuParam.getPid());
model.setIsDisable(systemMenuParam.getIsDisable());
model.setUpdateTime(System.currentTimeMillis() / 1000);
this.updateById(model);
systemMenuMapper.updateById(model);
RedisUtil.del(SystemConfig.backstageRolesKey);
}
@@ -163,10 +165,10 @@ public class ISystemMenuServiceImpl extends MPJBaseServiceImpl<SystemMenuMapper,
*/
@Override
public void del(Integer id) {
SystemMenu model = this.getOne(new QueryWrapper<SystemMenu>().eq("id", id));
SystemMenu model = systemMenuMapper.selectOne(new QueryWrapper<SystemMenu>().eq("id", id));
Assert.notNull(model, "菜单已不存在!");
this.removeById(id);
systemMenuMapper.deleteById(id);
iSystemRoleMenuService.batchDeleteByMenuId(id);
RedisUtil.del(SystemConfig.backstageRolesKey);

View File

@@ -1,16 +1,16 @@
package com.hxkj.admin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.hxkj.admin.config.SystemConfig;
import com.hxkj.admin.service.ISystemMenuService;
import com.hxkj.admin.service.ISystemRoleMenuService;
import com.hxkj.common.entity.system.SystemMenu;
import com.hxkj.common.entity.system.SystemRoleMenu;
import com.hxkj.common.mapper.system.SystemMenuMapper;
import com.hxkj.common.mapper.system.SystemRoleMenuMapper;
import com.hxkj.common.utils.RedisUtil;
import com.hxkj.common.utils.ToolsUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
@@ -18,10 +18,13 @@ import java.util.LinkedList;
import java.util.List;
@Service
public class ISystemRoleMenuServiceImpl extends MPJBaseServiceImpl<SystemRoleMenuMapper, SystemRoleMenu> implements ISystemRoleMenuService {
public class ISystemRoleMenuServiceImpl implements ISystemRoleMenuService {
@Resource
ISystemMenuService iSystemMenuService;
SystemRoleMenuMapper systemRoleMenuMapper;
@Resource
SystemMenuMapper systemMenuMapper;
/**
* 根据角色ID获取菜单ID
@@ -32,7 +35,8 @@ public class ISystemRoleMenuServiceImpl extends MPJBaseServiceImpl<SystemRoleMen
@Override
public List<Integer> selectMenuIdsByRoleId(Integer roleId) {
List<Integer> menus = new LinkedList<>();
List<SystemRoleMenu> systemRoleMenus = this.list(new QueryWrapper<SystemRoleMenu>().eq("role_id", roleId));
List<SystemRoleMenu> systemRoleMenus = systemRoleMenuMapper.selectList(
new QueryWrapper<SystemRoleMenu>().eq("role_id", roleId));
for (SystemRoleMenu systemRoleMenu : systemRoleMenus) {
menus.add(systemRoleMenu.getMenuId());
}
@@ -47,16 +51,15 @@ public class ISystemRoleMenuServiceImpl extends MPJBaseServiceImpl<SystemRoleMen
* @param menuIds 菜单ID组
*/
@Override
@Transactional
public void batchSaveByMenuIds(Integer roleId, String menuIds) {
if (menuIds != null && !menuIds.equals("")) {
List<SystemRoleMenu> arrayList = new ArrayList<>();
for (String menuId : menuIds.split(",")) {
SystemRoleMenu model = new SystemRoleMenu();
model.setRoleId(roleId);
model.setMenuId(Integer.parseInt(menuId));
arrayList.add(model);
systemRoleMenuMapper.insert(model);
}
this.saveBatch(arrayList);
}
}
@@ -68,7 +71,7 @@ public class ISystemRoleMenuServiceImpl extends MPJBaseServiceImpl<SystemRoleMen
*/
@Override
public void batchDeleteByRoleId(Integer roleId) {
this.remove(new QueryWrapper<SystemRoleMenu>().eq("role_id", roleId));
systemRoleMenuMapper.delete(new QueryWrapper<SystemRoleMenu>().eq("role_id", roleId));
}
/**
@@ -79,7 +82,7 @@ public class ISystemRoleMenuServiceImpl extends MPJBaseServiceImpl<SystemRoleMen
*/
@Override
public void batchDeleteByMenuId(Integer menuId) {
this.remove(new QueryWrapper<SystemRoleMenu>().eq("menu_id", menuId));
systemRoleMenuMapper.delete(new QueryWrapper<SystemRoleMenu>().eq("menu_id", menuId));
}
/**
@@ -93,13 +96,14 @@ public class ISystemRoleMenuServiceImpl extends MPJBaseServiceImpl<SystemRoleMen
List<Integer> menuIds = new LinkedList<>();
List<String> menuArray = new LinkedList<>();
List<SystemRoleMenu> systemRoleMenus = this.list(new QueryWrapper<SystemRoleMenu>().eq("role_id", roleId));
List<SystemRoleMenu> systemRoleMenus = systemRoleMenuMapper.selectList(
new QueryWrapper<SystemRoleMenu>().eq("role_id", roleId));
for (SystemRoleMenu systemRoleMenu : systemRoleMenus) {
menuIds.add(systemRoleMenu.getMenuId());
}
if (menuIds.size() > 0) {
List<SystemMenu> systemMenus = iSystemMenuService.list(new QueryWrapper<SystemMenu>()
List<SystemMenu> systemMenus = systemMenuMapper.selectList(new QueryWrapper<SystemMenu>()
.select("id,perms")
.in("id", menuIds)
.eq("is_disable", 0));

View File

@@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.hxkj.admin.config.SystemConfig;
import com.hxkj.admin.service.ISystemAdminService;
import com.hxkj.admin.service.ISystemRoleMenuService;
@@ -15,6 +14,7 @@ import com.hxkj.admin.vo.system.SystemRoleVo;
import com.hxkj.common.core.PageResult;
import com.hxkj.common.entity.system.SystemAdmin;
import com.hxkj.common.entity.system.SystemRole;
import com.hxkj.common.mapper.system.SystemAdminMapper;
import com.hxkj.common.mapper.system.SystemRoleMapper;
import com.hxkj.common.utils.RedisUtil;
import com.hxkj.common.utils.TimeUtil;
@@ -29,15 +29,17 @@ import java.util.Arrays;
import java.util.List;
@Service
public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper, SystemRole> implements ISystemRoleService {
public class ISystemRoleServiceImpl implements ISystemRoleService {
@Resource
ISystemAdminService iSystemAdminService;
SystemAdminMapper systemAdminMapper;
@Resource
SystemRoleMapper systemRoleMapper;
@Resource
ISystemRoleMenuService iSystemRoleMenuService;
/**
* 根据ID获取角色名称
*
@@ -52,7 +54,7 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
.eq("id", id)
.last("limit 1");
SystemRole systemRole = this.getOne(queryWrapper, false);
SystemRole systemRole = systemRoleMapper.selectOne(queryWrapper);
if (systemRole == null) {
return "";
}
@@ -74,7 +76,7 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
QueryWrapper<SystemRole> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc(Arrays.asList("sort", "id"));
IPage<SystemRole> iPage = this.page(new Page<>(page, limit), queryWrapper);
IPage<SystemRole> iPage = systemRoleMapper.selectPage(new Page<>(page, limit), queryWrapper);
List<SystemRoleVo> roleVoArrayList = new ArrayList<>();
for (SystemRole systemRole : iPage.getRecords()) {
@@ -99,7 +101,7 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
*/
@Override
public SystemRoleVo detail(Integer id) {
SystemRole systemRole = this.getOne(new QueryWrapper<SystemRole>()
SystemRole systemRole = systemRoleMapper.selectOne(new QueryWrapper<SystemRole>()
.eq("id", id)
.last("limit 1"));
@@ -124,7 +126,7 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
@Override
@Transactional
public void add(SystemRoleParam systemRoleParam) {
Assert.isNull(this.getOne(new QueryWrapper<SystemRole>()
Assert.isNull(systemRoleMapper.selectOne(new QueryWrapper<SystemRole>()
.select("id,name")
.eq("name", systemRoleParam.getName().trim())
.last("limit 1")), "角色名称已存在!");
@@ -135,7 +137,7 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
model.setIsDisable(systemRoleParam.getIsDisable());
model.setCreateTime(System.currentTimeMillis() / 1000);
model.setUpdateTime(System.currentTimeMillis() / 1000);
this.save(model);
systemRoleMapper.insert(model);
iSystemRoleMenuService.batchSaveByMenuIds(model.getId(), systemRoleParam.getMenuIds());
}
@@ -149,12 +151,12 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
@Override
@Transactional
public void edit(SystemRoleParam systemRoleParam) {
Assert.notNull(this.getOne(new QueryWrapper<SystemRole>()
Assert.notNull(systemRoleMapper.selectOne(new QueryWrapper<SystemRole>()
.select("id,name")
.eq("id", systemRoleParam.getId())
.last("limit 1")), "角色已不存在!");
Assert.isNull(this.getOne(new QueryWrapper<SystemRole>()
Assert.isNull(systemRoleMapper.selectOne(new QueryWrapper<SystemRole>()
.select("id,name")
.ne("id", systemRoleParam.getId())
.eq("name", systemRoleParam.getName().trim())
@@ -166,7 +168,7 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
model.setRemark(systemRoleParam.getRemark());
model.setIsDisable(systemRoleParam.getIsDisable());
model.setUpdateTime(System.currentTimeMillis() / 1000);
this.updateById(model);
systemRoleMapper.updateById(model);
iSystemRoleMenuService.batchDeleteByRoleId(systemRoleParam.getId());
iSystemRoleMenuService.batchSaveByMenuIds(systemRoleParam.getId(), systemRoleParam.getMenuIds());
@@ -183,19 +185,19 @@ public class ISystemRoleServiceImpl extends MPJBaseServiceImpl<SystemRoleMapper,
@Transactional
public void del(Integer id) {
Assert.notNull(
this.getOne(new QueryWrapper<SystemRole>()
systemRoleMapper.selectOne(new QueryWrapper<SystemRole>()
.select("id", "name")
.eq("id", id)
.last("limit 1")),
"角色已不存在!");
Assert.isNull(iSystemAdminService.getOne(new QueryWrapper<SystemAdmin>()
Assert.isNull(systemAdminMapper.selectOne(new QueryWrapper<SystemAdmin>()
.select("id", "role", "nickname")
.eq("role", id)
.eq("is_delete", 0)),
"角色已被管理员使用,请先移除");
this.removeById(id);
systemRoleMapper.deleteById(id);
iSystemRoleMenuService.batchDeleteByRoleId(id);
RedisUtil.hDel(SystemConfig.backstageRolesKey, String.valueOf(id));
}

View File

@@ -1,6 +1,5 @@
package com.hxkj.admin.validate;
import com.hxkj.admin.validate.system.SystemAdminParam;
import com.hxkj.common.validator.annotation.IDMust;
import com.hxkj.common.validator.annotation.IntegerContains;
import lombok.Data;
@@ -22,8 +21,8 @@ public class AlbumParam implements Serializable {
public interface delete{}
public interface rename{}
public interface albumMove{}
public interface cateAdd{}
public interface albumMove{}
@IDMust(message = "id参数必传且需大于0", groups = {rename.class, albumMove.class, delete.class})
private Integer id;

View File

@@ -0,0 +1,21 @@
package com.hxkj.admin.vo.system;
import lombok.Data;
import java.io.Serializable;
@Data
public class LogLoginVo implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String ip;
private String os;
private String browser;
private String address;
private Integer status;
private String createTime;
}

View File

@@ -0,0 +1,29 @@
package com.hxkj.admin.vo.system;
import lombok.Data;
import java.io.Serializable;
@Data
public class LogOperateVo implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String nickname;
private String type;
private String title;
private String method;
private String ip;
private String url;
private String args;
private String error;
private String address;
private Integer status;
private String taskTime;
private String startTime;
private String endTime;
private String createTime;
}

View File

@@ -92,6 +92,11 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<!-- UserAgent -->
<dependency>
<groupId>nl.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
</dependency>
<!-- 七牛云 -->
<dependency>
<groupId>com.qiniu</groupId>

View File

@@ -1,13 +0,0 @@
package com.hxkj.common.basics;
import com.github.yulichang.base.MPJBaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 基类Mapper
* @param <T>
*/
@Mapper
public interface BaseMapper<T> extends MPJBaseMapper<T> {
}

View File

@@ -1,149 +0,0 @@
package com.hxkj.common.basics;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 基础服务接口类
*/
public interface BaseService<T> extends IService<T> {
/**
* 设置搜索条件
*
* @author fzr
* @param queryWrapper 条件构造器
* @param params 参数[条件:键@数据库字段:类型]
* @param conditions 条件
*/
default void setSearch(QueryWrapper<T> queryWrapper, Map<String, String> params, String[] conditions) {
for (String condition : conditions) {
String[] array = condition.split(":");
String type = array.length > 2 ? array[2].trim() : "";
String where = array[0].trim();
String[] keyArr = array[1].trim().split("@");
String key = keyArr[0].trim();
String field = keyArr.length > 1 ? keyArr[1].trim() : keyArr[0].trim();
String value = params.getOrDefault(key, "");
if (value.equals("")) {
continue;
}
if ((!type.equals("") && !Arrays.asList("int", "long", "str").contains(type))) {
System.out.println("搜索参数类型不在固定值内[int,long,str]");
continue;
}
Object val = value;
switch (where) {
case "=":
case "<>":
case ">":
case ">=":
case "<":
case "<=":
if (type.equals("int")) {
val = Integer.parseInt(value);
} else if (type.equals("long")) {
val = Long.parseLong(value);
}
case "in":
case "notIn":
if (type.equals("int")) {
List<Integer> intData = new ArrayList<>();
for (String v : value.split(",")) {
intData.add(Integer.parseInt(v.trim()));
}
val = intData;
} else if (type.equals("long")){
List<Long> longData = new ArrayList<>();
for (String v : value.split(",")) {
longData.add(Long.parseLong(v.trim()));
}
val = longData;
}
}
switch (where) {
case "=":
queryWrapper.eq(field, val);
break;
case "<>":
queryWrapper.ne(field, val);
break;
case ">":
queryWrapper.gt(field, val);
break;
case ">=":
queryWrapper.ge(field, val);
break;
case "<":
queryWrapper.lt(field, val);
break;
case "<=":
queryWrapper.le(field, val);
break;
case "between":
String[] betArr = value.split(",");
if (type.equals("int")) {
queryWrapper.between(field, Integer.parseInt(betArr[0]), Integer.parseInt(betArr[1]));
} else if (type.equals("long")){
queryWrapper.between(field, Long.parseLong(betArr[0]), Long.parseLong(betArr[1]));
} else {
queryWrapper.between(field, betArr[0], betArr[1]);
}
break;
case "notBetween":
String[] notBetArr = value.split(",");
if (type.equals("int")) {
queryWrapper.notBetween(field, Integer.parseInt(notBetArr[0]), Integer.parseInt(notBetArr[1]));
} else if (type.equals("long")){
queryWrapper.notBetween(field, Long.parseLong(notBetArr[0]), Long.parseLong(notBetArr[1]));
} else {
queryWrapper.notBetween(field, notBetArr[0], notBetArr[1]);
}
break;
case "like":
queryWrapper.like(field, val);
break;
case "notLike":
queryWrapper.notLike(field, val);
break;
case "likeLeft":
queryWrapper.likeLeft(field, val);
break;
case "likeRight":
queryWrapper.likeRight(field, val);
break;
case "in":
queryWrapper.in(field, val);
break;
case "notIn":
queryWrapper.notIn(field, val);
break;
}
}
}
/**
* 求和聚合
*
* @param field 字段名
* @param queryWrapper 条件构造器
* @return Long
*/
default BigDecimal sum(String field, QueryWrapper<T> queryWrapper) {
queryWrapper.select("IFNULL(sum("+field+"), 0) as totalValue");
Map<String, Object> map = this.getMap(queryWrapper);
return (BigDecimal) map.get("totalValue");
}
}

View File

@@ -8,6 +8,9 @@ public class GlobalConfig {
// 开启调试模式
public static Boolean debug = true;
// 获取地址开关
public static Boolean isAddressEnabled = true;
// 当前代码版本
public static String version = "v1.1.0";

View File

@@ -0,0 +1,309 @@
package com.hxkj.common.core.basics;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.hxkj.common.utils.TimeUtil;
import org.apache.ibatis.annotations.Mapper;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* 基类Mapper
* @param <T>
*/
@Mapper
public interface IBaseMapper<T> extends MPJBaseMapper<T> {
/**
* 求和聚合
*
* @param field 字段名
* @param queryWrapper 条件构造器
* @return Long
*/
default BigDecimal sum(String field, QueryWrapper<T> queryWrapper) {
queryWrapper.select("IFNULL(sum("+field+"), 0) as totalValue");
List<Object> objects = this.selectObjs(queryWrapper);
if (objects.size() > 0) {
return (BigDecimal) objects.get(0);
}
return new BigDecimal(0);
}
/**
* 设置搜索条件
*
* @author fzr
* @param queryWrapper 条件构造器
* @param params 参数[条件:键@数据库字段:类型]
* @param conditions 条件
*/
default void setSearch(MPJQueryWrapper<T> queryWrapper, Map<String, String> params, String[] conditions) {
for (String condition : conditions) {
String[] array = condition.split(":");
String type = array.length > 2 ? array[2].trim() : "";
String[] keyArr = array[1].trim().split("@");
String where = array[0].trim();
String key = keyArr[0].trim();
String value = params.getOrDefault(key, "");
String field = keyArr.length > 1 ? keyArr[1].trim() : keyArr[0].trim();
if (!where.equals("datetime") && (value == null || value.equals(""))) {
continue;
}
if ((!type.equals("") && !Arrays.asList("long", "str", "int").contains(type))) {
System.out.println("搜索参数类型不在固定值内[int,long,str]");
continue;
}
Object val = value;
switch (where) {
case "=":
case "<>":
case ">=":
case ">":
case "<=":
case "<":
if (type.equals("int")) {
val = Integer.parseInt(value);
} else if (type.equals("long")) {
val = Long.parseLong(value);
}
case "notIn":
case "in":
if (type.equals("long")){
List<Long> longData = new ArrayList<>();
for (String v : value.split(",")) {
longData.add(Long.parseLong(v.trim()));
}
val = longData;
} else if (type.equals("int")) {
List<Integer> intData = new ArrayList<>();
for (String v : value.split(",")) {
intData.add(Integer.parseInt(v.trim()));
}
val = intData;
}
}
switch (where) {
case "<>":
queryWrapper.ne(field, val);
break;
case "=":
queryWrapper.eq(field, val);
break;
case ">":
queryWrapper.gt(field, val);
break;
case ">=":
queryWrapper.ge(field, val);
break;
case "<":
queryWrapper.lt(field, val);
break;
case "<=":
queryWrapper.le(field, val);
break;
case "between":
String[] betArr = value.split(",");
if (!type.equals("") && type.equals("int")) {
queryWrapper.between(field, Integer.parseInt(betArr[0]), Integer.parseInt(betArr[1]));
} else if (type.equals("long")){
queryWrapper.between(field, Long.parseLong(betArr[0]), Long.parseLong(betArr[1]));
} else {
queryWrapper.between(field, betArr[0], betArr[1]);
}
break;
case "notBetween":
String[] notBetArr = value.split(",");
if (!type.equals("") && type.equals("int")) {
queryWrapper.notBetween(field, Integer.parseInt(notBetArr[0]), Integer.parseInt(notBetArr[1]));
} else if (type.equals("long")){
queryWrapper.notBetween(field, Long.parseLong(notBetArr[0]), Long.parseLong(notBetArr[1]));
} else {
queryWrapper.notBetween(field, notBetArr[0], notBetArr[1]);
}
break;
case "like":
queryWrapper.like(field, val);
break;
case "notLike":
queryWrapper.notLike(field, val);
break;
case "likeLeft":
queryWrapper.likeLeft(field, val);
break;
case "likeRight":
queryWrapper.likeRight(field, val);
break;
case "in":
queryWrapper.in(field, val);
break;
case "notIn":
queryWrapper.notIn(field, val);
break;
case "datetime":
String[] dateKeys = key.split("-");
String dateStart = params.getOrDefault(dateKeys[0].trim(), "");
if (dateStart.equals("")) {
continue;
}
String dateEnd = dateKeys.length > 1 ? params.getOrDefault(dateKeys[1].trim(), "") : "";
if (type.equals("long")) {
if (!dateEnd.equals("")) { queryWrapper.le(field, Long.parseLong(dateEnd)); }
queryWrapper.ge(field, Long.parseLong(dateStart));
} else {
queryWrapper.ge(field, TimeUtil.dateToTimestamp(dateStart));
if (!dateEnd.equals("")) { queryWrapper.le(field, TimeUtil.dateToTimestamp(dateEnd)); }
}
break;
}
}
}
/**
* 设置搜索条件
*
* @author fzr
* @param queryWrapper 条件构造器
* @param params 参数[条件:键@数据库字段:类型]
* @param conditions 条件
*/
default void setSearch(QueryWrapper<T> queryWrapper, Map<String, String> params, String[] conditions) {
for (String condition : conditions) {
String[] array = condition.split(":");
String type = array.length > 2 ? array[2].trim() : "";
String where = array[0].trim();
String[] keyArr = array[1].trim().split("@");
String key = keyArr[0].trim();
String field = keyArr.length > 1 ? keyArr[1].trim() : keyArr[0].trim();
String value = params.getOrDefault(key, "");
if (value.equals("") && !where.equals("datetime")) {
continue;
}
if ((!type.equals("") && !Arrays.asList("int", "long", "str").contains(type))) {
System.out.println("搜索参数类型不在固定值内[int,long,str]");
continue;
}
Object val = value;
switch (where) {
case "=":
case "<>":
case ">":
case ">=":
case "<":
case "<=":
if (type.equals("int")) {
val = Integer.parseInt(value);
} else if (type.equals("long")) {
val = Long.parseLong(value);
}
case "in":
case "notIn":
if (type.equals("int")) {
List<Integer> intData = new ArrayList<>();
for (String v : value.split(",")) {
intData.add(Integer.parseInt(v.trim()));
}
val = intData;
} else if (type.equals("long")){
List<Long> longData = new ArrayList<>();
for (String v : value.split(",")) {
longData.add(Long.parseLong(v.trim()));
}
val = longData;
}
}
switch (where) {
case "=":
queryWrapper.eq(field, val);
break;
case "<>":
queryWrapper.ne(field, val);
break;
case ">":
queryWrapper.gt(field, val);
break;
case ">=":
queryWrapper.ge(field, val);
break;
case "<":
queryWrapper.lt(field, val);
break;
case "<=":
queryWrapper.le(field, val);
break;
case "between":
String[] betArr = value.split(",");
if (type.equals("int")) {
queryWrapper.between(field, Integer.parseInt(betArr[0]), Integer.parseInt(betArr[1]));
} else if (type.equals("long")){
queryWrapper.between(field, Long.parseLong(betArr[0]), Long.parseLong(betArr[1]));
} else {
queryWrapper.between(field, betArr[0], betArr[1]);
}
break;
case "notBetween":
String[] notBetArr = value.split(",");
if (type.equals("int")) {
queryWrapper.notBetween(field, Integer.parseInt(notBetArr[0]), Integer.parseInt(notBetArr[1]));
} else if (type.equals("long")){
queryWrapper.notBetween(field, Long.parseLong(notBetArr[0]), Long.parseLong(notBetArr[1]));
} else {
queryWrapper.notBetween(field, notBetArr[0], notBetArr[1]);
}
break;
case "like":
queryWrapper.like(field, val);
break;
case "notLike":
queryWrapper.notLike(field, val);
break;
case "likeLeft":
queryWrapper.likeLeft(field, val);
break;
case "likeRight":
queryWrapper.likeRight(field, val);
break;
case "in":
queryWrapper.in(field, val);
break;
case "notIn":
queryWrapper.notIn(field, val);
break;
case "datetime":
String[] dateKeys = key.split("-");
String dateStart = params.getOrDefault(dateKeys[0].trim(), "");
if (dateStart.equals("")) {
continue;
}
String dateEnd = dateKeys.length > 1 ? params.getOrDefault(dateKeys[1].trim(), "") : "";
if (type.equals("long")) {
queryWrapper.ge(field, Long.parseLong(dateStart));
if (!dateEnd.equals("")) { queryWrapper.le(field, Long.parseLong(dateEnd)); }
} else {
queryWrapper.ge(field, TimeUtil.dateToTimestamp(dateStart));
if (!dateEnd.equals("")) { queryWrapper.le(field, TimeUtil.dateToTimestamp(dateEnd)); }
}
break;
}
}
}
}

View File

@@ -0,0 +1,28 @@
package com.hxkj.common.entity.system;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
/**
* 系统登录日志实体
*/
@Data
public class SystemLogLogin implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value="id", type= IdType.AUTO)
private Integer id;
private Integer adminId;
private String username;
private String ip;
private String os;
private String browser;
private String address;
private Integer status;
private Long createTime;
}

View File

@@ -1,4 +1,4 @@
package com.hxkj.common.entity.log;
package com.hxkj.common.entity.system;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
@@ -10,7 +10,7 @@ import java.io.Serializable;
* 系统操作日志实体
*/
@Data
public class LogOperate implements Serializable
public class SystemLogOperate implements Serializable
{
private static final long serialVersionUID = 1L;
@@ -23,6 +23,9 @@ public class LogOperate implements Serializable
private String ip;
private String url;
private String args;
private String error;
private String address;
private Integer status;
private Long startTime;
private Long endTime;
private Long taskTime;

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.AlbumCate;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 相册分类
*/
@Mapper
public interface AlbumCateMapper extends BaseMapper<AlbumCate> {
public interface AlbumCateMapper extends IBaseMapper<AlbumCate> {
}

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.Album;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 相册
*/
@Mapper
public interface AlbumMapper extends BaseMapper<Album> {
public interface AlbumMapper extends IBaseMapper<Album> {
}

View File

@@ -1,12 +0,0 @@
package com.hxkj.common.mapper.log;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.entity.log.LogOperate;
import org.apache.ibatis.annotations.Mapper;
/**
* 系统操作日志
*/
@Mapper
public interface LogOperateMapper extends BaseMapper<LogOperate> {
}

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemAdmin;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 系统管理员
*/
@Mapper
public interface SystemAdminMapper extends BaseMapper<SystemAdmin> {
public interface SystemAdminMapper extends IBaseMapper<SystemAdmin> {
}

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemConfig;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 系统配置
*/
@Mapper
public interface SystemConfigMapper extends BaseMapper<SystemConfig> {
public interface SystemConfigMapper extends IBaseMapper<SystemConfig> {
}

View File

@@ -0,0 +1,12 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemLogLogin;
import org.apache.ibatis.annotations.Mapper;
/**
* 系统登录日志
*/
@Mapper
public interface SystemLogLoginMapper extends IBaseMapper<SystemLogLogin> {
}

View File

@@ -0,0 +1,12 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemLogOperate;
import org.apache.ibatis.annotations.Mapper;
/**
* 系统操作日志
*/
@Mapper
public interface SystemLogOperateMapper extends IBaseMapper<SystemLogOperate> {
}

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemMenu;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 系统菜单
*/
@Mapper
public interface SystemMenuMapper extends BaseMapper<SystemMenu> {
public interface SystemMenuMapper extends IBaseMapper<SystemMenu> {
}

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemRole;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 系统角色
*/
@Mapper
public interface SystemRoleMapper extends BaseMapper<SystemRole> {
public interface SystemRoleMapper extends IBaseMapper<SystemRole> {
}

View File

@@ -1,6 +1,6 @@
package com.hxkj.common.mapper.system;
import com.hxkj.common.basics.BaseMapper;
import com.hxkj.common.core.basics.IBaseMapper;
import com.hxkj.common.entity.system.SystemRoleMenu;
import org.apache.ibatis.annotations.Mapper;
@@ -8,5 +8,5 @@ import org.apache.ibatis.annotations.Mapper;
* 角色菜单
*/
@Mapper
public interface SystemRoleMenuMapper extends BaseMapper<SystemRoleMenu> {
public interface SystemRoleMenuMapper extends IBaseMapper<SystemRoleMenu> {
}

View File

@@ -54,8 +54,8 @@ public class ArithUtil {
}
/**
* 提供(相对)精确的除法运算当发生除不尽的情况时精确到
* 小数点以后10位以后的数字四舍五入。
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商

View File

@@ -1,11 +1,16 @@
package com.hxkj.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.*;
/**
@@ -13,6 +18,8 @@ import java.util.*;
*/
public class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
/**
* 获取请求对象
*
@@ -98,7 +105,6 @@ public class HttpUtil {
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
@@ -109,10 +115,7 @@ public class HttpUtil {
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length()
if (ipAddress != null && ipAddress.length() > 15) {
// = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
@@ -140,4 +143,206 @@ public class HttpUtil {
return false;
}
/**
* 向指定URL发送GET方法的请求 (不带参)
*
* @param url 发送请求的 URL
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url) {
return sendGet(url, StringUtil.EMPTY);
}
/**
* 向指定URL发送GET方法的请求 (带参固定编码)
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
return sendGet(url, param, "UTF-8");
}
/**
* 向指定URL发送GET方法的请求 (带参指定编码)
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param contentType 编码类型
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param, String contentType) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = StringUtil.isNotBlank(param) ? url + "?" + param : url;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("rev - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
log.info("sendPost - {}", url);
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("rev - {}", result);
}
catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
/**
* 发送SSL的POST请求
*
* @param url 请求地址
* @param param 请求参数
* @return String
*/
public static String sendSSLPost(String url, String param) {
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try {
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret;
while ((ret = br.readLine()) != null) {
if (!"".equals(ret.trim())) {
result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
}
}
log.info("rev - {}", result);
conn.disconnect();
br.close();
}
catch (ConnectException e) {
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
}
/**
* SSL证书协议接口
*/
private static class TrustAnyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
/**
* POST请求安全接口
*/
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}

View File

@@ -2,6 +2,9 @@ package com.hxkj.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hxkj.common.config.GlobalConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
@@ -12,54 +15,81 @@ import java.net.UnknownHostException;
*/
public class IpUtil {
private static final Logger log = LoggerFactory.getLogger(IpUtil.class);
/**
* 获取客户端IP
*
* @param request 请求对象
* @return IP地址
*/
public static String getIpAddress(HttpServletRequest request)
{
if (request == null)
{
public static String getIpAddress(HttpServletRequest request) {
if (request == null) {
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
}
/**
* 根据IP获取所在地址
*
* @param ip Ip地址
* @return String (广州省 广州市)
*/
public static String getRealAddressByIP(String ip) {
String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
String UNKNOWN = "XX XX";
// 内网不查询
if (IpUtil.internalIp(ip)) {
return "内网IP";
}
if (GlobalConfig.isAddressEnabled) {
try {
String rspStr = HttpUtil.sendGet(IP_URL, "ip=" + ip + "&json=true", "GBK");
if (StringUtil.isEmpty(rspStr)) {
log.error("获取地理位置异常 {}", ip);
return UNKNOWN;
}
JSONObject obj = JSONObject.parseObject(rspStr);
String region = obj.getString("pro");
String city = obj.getString("city");
return String.format("%s %s", region, city);
}
catch (Exception e) {
log.error("获取地理位置异常 {}", ip);
}
}
return UNKNOWN;
}
/**
* 检查是否为内部IP地址
*
* @param ip IP地址
* @return 结果
*/
public static boolean internalIp(String ip)
{
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
public static boolean internalIp(String ip) {
byte[] address = textToNumericFormatV4(ip);
return internalIp(address) || "127.0.0.1".equals(ip);
}
/**
@@ -68,10 +98,8 @@ public class IpUtil {
* @param address byte地址
* @return 结果
*/
private static boolean internalIp(byte[] address)
{
if (address == null || address.length < 2)
{
private static boolean internalIp(byte[] address) {
if (address == null || address.length < 2) {
return true;
}
final byte b0 = address[0];
@@ -85,13 +113,11 @@ public class IpUtil {
// 192.168.x.x/16
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0)
{
switch (b0) {
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4)
{
if (b1 >= SECTION_3 && b1 <= SECTION_4) {
return true;
}
case SECTION_5:
@@ -109,25 +135,20 @@ public class IpUtil {
* @param text IPv4地址
* @return byte 字节
*/
public static byte[] textToNumericFormatV4(String text)
{
if (text.length() == 0)
{
public static byte[] textToNumericFormatV4(String text) {
if (text.length() == 0) {
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try
{
try {
long l;
int i;
switch (elements.length)
{
switch (elements.length) {
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L))
{
if ((l < 0L) || (l > 4294967295L)) {
return null;
}
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
@@ -137,14 +158,12 @@ public class IpUtil {
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L))
{
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L))
{
if ((l < 0L) || (l > 16777215L)) {
return null;
}
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
@@ -152,29 +171,24 @@ public class IpUtil {
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i)
{
for (i = 0; i < 2; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
{
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L))
{
if ((l < 0L) || (l > 65535L)) {
return null;
}
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i)
{
for (i = 0; i < 4; ++i) {
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
{
if ((l < 0L) || (l > 255L)) {
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
@@ -183,9 +197,7 @@ public class IpUtil {
default:
return null;
}
}
catch (NumberFormatException e)
{
} catch (NumberFormatException e) {
return null;
}
return bytes;
@@ -196,8 +208,7 @@ public class IpUtil {
*
* @return 本地IP地址
*/
public static String getHostIp()
{
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
}
@@ -210,8 +221,7 @@ public class IpUtil {
*
* @return 本地主机名
*/
public static String getHostName()
{
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
}
@@ -244,8 +254,7 @@ public class IpUtil {
* @param checkString 被检测的字符串
* @return 是否未知
*/
public static boolean isUnknown(String checkString)
{
public static boolean isUnknown(String checkString) {
return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
}

View File

@@ -22,8 +22,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue)
{
public static <T> T nvl(T value, T defaultValue) {
return value != null ? value : defaultValue;
}
@@ -33,8 +32,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param coll 要判断的Collection
* @return true为空 false非空
*/
public static boolean isEmpty(Collection<?> coll)
{
public static boolean isEmpty(Collection<?> coll) {
return isNull(coll) || coll.isEmpty();
}
@@ -44,8 +42,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param coll 要判断的Collection
* @return true非空 false
*/
public static boolean isNotEmpty(Collection<?> coll)
{
public static boolean isNotEmpty(Collection<?> coll) {
return !isEmpty(coll);
}
@@ -53,10 +50,9 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
** @return true为空 false非空
* @return true为空 false非空
*/
public static boolean isEmpty(Object[] objects)
{
public static boolean isEmpty(Object[] objects) {
return isNull(objects) || (objects.length == 0);
}
@@ -66,8 +62,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param objects 要判断的对象数组
* @return true非空 false
*/
public static boolean isNotEmpty(Object[] objects)
{
public static boolean isNotEmpty(Object[] objects) {
return !isEmpty(objects);
}
@@ -77,8 +72,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param map 要判断的Map
* @return true为空 false非空
*/
public static boolean isEmpty(Map<?, ?> map)
{
public static boolean isEmpty(Map<?, ?> map) {
return isNull(map) || map.isEmpty();
}
@@ -88,8 +82,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param map 要判断的Map
* @return true非空 false
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
public static boolean isNotEmpty(Map<?, ?> map) {
return !isEmpty(map);
}
@@ -99,8 +92,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param str String
* @return true为空 false非空
*/
public static boolean isEmpty(String str)
{
public static boolean isEmpty(String str) {
return isNull(str) || NULL_STR.equals(str.trim());
}
@@ -110,30 +102,27 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param str String
* @return true非空串 false空串
*/
public static boolean isNotEmpty(String str)
{
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* * 判断一个对象是否为空
* 判断一个对象是否为空
*
* @param object Object
* @return true为空 false非空
*/
public static boolean isNull(Object object)
{
public static boolean isNull(Object object) {
return object == null;
}
/**
* * 判断一个对象是否非空
* 判断一个对象是否非空
*
* @param object Object
* @return true非空 false
*/
public static boolean isNotNull(Object object)
{
public static boolean isNotNull(Object object) {
return !isNull(object);
}
@@ -143,16 +132,14 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param object 对象
* @return true是数组 false不是数组
*/
public static boolean isArray(Object object)
{
public static boolean isArray(Object object) {
return isNotNull(object) && object.getClass().isArray();
}
/**
* 去空格
*/
public static String trim(String str)
{
public static String trim(String str) {
return (str == null ? "" : str.trim());
}
@@ -163,24 +150,20 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start)
{
if (str == null)
{
public static String substring(final String str, int start) {
if (str == null) {
return NULL_STR;
}
if (start < 0)
{
if (start < 0) {
start = str.length() + start;
}
if (start < 0)
{
if (start < 0) {
start = 0;
}
if (start > str.length())
{
if (start > str.length()) {
return NULL_STR;
}
@@ -195,38 +178,32 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end)
{
if (str == null)
{
public static String substring(final String str, int start, int end) {
if (str == null) {
return NULL_STR;
}
if (end < 0)
{
if (end < 0) {
end = str.length() + end;
}
if (start < 0)
{
if (start < 0) {
start = str.length() + start;
}
if (end > str.length())
{
if (end > str.length()) {
end = str.length();
}
if (start > end)
{
if (start > end) {
return NULL_STR;
}
if (start < 0)
{
if (start < 0) {
start = 0;
}
if (end < 0)
{
if (end < 0) {
end = 0;
}
@@ -241,8 +218,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param sep 分隔符
* @return set集合
*/
public static Set<String> str2Set(String str, String sep)
{
public static Set<String> str2Set(String str, String sep) {
return new HashSet<String>(str2List(str, sep, true, false));
}
@@ -255,28 +231,23 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param trim 去掉首尾空白
* @return list集合
*/
public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim)
{
public static List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<String>();
if (StringUtil.isEmpty(str))
{
if (StringUtil.isEmpty(str)) {
return list;
}
// 过滤空白字符串
if (filterBlank && StringUtil.isBlank(str))
{
if (filterBlank && StringUtil.isBlank(str)) {
return list;
}
String[] split = str.split(sep);
for (String string : split)
{
if (filterBlank && StringUtil.isBlank(string))
{
for (String string : split) {
if (filterBlank && StringUtil.isBlank(string)) {
continue;
}
if (trim)
{
if (trim) {
string = string.trim();
}
list.add(string);
@@ -292,8 +263,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param searchCharSequences 需要检查的字符串数组
* @return 是否包含任意一个字符串
*/
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences)
{
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) {
if (isEmpty(cs) || isEmpty(searchCharSequences))
{
return false;
@@ -311,43 +281,34 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
/**
* 驼峰转下划线命名
*/
public static String toUnderScoreCase(String str)
{
if (str == null)
{
public static String toUnderScoreCase(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
boolean cureCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
boolean nextCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i > 0)
{
if (i > 0) {
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
} else {
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
cureCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
if (i < (str.length() - 1)) {
nextCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
if (preCharIsUpperCase && cureCharIsUpperCase && !nextCharIsUpperCase) {
sb.append(SEPARATOR);
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
} else if ((i != 0 && !preCharIsUpperCase) && cureCharIsUpperCase)
{
sb.append(SEPARATOR);
}
@@ -364,14 +325,10 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param strArr 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strArr)
{
if (str != null && strArr != null)
{
for (String s : strArr)
{
if (str.equalsIgnoreCase(trim(s)))
{
public static boolean inStringIgnoreCase(String str, String... strArr) {
if (str != null && strArr != null) {
for (String s : strArr) {
if (str.equalsIgnoreCase(trim(s))) {
return true;
}
}
@@ -387,27 +344,22 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name)
{
public static String convertToCamelCase(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
else if (!name.contains("_")) {
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
for (String camel : camels) {
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty())
{
if (camel.isEmpty()) {
continue;
}
// 首字母大写
@@ -423,30 +375,22 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param s 字符串
* @return 驼峰字符串
*/
public static String toCamelCase(String s)
{
if (s == null)
{
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR)
{
if (c == SEPARATOR) {
upperCase = true;
}
else if (upperCase)
{
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
} else {
sb.append(c);
}
}
@@ -460,16 +404,12 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param strArr 需要检查的字符串数组
* @return 是否匹配
*/
public static boolean matches(String str, List<String> strArr)
{
if (isEmpty(str) || isEmpty(strArr))
{
public static boolean matches(String str, List<String> strArr) {
if (isEmpty(str) || isEmpty(strArr)) {
return false;
}
for (String pattern : strArr)
{
if (isMatch(pattern, str))
{
for (String pattern : strArr) {
if (isMatch(pattern, str)) {
return true;
}
}
@@ -486,8 +426,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param url 需要匹配的url
* @return boolean
*/
public static boolean isMatch(String pattern, String url)
{
public static boolean isMatch(String pattern, String url) {
AntPathMatcher matcher = new AntPathMatcher();
return matcher.match(pattern, url);
}
@@ -500,8 +439,7 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param size 字符串指定长度
* @return 返回数字的字符串格式,该字符串为指定长度。
*/
public static String padL(final Number num, final int size)
{
public static String padL(final Number num, final int size) {
return padL(num.toString(), size, '0');
}
@@ -514,29 +452,20 @@ public class StringUtil extends org.apache.commons.lang3.StringUtils
* @param c 用于补齐的字符
* @return 返回指定长度的字符串,由原字符串左补齐或截取得到。
*/
public static String padL(final String s, final int size, final char c)
{
public static String padL(final String s, final int size, final char c) {
final StringBuilder sb = new StringBuilder(size);
if (s != null)
{
if (s != null) {
final int len = s.length();
if (s.length() <= size)
{
for (int i = size - len; i > 0; i--)
{
if (s.length() <= size) {
for (int i = size - len; i > 0; i--) {
sb.append(c);
}
sb.append(s);
}
else
{
} else {
return s.substring(len - size, len);
}
}
else
{
for (int i = size; i > 0; i--)
{
} else {
for (int i = size; i > 0; i--) {
sb.append(c);
}
}

View File

@@ -1,6 +1,9 @@
package com.hxkj.common.utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
@@ -445,4 +448,50 @@ public class TimeUtil {
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取几天前的日期列表
*
* @author fzr
* @param day 获取多少天
* @return [2022-03-29, 2022-03-30, 2022-03-31, 2022-04-01]
*/
public static List<String> daysAgoDate(Integer day) {
long time = TimeUtil.today().get(0);
List<String> data = new ArrayList<>();
for (int i=0; i<day; i++) {
if (i != 0) {
time -= 86400;
}
data.add(TimeUtil.timestampToDate(time, "yyyy-MM-dd"));
}
Collections.reverse(data);
return data;
}
/**
* 获取几天前的日期列表
*
* @author fzr
* @param day 获取多少天
* @return [1648483200, 1648569600, 1648656000, 1648742400]
*/
public static List<Long> daysAgoTime(Integer day) {
long time = TimeUtil.today().get(0);
List<Long> data = new ArrayList<>();
for (int i=0; i<day; i++) {
if (i != 0) {
time -= 86400;
}
data.add(time);
}
Collections.reverse(data);
return data;
}
}

View File

@@ -137,7 +137,7 @@ public class ToolsUtil {
*
* @author fzr
* @param json 对象
* @return Map
* @return Map<String, Object>
*/
public static Map<String, Object> jsonToMap(String json){
Type type = new TypeToken<Map<String, Object>>() {}.getType();
@@ -149,7 +149,7 @@ public class ToolsUtil {
*
* @author fzr
* @param json 对象
* @return Map
* @return Map<String, String>
*/
public static Map<String, String> jsonToStrMap(String json){
Type type = new TypeToken<Map<String, String>>() {}.getType();
@@ -160,7 +160,7 @@ public class ToolsUtil {
* 列表转字符串
*
* @author fzr
* @param list 列表
* @param list 列表 [1, 2, 4] -> 1,2,3
* @param separator 分割符号
* @return String
*/
@@ -176,7 +176,7 @@ public class ToolsUtil {
* 列表转字符串
*
* @author fzr
* @param list 列表
* @param list 列表 ["1", "2", "3"] -> 1,2,3
* @param separator 分割符号
* @return String
*/

View File

@@ -31,6 +31,7 @@
<apache-commons.version>2.10.0</apache-commons.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<gson.version>2.9.0</gson.version>
<bitwalker.version>1.2.4</bitwalker.version>
<qiniu.version>7.9.5</qiniu.version>
<qcloud-version>5.6.54</qcloud-version>
<tencentcloudapi.version>3.1.411</tencentcloudapi.version>
@@ -103,6 +104,12 @@
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- UserAgent -->
<dependency>
<groupId>nl.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>${bitwalker.version}</version>
</dependency>
<!-- 七牛云 -->
<dependency>
<groupId>com.qiniu</groupId>