commit init
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
package com.cnbm.common.aspect;
|
||||
|
||||
import com.cnbm.common.exception.ErrorCode;
|
||||
import com.cnbm.common.exception.RenException;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:58 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class RedisAspect {
|
||||
private Logger logger = LoggerFactory.getLogger(getClass());
|
||||
/**
|
||||
* 是否开启redis缓存 true开启 false关闭
|
||||
*/
|
||||
@Value("${renren.redis.open: false}")
|
||||
private boolean open;
|
||||
|
||||
@Around("execution(* com.cnbm.common.redis.RedisUtils.*(..))")
|
||||
public Object around(ProceedingJoinPoint point) throws Throwable {
|
||||
Object result = null;
|
||||
if(open){
|
||||
try{
|
||||
result = point.proceed();
|
||||
}catch (Exception e){
|
||||
logger.error("redis error", e);
|
||||
throw new RenException(ErrorCode.REDIS_ERROR);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
119
ym-common/src/main/java/com/cnbm/common/constant/Constant.java
Normal file
119
ym-common/src/main/java/com/cnbm/common/constant/Constant.java
Normal file
@@ -0,0 +1,119 @@
|
||||
package com.cnbm.common.constant;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:57 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface Constant {
|
||||
/**
|
||||
* 成功
|
||||
*/
|
||||
int SUCCESS = 1;
|
||||
/**
|
||||
* 失败
|
||||
*/
|
||||
int FAIL = 0;
|
||||
/**
|
||||
* 菜单根节点标识
|
||||
*/
|
||||
Long MENU_ROOT = 0L;
|
||||
/**
|
||||
* 部门根节点标识
|
||||
*/
|
||||
Long DEPT_ROOT = 0L;
|
||||
/**
|
||||
* 升序
|
||||
*/
|
||||
String ASC = "asc";
|
||||
/**
|
||||
* 降序
|
||||
*/
|
||||
String DESC = "desc";
|
||||
/**
|
||||
* 创建时间字段名
|
||||
*/
|
||||
String CREATE_DATE = "create_date";
|
||||
|
||||
/**
|
||||
* 数据权限过滤
|
||||
*/
|
||||
String SQL_FILTER = "sqlFilter";
|
||||
/**
|
||||
* 当前页码
|
||||
*/
|
||||
String PAGE = "page";
|
||||
/**
|
||||
* 每页显示记录数
|
||||
*/
|
||||
String LIMIT = "limit";
|
||||
/**
|
||||
* 排序字段
|
||||
*/
|
||||
String ORDER_FIELD = "orderField";
|
||||
/**
|
||||
* 排序方式
|
||||
*/
|
||||
String ORDER = "order";
|
||||
/**
|
||||
* token header
|
||||
*/
|
||||
String TOKEN_HEADER = "token";
|
||||
|
||||
/**
|
||||
* 云存储配置KEY
|
||||
*/
|
||||
String CLOUD_STORAGE_CONFIG_KEY = "CLOUD_STORAGE_CONFIG_KEY";
|
||||
|
||||
/**
|
||||
* 定时任务状态
|
||||
*/
|
||||
enum ScheduleStatus {
|
||||
/**
|
||||
* 暂停
|
||||
*/
|
||||
PAUSE(0),
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL(1);
|
||||
|
||||
private int value;
|
||||
|
||||
ScheduleStatus(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 云服务商
|
||||
*/
|
||||
enum CloudService {
|
||||
/**
|
||||
* 七牛云
|
||||
*/
|
||||
QINIU(1),
|
||||
/**
|
||||
* 阿里云
|
||||
*/
|
||||
ALIYUN(2),
|
||||
/**
|
||||
* 腾讯云
|
||||
*/
|
||||
QCLOUD(3);
|
||||
|
||||
private int value;
|
||||
|
||||
CloudService(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.cnbm.common.convert;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:57 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Component
|
||||
public class DateConverter implements Converter<String, Date> {
|
||||
private static final Logger logger = LoggerFactory.getLogger(DateConverter.class);
|
||||
private static List<String> formatList = new ArrayList<>(5);
|
||||
static {
|
||||
formatList.add("yyyy-MM");
|
||||
formatList.add("yyyy-MM-dd");
|
||||
formatList.add("yyyy-MM-dd hh:mm");
|
||||
formatList.add("yyyy-MM-dd hh:mm:ss");
|
||||
formatList.add("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date convert(String source) {
|
||||
String value = source.trim();
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if(source.matches("^\\d{4}-\\d{1,2}$")){
|
||||
return parseDate(source, formatList.get(0));
|
||||
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
|
||||
return parseDate(source, formatList.get(1));
|
||||
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
|
||||
return parseDate(source, formatList.get(2));
|
||||
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
|
||||
return parseDate(source, formatList.get(3));
|
||||
}else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}.*T.*\\d{1,2}:\\d{1,2}:\\d{1,2}.*..*$")){
|
||||
return parseDate(source, formatList.get(4));
|
||||
} else {
|
||||
throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
* @param dateStr String 字符型日期
|
||||
* @param format String 格式
|
||||
* @return Date 日期
|
||||
*/
|
||||
public Date parseDate(String dateStr, String format) {
|
||||
Date date = null;
|
||||
try {
|
||||
DateFormat dateFormat = new SimpleDateFormat(format);
|
||||
date = dateFormat.parse(dateStr);
|
||||
} catch (Exception e) {
|
||||
logger.error("Formatted date with date: {} and format : {} ", dateStr, format);
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
}
|
||||
12
ym-common/src/main/java/com/cnbm/common/dao/BaseDao.java
Normal file
12
ym-common/src/main/java/com/cnbm/common/dao/BaseDao.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package com.cnbm.common.dao;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:02 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface BaseDao<T> extends BaseMapper<T> {
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.cnbm.common.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:03 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Data
|
||||
public abstract class BaseEntity implements Serializable {
|
||||
/**
|
||||
* id
|
||||
*/
|
||||
@TableId
|
||||
private Long id;
|
||||
/**
|
||||
* 创建者
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Long creator;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Date createDate;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.cnbm.common.exception;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:45 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface ErrorCode {
|
||||
int INTERNAL_SERVER_ERROR = 500;
|
||||
int UNAUTHORIZED = 401;
|
||||
|
||||
int NOT_NULL = 10001;
|
||||
int DB_RECORD_EXISTS = 10002;
|
||||
int PARAMS_GET_ERROR = 10003;
|
||||
int ACCOUNT_PASSWORD_ERROR = 10004;
|
||||
int ACCOUNT_DISABLE = 10005;
|
||||
int IDENTIFIER_NOT_NULL = 10006;
|
||||
int CAPTCHA_ERROR = 10007;
|
||||
int SUB_MENU_EXIST = 10008;
|
||||
int PASSWORD_ERROR = 10009;
|
||||
int SUPERIOR_DEPT_ERROR = 10011;
|
||||
int SUPERIOR_MENU_ERROR = 10012;
|
||||
int DATA_SCOPE_PARAMS_ERROR = 10013;
|
||||
int DEPT_SUB_DELETE_ERROR = 10014;
|
||||
int DEPT_USER_DELETE_ERROR = 10015;
|
||||
int UPLOAD_FILE_EMPTY = 10019;
|
||||
int TOKEN_NOT_EMPTY = 10020;
|
||||
int TOKEN_INVALID = 10021;
|
||||
int ACCOUNT_LOCK = 10022;
|
||||
int OSS_UPLOAD_FILE_ERROR = 10024;
|
||||
int REDIS_ERROR = 10027;
|
||||
int JOB_ERROR = 10028;
|
||||
int INVALID_SYMBOL = 10029;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.cnbm.common.exception;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/10 2:12 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class ExceptionUtils {
|
||||
|
||||
/**
|
||||
* 获取异常信息
|
||||
* @param ex 异常
|
||||
* @return 返回异常信息
|
||||
*/
|
||||
public static String getErrorStackTrace(Exception ex){
|
||||
StringWriter sw = null;
|
||||
PrintWriter pw = null;
|
||||
try {
|
||||
sw = new StringWriter();
|
||||
pw = new PrintWriter(sw, true);
|
||||
ex.printStackTrace(pw);
|
||||
}finally {
|
||||
try {
|
||||
if(pw != null) {
|
||||
pw.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
try {
|
||||
if(sw != null) {
|
||||
sw.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return sw.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.cnbm.common.exception;
|
||||
|
||||
import com.cnbm.common.utils.MessageUtils;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:54 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class RenException extends RuntimeException{
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private int code;
|
||||
private String msg;
|
||||
|
||||
public RenException(int code) {
|
||||
this.code = code;
|
||||
this.msg = MessageUtils.getMessage(code);
|
||||
}
|
||||
|
||||
public RenException(int code, String... params) {
|
||||
this.code = code;
|
||||
this.msg = MessageUtils.getMessage(code, params);
|
||||
}
|
||||
|
||||
public RenException(int code, Throwable e) {
|
||||
super(e);
|
||||
this.code = code;
|
||||
this.msg = MessageUtils.getMessage(code);
|
||||
}
|
||||
|
||||
public RenException(int code, Throwable e, String... params) {
|
||||
super(e);
|
||||
this.code = code;
|
||||
this.msg = MessageUtils.getMessage(code, params);
|
||||
}
|
||||
|
||||
public RenException(String msg) {
|
||||
super(msg);
|
||||
this.code = ErrorCode.INTERNAL_SERVER_ERROR;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public RenException(String msg, Throwable e) {
|
||||
super(msg, e);
|
||||
this.code = ErrorCode.INTERNAL_SERVER_ERROR;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
35
ym-common/src/main/java/com/cnbm/common/page/PageData.java
Normal file
35
ym-common/src/main/java/com/cnbm/common/page/PageData.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package com.cnbm.common.page;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:05 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Data
|
||||
@ApiModel(value = "分页数据")
|
||||
public class PageData<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "总记录数")
|
||||
private int total;
|
||||
|
||||
@ApiModelProperty(value = "列表数据")
|
||||
private List<T> list;
|
||||
|
||||
/**
|
||||
* 分页
|
||||
* @param list 列表数据
|
||||
* @param total 总记录数
|
||||
*/
|
||||
public PageData(List<T> list, long total) {
|
||||
this.list = list;
|
||||
this.total = (int)total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.cnbm.common.redis;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
|
||||
import lombok.extern.log4j.Log4j2;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:00 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Configuration
|
||||
@Log4j2
|
||||
public class RedisConfig {
|
||||
@Resource
|
||||
private RedisConnectionFactory factory;
|
||||
|
||||
@Bean
|
||||
public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(){
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
|
||||
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
|
||||
|
||||
return jackson2JsonRedisSerializer;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate() {
|
||||
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
|
||||
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());
|
||||
redisTemplate.setConnectionFactory(factory);
|
||||
return redisTemplate;
|
||||
}
|
||||
}
|
||||
58
ym-common/src/main/java/com/cnbm/common/redis/RedisKeys.java
Normal file
58
ym-common/src/main/java/com/cnbm/common/redis/RedisKeys.java
Normal file
@@ -0,0 +1,58 @@
|
||||
package com.cnbm.common.redis;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:01 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class RedisKeys {
|
||||
/**
|
||||
* 系统参数Key
|
||||
*/
|
||||
public static String getSysParamsKey(){
|
||||
return "sys:params";
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证码Key
|
||||
*/
|
||||
public static String getCaptchaKey(String uuid){
|
||||
return "sys:captcha:" + uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录用户Key
|
||||
*/
|
||||
public static String getSecurityUserKey(Long id){
|
||||
return "sys:security:user:" + id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统日志Key
|
||||
*/
|
||||
public static String getSysLogKey(){
|
||||
return "sys:log";
|
||||
}
|
||||
|
||||
/**
|
||||
* 系统资源Key
|
||||
*/
|
||||
public static String getSysResourceKey(){
|
||||
return "sys:resource";
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户菜单导航Key
|
||||
*/
|
||||
public static String getUserMenuNavKey(Long userId){
|
||||
return "sys:user:nav:" + userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户权限标识Key
|
||||
*/
|
||||
public static String getUserPermissionsKey(Long userId){
|
||||
return "sys:user:permissions:" + userId;
|
||||
}
|
||||
}
|
||||
|
||||
118
ym-common/src/main/java/com/cnbm/common/redis/RedisUtils.java
Normal file
118
ym-common/src/main/java/com/cnbm/common/redis/RedisUtils.java
Normal file
@@ -0,0 +1,118 @@
|
||||
package com.cnbm.common.redis;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.HashOperations;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:00 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Component
|
||||
public class RedisUtils {
|
||||
@Autowired
|
||||
private RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
/** 默认过期时长为24小时,单位:秒 */
|
||||
public final static long DEFAULT_EXPIRE = 60 * 60 * 24L;
|
||||
/** 过期时长为1小时,单位:秒 */
|
||||
public final static long HOUR_ONE_EXPIRE = 60 * 60 * 1L;
|
||||
/** 过期时长为6小时,单位:秒 */
|
||||
public final static long HOUR_SIX_EXPIRE = 60 * 60 * 6L;
|
||||
/** 不设置过期时长 */
|
||||
public final static long NOT_EXPIRE = -1L;
|
||||
|
||||
public void set(String key, Object value, long expire){
|
||||
redisTemplate.opsForValue().set(key, value);
|
||||
if(expire != NOT_EXPIRE){
|
||||
expire(key, expire);
|
||||
}
|
||||
}
|
||||
|
||||
public void set(String key, Object value){
|
||||
set(key, value, DEFAULT_EXPIRE);
|
||||
}
|
||||
|
||||
public Object get(String key, long expire) {
|
||||
Object value = redisTemplate.opsForValue().get(key);
|
||||
if(expire != NOT_EXPIRE){
|
||||
expire(key, expire);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public Object get(String key) {
|
||||
return get(key, NOT_EXPIRE);
|
||||
}
|
||||
|
||||
public void delete(String key) {
|
||||
redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
public void delete(Collection<String> keys) {
|
||||
redisTemplate.delete(keys);
|
||||
}
|
||||
|
||||
public Object hGet(String key, String field) {
|
||||
return redisTemplate.opsForHash().get(key, field);
|
||||
}
|
||||
|
||||
public Map<String, Object> hGetAll(String key){
|
||||
HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
|
||||
return hashOperations.entries(key);
|
||||
}
|
||||
|
||||
public void hMSet(String key, Map<String, Object> map){
|
||||
hMSet(key, map, DEFAULT_EXPIRE);
|
||||
}
|
||||
|
||||
public void hMSet(String key, Map<String, Object> map, long expire){
|
||||
redisTemplate.opsForHash().putAll(key, map);
|
||||
|
||||
if(expire != NOT_EXPIRE){
|
||||
expire(key, expire);
|
||||
}
|
||||
}
|
||||
|
||||
public void hSet(String key, String field, Object value) {
|
||||
hSet(key, field, value, DEFAULT_EXPIRE);
|
||||
}
|
||||
|
||||
public void hSet(String key, String field, Object value, long expire) {
|
||||
redisTemplate.opsForHash().put(key, field, value);
|
||||
|
||||
if(expire != NOT_EXPIRE){
|
||||
expire(key, expire);
|
||||
}
|
||||
}
|
||||
|
||||
public void expire(String key, long expire){
|
||||
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
public void hDel(String key, Object... fields){
|
||||
redisTemplate.opsForHash().delete(key, fields);
|
||||
}
|
||||
|
||||
public void leftPush(String key, Object value){
|
||||
leftPush(key, value, DEFAULT_EXPIRE);
|
||||
}
|
||||
|
||||
public void leftPush(String key, Object value, long expire){
|
||||
redisTemplate.opsForList().leftPush(key, value);
|
||||
|
||||
if(expire != NOT_EXPIRE){
|
||||
expire(key, expire);
|
||||
}
|
||||
}
|
||||
|
||||
public Object rightPop(String key){
|
||||
return redisTemplate.opsForList().rightPop(key);
|
||||
}
|
||||
}
|
||||
108
ym-common/src/main/java/com/cnbm/common/service/BaseService.java
Normal file
108
ym-common/src/main/java/com/cnbm/common/service/BaseService.java
Normal file
@@ -0,0 +1,108 @@
|
||||
package com.cnbm.common.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:06 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface BaseService<T> {
|
||||
Class<T> currentModelClass();
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 插入一条记录(选择字段,策略插入)
|
||||
* </p>
|
||||
*
|
||||
* @param entity 实体对象
|
||||
*/
|
||||
boolean insert(T entity);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 插入(批量),该方法不支持 Oracle、SQL Server
|
||||
* </p>
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
*/
|
||||
boolean insertBatch(Collection<T> entityList);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 插入(批量),该方法不支持 Oracle、SQL Server
|
||||
* </p>
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @param batchSize 插入批次数量
|
||||
*/
|
||||
boolean insertBatch(Collection<T> entityList, int batchSize);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 根据 ID 选择修改
|
||||
* </p>
|
||||
*
|
||||
* @param entity 实体对象
|
||||
*/
|
||||
boolean updateById(T entity);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 根据 whereEntity 条件,更新记录
|
||||
* </p>
|
||||
*
|
||||
* @param entity 实体对象
|
||||
* @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
|
||||
*/
|
||||
boolean update(T entity, Wrapper<T> updateWrapper);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 根据ID 批量更新
|
||||
* </p>
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
*/
|
||||
boolean updateBatchById(Collection<T> entityList);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 根据ID 批量更新
|
||||
* </p>
|
||||
*
|
||||
* @param entityList 实体对象集合
|
||||
* @param batchSize 更新批次数量
|
||||
*/
|
||||
boolean updateBatchById(Collection<T> entityList, int batchSize);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 根据 ID 查询
|
||||
* </p>
|
||||
*
|
||||
* @param id 主键ID
|
||||
*/
|
||||
T selectById(Serializable id);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 根据 ID 删除
|
||||
* </p>
|
||||
*
|
||||
* @param id 主键ID
|
||||
*/
|
||||
boolean deleteById(Serializable id);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 删除(根据ID 批量删除)
|
||||
* </p>
|
||||
*
|
||||
* @param idList 主键ID列表
|
||||
*/
|
||||
boolean deleteBatchIds(Collection<? extends Serializable> idList);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.cnbm.common.service;
|
||||
|
||||
import com.cnbm.common.page.PageData;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:06 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface CrudService<T, D> extends BaseService<T> {
|
||||
|
||||
PageData<D> page(Map<String, Object> params);
|
||||
|
||||
List<D> list(Map<String, Object> params);
|
||||
|
||||
D get(Long id);
|
||||
|
||||
void save(D dto);
|
||||
|
||||
void update(D dto);
|
||||
|
||||
void delete(Long[] ids);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.cnbm.common.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.enums.SqlMethod;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Constants;
|
||||
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
|
||||
import com.cnbm.common.constant.Constant;
|
||||
import com.cnbm.common.page.PageData;
|
||||
import com.cnbm.common.service.BaseService;
|
||||
import com.cnbm.common.utils.ConvertUtils;
|
||||
import org.apache.ibatis.binding.MapperMethod;
|
||||
import org.apache.ibatis.logging.Log;
|
||||
import org.apache.ibatis.logging.LogFactory;
|
||||
import org.apache.ibatis.session.SqlSession;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:10 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> implements BaseService<T> {
|
||||
@Autowired
|
||||
protected M baseDao;
|
||||
protected Log log = LogFactory.getLog(getClass());
|
||||
|
||||
/**
|
||||
* 获取分页对象
|
||||
*
|
||||
* @param params 分页查询参数
|
||||
* @param defaultOrderField 默认排序字段
|
||||
* @param isAsc 排序方式
|
||||
*/
|
||||
protected IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
|
||||
//分页参数
|
||||
long curPage = 1;
|
||||
long limit = 10;
|
||||
|
||||
if (params.get(Constant.PAGE) != null) {
|
||||
curPage = Long.parseLong((String) params.get(Constant.PAGE));
|
||||
}
|
||||
if (params.get(Constant.LIMIT) != null) {
|
||||
limit = Long.parseLong((String) params.get(Constant.LIMIT));
|
||||
}
|
||||
|
||||
//分页对象
|
||||
Page<T> page = new Page<>(curPage, limit);
|
||||
|
||||
//分页参数
|
||||
params.put(Constant.PAGE, page);
|
||||
|
||||
//排序字段
|
||||
String orderField = (String) params.get(Constant.ORDER_FIELD);
|
||||
String order = (String) params.get(Constant.ORDER);
|
||||
|
||||
//前端字段排序
|
||||
if (StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)) {
|
||||
if (Constant.ASC.equalsIgnoreCase(order)) {
|
||||
return page.addOrder(OrderItem.asc(orderField));
|
||||
} else {
|
||||
return page.addOrder(OrderItem.desc(orderField));
|
||||
}
|
||||
}
|
||||
|
||||
//没有排序字段,则不排序
|
||||
if (StringUtils.isBlank(defaultOrderField)) {
|
||||
return page;
|
||||
}
|
||||
|
||||
//默认排序
|
||||
if (isAsc) {
|
||||
page.addOrder(OrderItem.asc(defaultOrderField));
|
||||
} else {
|
||||
page.addOrder(OrderItem.desc(defaultOrderField));
|
||||
}
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
protected <T> PageData<T> getPageData(List<?> list, long total, Class<T> target) {
|
||||
List<T> targetList = ConvertUtils.sourceToTarget(list, target);
|
||||
|
||||
return new PageData<>(targetList, total);
|
||||
}
|
||||
|
||||
protected <T> PageData<T> getPageData(IPage page, Class<T> target) {
|
||||
return getPageData(page.getRecords(), page.getTotal(), target);
|
||||
}
|
||||
|
||||
protected void paramsToLike(Map<String, Object> params, String... likes) {
|
||||
for (String like : likes) {
|
||||
String val = (String) params.get(like);
|
||||
if (StringUtils.isNotBlank(val)) {
|
||||
params.put(like, "%" + val + "%");
|
||||
} else {
|
||||
params.put(like, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 判断数据库操作是否成功
|
||||
* </p>
|
||||
* <p>
|
||||
* 注意!! 该方法为 Integer 判断,不可传入 int 基本类型
|
||||
* </p>
|
||||
*
|
||||
* @param result 数据库操作返回影响条数
|
||||
* @return boolean
|
||||
*/
|
||||
protected static boolean retBool(Integer result) {
|
||||
return SqlHelper.retBool(result);
|
||||
}
|
||||
|
||||
protected Class<M> currentMapperClass() {
|
||||
return (Class<M>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<T> currentModelClass() {
|
||||
return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1);
|
||||
}
|
||||
|
||||
protected String getSqlStatement(SqlMethod sqlMethod) {
|
||||
return SqlHelper.getSqlStatement(this.currentMapperClass(), sqlMethod);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean insert(T entity) {
|
||||
return BaseServiceImpl.retBool(baseDao.insert(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean insertBatch(Collection<T> entityList) {
|
||||
return insertBatch(entityList, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean insertBatch(Collection<T> entityList, int batchSize) {
|
||||
String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);
|
||||
return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行批量操作
|
||||
*/
|
||||
protected <E> boolean executeBatch(Collection<E> list, int batchSize, BiConsumer<SqlSession, E> consumer) {
|
||||
return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean updateById(T entity) {
|
||||
return BaseServiceImpl.retBool(baseDao.updateById(entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean update(T entity, Wrapper<T> updateWrapper) {
|
||||
return BaseServiceImpl.retBool(baseDao.update(entity, updateWrapper));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateBatchById(Collection<T> entityList) {
|
||||
return updateBatchById(entityList, 30);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateBatchById(Collection<T> entityList, int batchSize) {
|
||||
String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID);
|
||||
return executeBatch(entityList, batchSize, (sqlSession, entity) -> {
|
||||
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
|
||||
param.put(Constants.ENTITY, entity);
|
||||
sqlSession.update(sqlStatement, param);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public T selectById(Serializable id) {
|
||||
return baseDao.selectById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteById(Serializable id) {
|
||||
return SqlHelper.retBool(baseDao.deleteById(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteBatchIds(Collection<? extends Serializable> idList) {
|
||||
return SqlHelper.retBool(baseDao.deleteBatchIds(idList));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.cnbm.common.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
|
||||
import com.cnbm.common.page.PageData;
|
||||
import com.cnbm.common.service.CrudService;
|
||||
import com.cnbm.common.utils.ConvertUtils;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:11 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public abstract class CrudServiceImpl<M extends BaseMapper<T>, T, D> extends BaseServiceImpl<M, T> implements CrudService<T, D> {
|
||||
|
||||
protected Class<D> currentDtoClass() {
|
||||
return (Class<D>) ReflectionKit.getSuperClassGenericType(getClass(), CrudServiceImpl.class, 2);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageData<D> page(Map<String, Object> params) {
|
||||
IPage<T> page = baseDao.selectPage(
|
||||
getPage(params, null, false),
|
||||
getWrapper(params)
|
||||
);
|
||||
|
||||
return getPageData(page, currentDtoClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<D> list(Map<String, Object> params) {
|
||||
List<T> entityList = baseDao.selectList(getWrapper(params));
|
||||
|
||||
return ConvertUtils.sourceToTarget(entityList, currentDtoClass());
|
||||
}
|
||||
|
||||
public abstract QueryWrapper<T> getWrapper(Map<String, Object> params);
|
||||
|
||||
@Override
|
||||
public D get(Long id) {
|
||||
T entity = baseDao.selectById(id);
|
||||
|
||||
return ConvertUtils.sourceToTarget(entity, currentDtoClass());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(D dto) {
|
||||
T entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
|
||||
insert(entity);
|
||||
|
||||
//copy主键值到dto
|
||||
BeanUtils.copyProperties(entity, dto);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(D dto) {
|
||||
T entity = ConvertUtils.sourceToTarget(dto, currentModelClass());
|
||||
updateById(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Long[] ids) {
|
||||
baseDao.deleteBatchIds(Arrays.asList(ids));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:48 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class ConvertUtils {
|
||||
private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);
|
||||
|
||||
public static <T> T sourceToTarget(Object source, Class<T> target){
|
||||
if(source == null){
|
||||
return null;
|
||||
}
|
||||
T targetObject = null;
|
||||
try {
|
||||
targetObject = target.newInstance();
|
||||
BeanUtils.copyProperties(source, targetObject);
|
||||
} catch (Exception e) {
|
||||
logger.error("convert error ", e);
|
||||
}
|
||||
|
||||
return targetObject;
|
||||
}
|
||||
|
||||
public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target){
|
||||
if(sourceList == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
List targetList = new ArrayList<>(sourceList.size());
|
||||
try {
|
||||
for(Object source : sourceList){
|
||||
T targetObject = target.newInstance();
|
||||
BeanUtils.copyProperties(source, targetObject);
|
||||
targetList.add(targetObject);
|
||||
}
|
||||
}catch (Exception e){
|
||||
logger.error("convert error ", e);
|
||||
}
|
||||
|
||||
return targetList;
|
||||
}
|
||||
}
|
||||
174
ym-common/src/main/java/com/cnbm/common/utils/DateUtils.java
Normal file
174
ym-common/src/main/java/com/cnbm/common/utils/DateUtils.java
Normal file
@@ -0,0 +1,174 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.LocalDate;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:47 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class DateUtils {
|
||||
/** 时间格式(yyyy-MM-dd) */
|
||||
public final static String DATE_PATTERN = "yyyy-MM-dd";
|
||||
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
|
||||
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
/**
|
||||
* 日期格式化 日期格式为:yyyy-MM-dd
|
||||
* @param date 日期
|
||||
* @return 返回yyyy-MM-dd格式日期
|
||||
*/
|
||||
public static String format(Date date) {
|
||||
return format(date, DATE_PATTERN);
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期格式化 日期格式为:yyyy-MM-dd
|
||||
* @param date 日期
|
||||
* @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN
|
||||
* @return 返回yyyy-MM-dd格式日期
|
||||
*/
|
||||
public static String format(Date date, String pattern) {
|
||||
if(date != null){
|
||||
SimpleDateFormat df = new SimpleDateFormat(pattern);
|
||||
return df.format(date);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期解析
|
||||
* @param date 日期
|
||||
* @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN
|
||||
* @return 返回Date
|
||||
*/
|
||||
public static Date parse(String date, String pattern) {
|
||||
try {
|
||||
return new SimpleDateFormat(pattern).parse(date);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转换成日期
|
||||
* @param strDate 日期字符串
|
||||
* @param pattern 日期的格式,如:DateUtils.DATE_TIME_PATTERN
|
||||
*/
|
||||
public static Date stringToDate(String strDate, String pattern) {
|
||||
if (StringUtils.isBlank(strDate)){
|
||||
return null;
|
||||
}
|
||||
|
||||
DateTimeFormatter fmt = DateTimeFormat.forPattern(pattern);
|
||||
return fmt.parseLocalDateTime(strDate).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据周数,获取开始日期、结束日期
|
||||
* @param week 周期 0本周,-1上周,-2上上周,1下周,2下下周
|
||||
* @return 返回date[0]开始日期、date[1]结束日期
|
||||
*/
|
||||
public static Date[] getWeekStartAndEnd(int week) {
|
||||
DateTime dateTime = new DateTime();
|
||||
LocalDate date = new LocalDate(dateTime.plusWeeks(week));
|
||||
|
||||
date = date.dayOfWeek().withMinimumValue();
|
||||
Date beginDate = date.toDate();
|
||||
Date endDate = date.plusDays(6).toDate();
|
||||
return new Date[]{beginDate, endDate};
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【秒】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param seconds 秒数,负数为减
|
||||
* @return 加/减几秒后的日期
|
||||
*/
|
||||
public static Date addDateSeconds(Date date, int seconds) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusSeconds(seconds).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【分钟】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param minutes 分钟数,负数为减
|
||||
* @return 加/减几分钟后的日期
|
||||
*/
|
||||
public static Date addDateMinutes(Date date, int minutes) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusMinutes(minutes).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【小时】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param hours 小时数,负数为减
|
||||
* @return 加/减几小时后的日期
|
||||
*/
|
||||
public static Date addDateHours(Date date, int hours) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusHours(hours).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【天】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param days 天数,负数为减
|
||||
* @return 加/减几天后的日期
|
||||
*/
|
||||
public static Date addDateDays(Date date, int days) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusDays(days).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【周】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param weeks 周数,负数为减
|
||||
* @return 加/减几周后的日期
|
||||
*/
|
||||
public static Date addDateWeeks(Date date, int weeks) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusWeeks(weeks).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【月】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param months 月数,负数为减
|
||||
* @return 加/减几月后的日期
|
||||
*/
|
||||
public static Date addDateMonths(Date date, int months) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusMonths(months).toDate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 对日期的【年】进行加/减
|
||||
*
|
||||
* @param date 日期
|
||||
* @param years 年数,负数为减
|
||||
* @return 加/减几年后的日期
|
||||
*/
|
||||
public static Date addDateYears(Date date, int years) {
|
||||
DateTime dateTime = new DateTime(date);
|
||||
return dateTime.plusYears(years).toDate();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import cn.afterturn.easypoi.excel.ExcelExportUtil;
|
||||
import cn.afterturn.easypoi.excel.entity.ExportParams;
|
||||
import com.cnbm.common.utils.DateUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/10 9:57 AM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class ExcelUtils {
|
||||
|
||||
/**
|
||||
* Excel导出
|
||||
*
|
||||
* @param response response
|
||||
* @param fileName 文件名
|
||||
* @param list 数据List
|
||||
* @param pojoClass 对象Class
|
||||
*/
|
||||
public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> list,
|
||||
Class<?> pojoClass) throws IOException {
|
||||
if(StringUtils.isBlank(fileName)){
|
||||
//当前日期
|
||||
fileName = DateUtils.format(new Date());
|
||||
}
|
||||
|
||||
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, list);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.setHeader("content-Type", "application/vnd.ms-excel");
|
||||
response.setHeader("Content-Disposition",
|
||||
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
|
||||
ServletOutputStream out = response.getOutputStream();
|
||||
workbook.write(out);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Excel导出,先sourceList转换成List<targetClass>,再导出
|
||||
*
|
||||
* @param response response
|
||||
* @param fileName 文件名
|
||||
* @param sourceList 原数据List
|
||||
* @param targetClass 目标对象Class
|
||||
*/
|
||||
public static void exportExcelToTarget(HttpServletResponse response, String fileName, Collection<?> sourceList,
|
||||
Class<?> targetClass) throws Exception {
|
||||
List targetList = new ArrayList<>(sourceList.size());
|
||||
for(Object source : sourceList){
|
||||
Object target = targetClass.newInstance();
|
||||
BeanUtils.copyProperties(source, target);
|
||||
targetList.add(target);
|
||||
}
|
||||
|
||||
exportExcel(response, fileName, targetList, targetClass);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.context.request.RequestAttributes;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:49 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class HttpContextUtils {
|
||||
public static HttpServletRequest getHttpServletRequest() {
|
||||
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
|
||||
if(requestAttributes == null){
|
||||
return null;
|
||||
}
|
||||
|
||||
return ((ServletRequestAttributes) requestAttributes).getRequest();
|
||||
}
|
||||
|
||||
public static Map<String, String> getParameterMap(HttpServletRequest request) {
|
||||
Enumeration<String> parameters = request.getParameterNames();
|
||||
|
||||
Map<String, String> params = new HashMap<>();
|
||||
while (parameters.hasMoreElements()) {
|
||||
String parameter = parameters.nextElement();
|
||||
String value = request.getParameter(parameter);
|
||||
if (StringUtils.isNotBlank(value)) {
|
||||
params.put(parameter, value);
|
||||
}
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
public static String getDomain(){
|
||||
HttpServletRequest request = getHttpServletRequest();
|
||||
StringBuffer url = request.getRequestURL();
|
||||
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
|
||||
}
|
||||
|
||||
public static String getOrigin(){
|
||||
HttpServletRequest request = getHttpServletRequest();
|
||||
return request.getHeader(HttpHeaders.ORIGIN);
|
||||
}
|
||||
}
|
||||
49
ym-common/src/main/java/com/cnbm/common/utils/IpUtils.java
Normal file
49
ym-common/src/main/java/com/cnbm/common/utils/IpUtils.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:50 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class IpUtils {
|
||||
private static Logger logger = LoggerFactory.getLogger(IpUtils.class);
|
||||
|
||||
/**
|
||||
* 获取IP地址
|
||||
*
|
||||
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
|
||||
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
|
||||
*/
|
||||
public static String getIpAddr(HttpServletRequest request) {
|
||||
String unknown = "unknown";
|
||||
String ip = null;
|
||||
try {
|
||||
ip = request.getHeader("x-forwarded-for");
|
||||
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("IPUtils ERROR ", e);
|
||||
}
|
||||
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
67
ym-common/src/main/java/com/cnbm/common/utils/JsonUtils.java
Normal file
67
ym-common/src/main/java/com/cnbm/common/utils/JsonUtils.java
Normal file
@@ -0,0 +1,67 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:50 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class JsonUtils {
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
public static String toJsonString(Object object) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(object);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T parseObject(String text, Class<T> clazz) {
|
||||
if (StrUtil.isEmpty(text)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(text, clazz);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
|
||||
if (ArrayUtil.isEmpty(bytes)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(bytes, clazz);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T parseObject(String text, TypeReference<T> typeReference) {
|
||||
try {
|
||||
return objectMapper.readValue(text, typeReference);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> List<T> parseArray(String text, Class<T> clazz) {
|
||||
if (StrUtil.isEmpty(text)) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import org.springframework.context.MessageSource;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:42 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class MessageUtils {
|
||||
private static MessageSource messageSource;
|
||||
static {
|
||||
messageSource = (MessageSource)SpringContextUtils.getBean("messageSource");
|
||||
}
|
||||
|
||||
public static String getMessage(int code){
|
||||
return getMessage(code, new String[0]);
|
||||
}
|
||||
|
||||
public static String getMessage(int code, String... params){
|
||||
return messageSource.getMessage(code+"", params, LocaleContextHolder.getLocale());
|
||||
}
|
||||
}
|
||||
89
ym-common/src/main/java/com/cnbm/common/utils/Result.java
Normal file
89
ym-common/src/main/java/com/cnbm/common/utils/Result.java
Normal file
@@ -0,0 +1,89 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import com.cnbm.common.exception.ErrorCode;
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:41 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@ApiModel(value = "响应")
|
||||
public class Result<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
/**
|
||||
* 编码:0表示成功,其他值表示失败
|
||||
*/
|
||||
@ApiModelProperty(value = "编码:0表示成功,其他值表示失败")
|
||||
private int code = 0;
|
||||
/**
|
||||
* 消息内容
|
||||
*/
|
||||
@ApiModelProperty(value = "消息内容")
|
||||
private String msg = "success";
|
||||
/**
|
||||
* 响应数据
|
||||
*/
|
||||
@ApiModelProperty(value = "响应数据")
|
||||
private T data;
|
||||
|
||||
public Result<T> ok(T data) {
|
||||
this.setData(data);
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean success(){
|
||||
return code == 0;
|
||||
}
|
||||
|
||||
public Result<T> error() {
|
||||
this.code = ErrorCode.INTERNAL_SERVER_ERROR;
|
||||
this.msg = MessageUtils.getMessage(this.code);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result<T> error(int code) {
|
||||
this.code = code;
|
||||
this.msg = MessageUtils.getMessage(this.code);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result<T> error(int code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Result<T> error(String msg) {
|
||||
this.code = ErrorCode.INTERNAL_SERVER_ERROR;
|
||||
this.msg = msg;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:43 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@Component
|
||||
public class SpringContextUtils implements ApplicationContextAware {
|
||||
public static ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
SpringContextUtils.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public static Object getBean(String name) {
|
||||
return applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> requiredType) {
|
||||
return applicationContext.getBean(requiredType);
|
||||
}
|
||||
|
||||
public static <T> T getBean(String name, Class<T> requiredType) {
|
||||
return applicationContext.getBean(name, requiredType);
|
||||
}
|
||||
|
||||
public static boolean containsBean(String name) {
|
||||
return applicationContext.containsBean(name);
|
||||
}
|
||||
|
||||
public static boolean isSingleton(String name) {
|
||||
return applicationContext.isSingleton(name);
|
||||
}
|
||||
|
||||
public static Class<? extends Object> getType(String name) {
|
||||
return applicationContext.getType(name);
|
||||
}
|
||||
|
||||
}
|
||||
50
ym-common/src/main/java/com/cnbm/common/utils/TreeNode.java
Normal file
50
ym-common/src/main/java/com/cnbm/common/utils/TreeNode.java
Normal file
@@ -0,0 +1,50 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:51 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class TreeNode<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
/**
|
||||
* 主键
|
||||
*/
|
||||
private Long id;
|
||||
/**
|
||||
* 上级ID
|
||||
*/
|
||||
private Long pid;
|
||||
/**
|
||||
* 子节点列表
|
||||
*/
|
||||
private List<T> children = new ArrayList<>();
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getPid() {
|
||||
return pid;
|
||||
}
|
||||
|
||||
public void setPid(Long pid) {
|
||||
this.pid = pid;
|
||||
}
|
||||
|
||||
public List<T> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(List<T> children) {
|
||||
this.children = children;
|
||||
}
|
||||
}
|
||||
69
ym-common/src/main/java/com/cnbm/common/utils/TreeUtils.java
Normal file
69
ym-common/src/main/java/com/cnbm/common/utils/TreeUtils.java
Normal file
@@ -0,0 +1,69 @@
|
||||
package com.cnbm.common.utils;
|
||||
|
||||
import com.cnbm.common.validator.AssertUtils;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:52 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class TreeUtils {
|
||||
/**
|
||||
* 根据pid,构建树节点
|
||||
*/
|
||||
public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) {
|
||||
//pid不能为空
|
||||
AssertUtils.isNull(pid, "pid");
|
||||
|
||||
List<T> treeList = new ArrayList<>();
|
||||
for(T treeNode : treeNodes) {
|
||||
if (pid.equals(treeNode.getPid())) {
|
||||
treeList.add(findChildren(treeNodes, treeNode));
|
||||
}
|
||||
}
|
||||
|
||||
return treeList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找子节点
|
||||
*/
|
||||
private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
|
||||
for(T treeNode : treeNodes) {
|
||||
if(rootNode.getId().equals(treeNode.getPid())) {
|
||||
rootNode.getChildren().add(findChildren(treeNodes, treeNode));
|
||||
}
|
||||
}
|
||||
return rootNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建树节点
|
||||
*/
|
||||
public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
|
||||
List<T> result = new ArrayList<>();
|
||||
|
||||
//list转map
|
||||
Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
|
||||
for(T treeNode : treeNodes){
|
||||
nodeMap.put(treeNode.getId(), treeNode);
|
||||
}
|
||||
|
||||
for(T node : nodeMap.values()) {
|
||||
T parent = nodeMap.get(node.getPid());
|
||||
if(parent != null && !(node.getId().equals(parent.getId()))){
|
||||
parent.getChildren().add(node);
|
||||
continue;
|
||||
}
|
||||
|
||||
result.add(node);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.cnbm.common.validator;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import com.cnbm.common.exception.ErrorCode;
|
||||
import com.cnbm.common.exception.RenException;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 2:53 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class AssertUtils {
|
||||
public static void isBlank(String str, String... params) {
|
||||
isBlank(str, ErrorCode.NOT_NULL, params);
|
||||
}
|
||||
|
||||
public static void isBlank(String str, Integer code, String... params) {
|
||||
if(code == null){
|
||||
throw new RenException(ErrorCode.NOT_NULL, "code");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(str)) {
|
||||
throw new RenException(code, params);
|
||||
}
|
||||
}
|
||||
|
||||
public static void isNull(Object object, String... params) {
|
||||
isNull(object, ErrorCode.NOT_NULL, params);
|
||||
}
|
||||
|
||||
public static void isNull(Object object, Integer code, String... params) {
|
||||
if(code == null){
|
||||
throw new RenException(ErrorCode.NOT_NULL, "code");
|
||||
}
|
||||
|
||||
if (object == null) {
|
||||
throw new RenException(code, params);
|
||||
}
|
||||
}
|
||||
|
||||
public static void isArrayEmpty(Object[] array, String... params) {
|
||||
isArrayEmpty(array, ErrorCode.NOT_NULL, params);
|
||||
}
|
||||
|
||||
public static void isArrayEmpty(Object[] array, Integer code, String... params) {
|
||||
if(code == null){
|
||||
throw new RenException(ErrorCode.NOT_NULL, "code");
|
||||
}
|
||||
|
||||
if(ArrayUtil.isEmpty(array)){
|
||||
throw new RenException(code, params);
|
||||
}
|
||||
}
|
||||
|
||||
public static void isListEmpty(List<?> list, String... params) {
|
||||
isListEmpty(list, ErrorCode.NOT_NULL, params);
|
||||
}
|
||||
|
||||
public static void isListEmpty(List<?> list, Integer code, String... params) {
|
||||
if(code == null){
|
||||
throw new RenException(ErrorCode.NOT_NULL, "code");
|
||||
}
|
||||
|
||||
if(CollUtil.isEmpty(list)){
|
||||
throw new RenException(code, params);
|
||||
}
|
||||
}
|
||||
|
||||
public static void isMapEmpty(Map map, String... params) {
|
||||
isMapEmpty(map, ErrorCode.NOT_NULL, params);
|
||||
}
|
||||
|
||||
public static void isMapEmpty(Map map, Integer code, String... params) {
|
||||
if(code == null){
|
||||
throw new RenException(ErrorCode.NOT_NULL, "code");
|
||||
}
|
||||
|
||||
if(MapUtil.isEmpty(map)){
|
||||
throw new RenException(code, params);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.cnbm.common.validator;
|
||||
|
||||
import com.cnbm.common.exception.RenException;
|
||||
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
|
||||
import org.springframework.context.i18n.LocaleContextHolder;
|
||||
import org.springframework.context.support.ResourceBundleMessageSource;
|
||||
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;
|
||||
|
||||
import javax.validation.ConstraintViolation;
|
||||
import javax.validation.Validation;
|
||||
import javax.validation.Validator;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:15 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public class ValidatorUtils {
|
||||
|
||||
private static ResourceBundleMessageSource getMessageSource() {
|
||||
ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
|
||||
bundleMessageSource.setDefaultEncoding("UTF-8");
|
||||
bundleMessageSource.setBasenames("i18n/validation");
|
||||
return bundleMessageSource;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验对象
|
||||
* @param object 待校验对象
|
||||
* @param groups 待校验的组
|
||||
*/
|
||||
public static void validateEntity(Object object, Class<?>... groups)
|
||||
throws RenException {
|
||||
Locale.setDefault(LocaleContextHolder.getLocale());
|
||||
Validator validator = Validation.byDefaultProvider().configure().messageInterpolator(
|
||||
new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(getMessageSource())))
|
||||
.buildValidatorFactory().getValidator();
|
||||
|
||||
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
|
||||
if (!constraintViolations.isEmpty()) {
|
||||
ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
|
||||
throw new RenException(constraint.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.cnbm.common.validator.group;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:16 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface AddGroup {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.cnbm.common.validator.group;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:16 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface DefaultGroup {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.cnbm.common.validator.group;
|
||||
|
||||
import javax.validation.GroupSequence;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:16 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
@GroupSequence({AddGroup.class, UpdateGroup.class})
|
||||
public interface Group {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.cnbm.common.validator.group;
|
||||
|
||||
/**
|
||||
* @Author weihongyang
|
||||
* @Date 2022/6/7 3:16 PM
|
||||
* @Version 1.0
|
||||
*/
|
||||
public interface UpdateGroup {
|
||||
}
|
||||
Reference in New Issue
Block a user