Commit e3c3ebb1 authored by dqjdda's avatar dqjdda
Browse files

代码优化

parents 78f08353 f0211db0
...@@ -20,38 +20,35 @@ public @interface Query { ...@@ -20,38 +20,35 @@ public @interface Query {
/** /**
* 连接查询的属性名,如User类中的dept * 连接查询的属性名,如User类中的dept
* @return
*/ */
String joinName() default ""; String joinName() default "";
/** /**
* 默认左连接 * 默认左连接
* @return
*/ */
Join join() default Join.LEFT; Join join() default Join.LEFT;
/** /**
* 多字段模糊搜索,仅支持String类型字段,多个用逗号隔开, 如@Query(blurry = "email,username") * 多字段模糊搜索,仅支持String类型字段,多个用逗号隔开, 如@Query(blurry = "email,username")
* @return
*/ */
String blurry() default ""; String blurry() default "";
enum Type { enum Type {
/** jie 2019/6/4 相等 */ // jie 2019/6/4 相等
EQUAL EQUAL
/** Dong ZhaoYang 2017/8/7 大于等于 */ // Dong ZhaoYang 2017/8/7 大于等于
, GREATER_THAN , GREATER_THAN
/** Dong ZhaoYang 2017/8/7 小于等于 */ // Dong ZhaoYang 2017/8/7 小于等于
, LESS_THAN , LESS_THAN
/** Dong ZhaoYang 2017/8/7 中模糊查询 */ // Dong ZhaoYang 2017/8/7 中模糊查询
, INNER_LIKE , INNER_LIKE
/** Dong ZhaoYang 2017/8/7 左模糊查询 */ // Dong ZhaoYang 2017/8/7 左模糊查询
, LEFT_LIKE , LEFT_LIKE
/** Dong ZhaoYang 2017/8/7 右模糊查询 */ // Dong ZhaoYang 2017/8/7 右模糊查询
, RIGHT_LIKE , RIGHT_LIKE
/** Dong ZhaoYang 2017/8/7 小于 */ // Dong ZhaoYang 2017/8/7 小于
, LESS_THAN_NQ , LESS_THAN_NQ
//** jie 2019/6/4 包含 */ // jie 2019/6/4 包含
, IN , IN
} }
......
...@@ -12,7 +12,6 @@ import org.aspectj.lang.annotation.Pointcut; ...@@ -12,7 +12,6 @@ import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript; import org.springframework.data.redis.core.script.RedisScript;
...@@ -23,10 +22,13 @@ import java.lang.reflect.Method; ...@@ -23,10 +22,13 @@ import java.lang.reflect.Method;
@Aspect @Aspect
@Component @Component
public class LimitAspect { public class LimitAspect {
@Autowired
private RedisTemplate redisTemplate; private final RedisTemplate redisTemplate;
private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class); private static final Logger logger = LoggerFactory.getLogger(LimitAspect.class);
public LimitAspect(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Pointcut("@annotation(me.zhengjie.annotation.Limit)") @Pointcut("@annotation(me.zhengjie.annotation.Limit)")
public void pointcut() { public void pointcut() {
...@@ -41,12 +43,10 @@ public class LimitAspect { ...@@ -41,12 +43,10 @@ public class LimitAspect {
LimitType limitType = limit.limitType(); LimitType limitType = limit.limitType();
String key = limit.key(); String key = limit.key();
if (StringUtils.isEmpty(key)) { if (StringUtils.isEmpty(key)) {
switch (limitType) { if (limitType == LimitType.IP) {
case IP: key = StringUtils.getIP(request);
key = StringUtils.getIP(request); } else {
break; key = signatureMethod.getName();
default:
key = signatureMethod.getName();
} }
} }
......
package me.zhengjie.exception; package me.zhengjie.exception;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.IntStream; import java.util.stream.IntStream;
...@@ -12,23 +11,17 @@ import java.util.stream.IntStream; ...@@ -12,23 +11,17 @@ import java.util.stream.IntStream;
*/ */
public class EntityExistException extends RuntimeException { public class EntityExistException extends RuntimeException {
public EntityExistException(Class clazz, Object... saveBodyParamsMap) { public EntityExistException(Class clazz, String field, String val) {
super(EntityExistException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, saveBodyParamsMap))); super(EntityExistException.generateMessage(clazz.getSimpleName(), toMap(field, val)));
} }
private static String generateMessage(String entity, Map<String, String> saveBodyParams) { private static String generateMessage(String entity, Map<Object, Object> saveBodyParams) {
return StringUtils.capitalize(entity) + return StringUtils.capitalize(entity) +
" 已存在 " + " 已存在 " +
saveBodyParams; saveBodyParams;
} }
private static <K, V> Map<K, V> toMap( private static Map<Object, Object> toMap(String... entries) {
Class<K> keyType, Class<V> valueType, Object... entries) { return new HashMap<Object, Object>(){{ put(entries[0], entries[1]); }};
if (entries.length % 2 == 1)
throw new IllegalArgumentException("Invalid entries");
return IntStream.range(0, entries.length / 2).map(i -> i * 2)
.collect(HashMap::new,
(m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])),
Map::putAll);
} }
} }
\ No newline at end of file
...@@ -12,24 +12,17 @@ import java.util.stream.IntStream; ...@@ -12,24 +12,17 @@ import java.util.stream.IntStream;
*/ */
public class EntityNotFoundException extends RuntimeException { public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(Class clazz, Object... searchParamsMap) { public EntityNotFoundException(Class clazz, String field, String val) {
super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), toMap(String.class, String.class, searchParamsMap))); super(EntityNotFoundException.generateMessage(clazz.getSimpleName(), toMap(field, val)));
} }
private static String generateMessage(String entity, Map<String, String> searchParams) { private static String generateMessage(String entity, Map<Object, Object> searchParams) {
return StringUtils.capitalize(entity) + return StringUtils.capitalize(entity) +
" 不存在 " + " 不存在 " +
searchParams; searchParams;
} }
private static <K, V> Map<K, V> toMap( private static Map<Object, Object> toMap(String... entries) {
Class<K> keyType, Class<V> valueType, Object... entries) { return new HashMap<Object, Object>(){{ put(entries[0], entries[1]); }};
if (entries.length % 2 == 1)
throw new IllegalArgumentException("Invalid entries");
return IntStream.range(0, entries.length / 2).map(i -> i * 2)
.collect(HashMap::new,
(m, i) -> m.put(keyType.cast(entries[i]), valueType.cast(entries[i + 1])),
Map::putAll);
} }
} }
\ No newline at end of file
...@@ -21,7 +21,7 @@ class ApiError { ...@@ -21,7 +21,7 @@ class ApiError {
timestamp = LocalDateTime.now(); timestamp = LocalDateTime.now();
} }
public ApiError(Integer status,String message) { ApiError(Integer status, String message) {
this(); this();
this.status = status; this.status = status;
this.message = message; this.message = message;
......
...@@ -11,6 +11,9 @@ import org.springframework.security.access.AccessDeniedException; ...@@ -11,6 +11,9 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Objects;
import static org.springframework.http.HttpStatus.*; import static org.springframework.http.HttpStatus.*;
/** /**
...@@ -23,8 +26,6 @@ public class GlobalExceptionHandler { ...@@ -23,8 +26,6 @@ public class GlobalExceptionHandler {
/** /**
* 处理所有不可知的异常 * 处理所有不可知的异常
* @param e
* @return
*/ */
@ExceptionHandler(Throwable.class) @ExceptionHandler(Throwable.class)
public ResponseEntity handleException(Throwable e){ public ResponseEntity handleException(Throwable e){
...@@ -36,8 +37,6 @@ public class GlobalExceptionHandler { ...@@ -36,8 +37,6 @@ public class GlobalExceptionHandler {
/** /**
* 处理 接口无权访问异常AccessDeniedException * 处理 接口无权访问异常AccessDeniedException
* @param e
* @return
*/ */
@ExceptionHandler(AccessDeniedException.class) @ExceptionHandler(AccessDeniedException.class)
public ResponseEntity handleAccessDeniedException(AccessDeniedException e){ public ResponseEntity handleAccessDeniedException(AccessDeniedException e){
...@@ -49,8 +48,6 @@ public class GlobalExceptionHandler { ...@@ -49,8 +48,6 @@ public class GlobalExceptionHandler {
/** /**
* 处理自定义异常 * 处理自定义异常
* @param e
* @return
*/ */
@ExceptionHandler(value = BadRequestException.class) @ExceptionHandler(value = BadRequestException.class)
public ResponseEntity<ApiError> badRequestException(BadRequestException e) { public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
...@@ -62,8 +59,6 @@ public class GlobalExceptionHandler { ...@@ -62,8 +59,6 @@ public class GlobalExceptionHandler {
/** /**
* 处理 EntityExist * 处理 EntityExist
* @param e
* @return
*/ */
@ExceptionHandler(value = EntityExistException.class) @ExceptionHandler(value = EntityExistException.class)
public ResponseEntity<ApiError> entityExistException(EntityExistException e) { public ResponseEntity<ApiError> entityExistException(EntityExistException e) {
...@@ -75,8 +70,6 @@ public class GlobalExceptionHandler { ...@@ -75,8 +70,6 @@ public class GlobalExceptionHandler {
/** /**
* 处理 EntityNotFound * 处理 EntityNotFound
* @param e
* @return
*/ */
@ExceptionHandler(value = EntityNotFoundException.class) @ExceptionHandler(value = EntityNotFoundException.class)
public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) { public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) {
...@@ -88,26 +81,20 @@ public class GlobalExceptionHandler { ...@@ -88,26 +81,20 @@ public class GlobalExceptionHandler {
/** /**
* 处理所有接口数据验证异常 * 处理所有接口数据验证异常
* @param e
* @returns
*/ */
@ExceptionHandler(MethodArgumentNotValidException.class) @ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
// 打印堆栈信息 // 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e)); log.error(ThrowableUtil.getStackTrace(e));
String[] str = e.getBindingResult().getAllErrors().get(0).getCodes()[1].split("\\."); String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
StringBuffer msg = new StringBuffer(str[1]+":"); ApiError apiError = new ApiError(BAD_REQUEST.value(), str[1] + ":" + e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
msg.append(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
ApiError apiError = new ApiError(BAD_REQUEST.value(),msg.toString());
return buildResponseEntity(apiError); return buildResponseEntity(apiError);
} }
/** /**
* 统一返回 * 统一返回
* @param apiError
* @return
*/ */
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) { private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus())); return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
} }
} }
...@@ -10,29 +10,21 @@ public interface EntityMapper<D, E> { ...@@ -10,29 +10,21 @@ public interface EntityMapper<D, E> {
/** /**
* DTO转Entity * DTO转Entity
* @param dto
* @return
*/ */
E toEntity(D dto); E toEntity(D dto);
/** /**
* Entity转DTO * Entity转DTO
* @param entity
* @return
*/ */
D toDto(E entity); D toDto(E entity);
/** /**
* DTO集合转Entity集合 * DTO集合转Entity集合
* @param dtoList
* @return
*/ */
List <E> toEntity(List<D> dtoList); List <E> toEntity(List<D> dtoList);
/** /**
* Entity集合转DTO集合 * Entity集合转DTO集合
* @param entityList
* @return
*/ */
List <D> toDto(List<E> entityList); List <D> toDto(List<E> entityList);
} }
...@@ -4,8 +4,7 @@ import com.alibaba.fastjson.JSON; ...@@ -4,8 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException; import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.Charset;
/** /**
* Value 序列化 * Value 序列化
...@@ -15,11 +14,9 @@ import java.nio.charset.Charset; ...@@ -15,11 +14,9 @@ import java.nio.charset.Charset;
*/ */
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> { public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz; private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) { FastJsonRedisSerializer(Class<T> clazz) {
super(); super();
this.clazz = clazz; this.clazz = clazz;
} }
...@@ -29,7 +26,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> { ...@@ -29,7 +26,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
if (t == null) { if (t == null) {
return new byte[0]; return new byte[0];
} }
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(StandardCharsets.UTF_8);
} }
@Override @Override
...@@ -37,7 +34,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> { ...@@ -37,7 +34,7 @@ public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
if (bytes == null || bytes.length <= 0) { if (bytes == null || bytes.length <= 0) {
return null; return null;
} }
String str = new String(bytes, DEFAULT_CHARSET); String str = new String(bytes, StandardCharsets.UTF_8);
return (T) JSON.parseObject(str, clazz); return (T) JSON.parseObject(str, clazz);
} }
......
...@@ -28,7 +28,6 @@ import java.time.Duration; ...@@ -28,7 +28,6 @@ import java.time.Duration;
@Slf4j @Slf4j
@Configuration @Configuration
@EnableCaching @EnableCaching
// 自动配置
@ConditionalOnClass(RedisOperations.class) @ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class) @EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig extends CachingConfigurerSupport { public class RedisConfig extends CachingConfigurerSupport {
...@@ -36,7 +35,6 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -36,7 +35,6 @@ public class RedisConfig extends CachingConfigurerSupport {
/** /**
* 设置 redis 数据默认过期时间,默认1天 * 设置 redis 数据默认过期时间,默认1天
* 设置@cacheable 序列化方式 * 设置@cacheable 序列化方式
* @return
*/ */
@Bean @Bean
public RedisCacheConfiguration redisCacheConfiguration(){ public RedisCacheConfiguration redisCacheConfiguration(){
...@@ -55,17 +53,16 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -55,17 +53,16 @@ public class RedisConfig extends CachingConfigurerSupport {
// value值的序列化采用fastJsonRedisSerializer // value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer); template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer); template.setHashValueSerializer(fastJsonRedisSerializer);
// 全局开启AutoType,这里方便开发,使用全局的方式
// 全局开启AutoType,不建议使用 ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单 // 建议使用这种方式,小范围指定白名单
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.service.dto");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.service.dto");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.system.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.quartz.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.monitor.domain"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.monitor.domain");
ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.security.security"); // ParserConfig.getGlobalInstance().addAccept("me.zhengjie.modules.security.security");
// key的序列化采用StringRedisSerializer // key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer()); template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer()); template.setHashKeySerializer(new StringRedisSerializer());
...@@ -75,8 +72,6 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -75,8 +72,6 @@ public class RedisConfig extends CachingConfigurerSupport {
/** /**
* 自定义缓存key生成策略,默认将使用该策略 * 自定义缓存key生成策略,默认将使用该策略
* 使用方法 @Cacheable
* @return
*/ */
@Bean @Bean
@Override @Override
...@@ -97,7 +92,7 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -97,7 +92,7 @@ public class RedisConfig extends CachingConfigurerSupport {
public CacheErrorHandler errorHandler() { public CacheErrorHandler errorHandler() {
// 异常处理,当Redis发生异常时,打印日志,但是程序正常走 // 异常处理,当Redis发生异常时,打印日志,但是程序正常走
log.info("初始化 -> [{}]", "Redis CacheErrorHandler"); log.info("初始化 -> [{}]", "Redis CacheErrorHandler");
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() { return new CacheErrorHandler() {
@Override @Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.error("Redis occur handleCacheGetError:key -> [{}]", key, e); log.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
...@@ -118,7 +113,6 @@ public class RedisConfig extends CachingConfigurerSupport { ...@@ -118,7 +113,6 @@ public class RedisConfig extends CachingConfigurerSupport {
log.error("Redis occur handleCacheClearError:", e); log.error("Redis occur handleCacheClearError:", e);
} }
}; };
return cacheErrorHandler;
} }
} }
...@@ -2,9 +2,10 @@ package me.zhengjie.redis; ...@@ -2,9 +2,10 @@ package me.zhengjie.redis;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/** /**
* 重写序列化器 * 重写序列化器
...@@ -15,15 +16,11 @@ public class StringRedisSerializer implements RedisSerializer<Object> { ...@@ -15,15 +16,11 @@ public class StringRedisSerializer implements RedisSerializer<Object> {
private final Charset charset; private final Charset charset;
private final String target = "\""; StringRedisSerializer() {
this(StandardCharsets.UTF_8);
private final String replacement = "";
public StringRedisSerializer() {
this(Charset.forName("UTF8"));
} }
public StringRedisSerializer(Charset charset) { private StringRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!"); Assert.notNull(charset, "Charset must not be null!");
this.charset = charset; this.charset = charset;
} }
...@@ -36,10 +33,10 @@ public class StringRedisSerializer implements RedisSerializer<Object> { ...@@ -36,10 +33,10 @@ public class StringRedisSerializer implements RedisSerializer<Object> {
@Override @Override
public byte[] serialize(Object object) { public byte[] serialize(Object object) {
String string = JSON.toJSONString(object); String string = JSON.toJSONString(object);
if (string == null) { if (StringUtils.isBlank(string)) {
return null; return null;
} }
string = string.replace(target, replacement); string = string.replace("\"", "");
return string.getBytes(charset); return string.getBytes(charset);
} }
} }
\ No newline at end of file
...@@ -55,7 +55,7 @@ public class SwaggerConfig { ...@@ -55,7 +55,7 @@ public class SwaggerConfig {
private ApiInfo apiInfo() { private ApiInfo apiInfo() {
return new ApiInfoBuilder() return new ApiInfoBuilder()
.title("eladmin 接口文档") .title("eladmin 接口文档")
.version("2.1") .version("2.2")
.build(); .build();
} }
......
...@@ -14,7 +14,7 @@ public class ElAdminConstant { ...@@ -14,7 +14,7 @@ public class ElAdminConstant {
/** /**
* 用于IP定位转换 * 用于IP定位转换
*/ */
public static final String REGION = "内网IP|内网IP"; static final String REGION = "内网IP|内网IP";
/** /**
* 常用接口 * 常用接口
......
...@@ -6,6 +6,7 @@ import javax.crypto.SecretKey; ...@@ -6,6 +6,7 @@ import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
/** /**
* 加密 * 加密
...@@ -27,23 +28,23 @@ public class EncryptUtils { ...@@ -27,23 +28,23 @@ public class EncryptUtils {
return null; return null;
} }
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8")); DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8")); IvParameterSpec iv = new IvParameterSpec(strParam.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return byte2hex( return byte2hex(
cipher.doFinal(source.getBytes("UTF-8"))).toUpperCase(); cipher.doFinal(source.getBytes(StandardCharsets.UTF_8))).toUpperCase();
} }
public static String byte2hex(byte[] inStr) { private static String byte2hex(byte[] inStr) {
String stmp; String stmp;
StringBuffer out = new StringBuffer(inStr.length * 2); StringBuilder out = new StringBuilder(inStr.length * 2);
for (int n = 0; n < inStr.length; n++) { for (byte b : inStr) {
stmp = Integer.toHexString(inStr[n] & 0xFF); stmp = Integer.toHexString(b & 0xFF);
if (stmp.length() == 1) { if (stmp.length() == 1) {
// 如果是0至F的单位字符串,则添加0 // 如果是0至F的单位字符串,则添加0
out.append("0" + stmp); out.append("0").append(stmp);
} else { } else {
out.append(stmp); out.append(stmp);
} }
...@@ -51,8 +52,7 @@ public class EncryptUtils { ...@@ -51,8 +52,7 @@ public class EncryptUtils {
return out.toString(); return out.toString();
} }
private static byte[] hex2byte(byte[] b) {
public static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0){ if ((b.length % 2) != 0){
throw new IllegalArgumentException("长度不是偶数"); throw new IllegalArgumentException("长度不是偶数");
} }
...@@ -66,9 +66,6 @@ public class EncryptUtils { ...@@ -66,9 +66,6 @@ public class EncryptUtils {
/** /**
* 对称解密 * 对称解密
* @param source
* @return
* @throws Exception
*/ */
public static String desDecrypt(String source) throws Exception { public static String desDecrypt(String source) throws Exception {
if (source == null || source.length() == 0){ if (source == null || source.length() == 0){
...@@ -76,10 +73,10 @@ public class EncryptUtils { ...@@ -76,10 +73,10 @@ public class EncryptUtils {
} }
byte[] src = hex2byte(source.getBytes()); byte[] src = hex2byte(source.getBytes());
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8")); DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec); SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8")); IvParameterSpec iv = new IvParameterSpec(strParam.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(src); byte[] retByte = cipher.doFinal(src);
return new String(retByte); return new String(retByte);
...@@ -87,8 +84,6 @@ public class EncryptUtils { ...@@ -87,8 +84,6 @@ public class EncryptUtils {
/** /**
* 密码加密 * 密码加密
* @param password
* @return
*/ */
public static String encryptPassword(String password){ public static String encryptPassword(String password){
return DigestUtils.md5DigestAsHex(password.getBytes()); return DigestUtils.md5DigestAsHex(password.getBytes());
......
...@@ -44,8 +44,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -44,8 +44,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* MultipartFile转File * MultipartFile转File
* @param multipartFile
* @return
*/ */
public static File toFile(MultipartFile multipartFile){ public static File toFile(MultipartFile multipartFile){
// 获取文件名 // 获取文件名
...@@ -65,21 +63,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -65,21 +63,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
} }
/** /**
* 删除 * 获取文件扩展名,不带 .
* @param files
*/
public static void deleteFile(File... files) {
for (File file : files) {
if (file.exists()) {
file.delete();
}
}
}
/**
* 获取文件扩展名
* @param filename
* @return
*/ */
public static String getExtensionName(String filename) { public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) { if ((filename != null) && (filename.length() > 0)) {
...@@ -93,8 +77,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -93,8 +77,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* Java文件操作 获取不带扩展名的文件名 * Java文件操作 获取不带扩展名的文件名
* @param filename
* @return
*/ */
public static String getFileNameNoEx(String filename) { public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) { if ((filename != null) && (filename.length() > 0)) {
...@@ -108,8 +90,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -108,8 +90,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* 文件大小转换 * 文件大小转换
* @param size
* @return
*/ */
public static String getSize(long size){ public static String getSize(long size){
String resultSize = ""; String resultSize = "";
...@@ -130,13 +110,9 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -130,13 +110,9 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* inputStream 转 File * inputStream 转 File
* @param ins
* @param name
* @return
* @throws Exception
*/ */
public static File inputStreamToFile(InputStream ins, String name) throws Exception{ static File inputStreamToFile(InputStream ins, String name) throws Exception{
File file = new File(System.getProperty("java.io.tmpdir") + name); File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
if (file.exists()) { if (file.exists()) {
return file; return file;
} }
...@@ -153,10 +129,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -153,10 +129,6 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
/** /**
* 将文件名解析成文件的上传路径 * 将文件名解析成文件的上传路径
*
* @param file
* @param filePath
* @return 上传到服务器的文件名
*/ */
public static File upload(MultipartFile file, String filePath) { public static File upload(MultipartFile file, String filePath) {
Date date = new Date(); Date date = new Date();
...@@ -170,7 +142,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -170,7 +142,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
File dest = new File(path); File dest = new File(path);
// 检测是否存在目录 // 检测是否存在目录
if (!dest.getParentFile().exists()) { if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹 dest.getParentFile().mkdirs();
} }
String d = dest.getPath(); String d = dest.getPath();
file.transferTo(dest);// 文件写入 file.transferTo(dest);// 文件写入
...@@ -187,16 +159,12 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -187,16 +159,12 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
byte[] buffer = new byte[(int)file.length()]; byte[] buffer = new byte[(int)file.length()];
inputFile.read(buffer); inputFile.read(buffer);
inputFile.close(); inputFile.close();
base64=new Base64().encode(buffer); base64=Base64.encode(buffer);
String encoded = base64.replaceAll("[\\s*\t\n\r]", ""); return base64.replaceAll("[\\s*\t\n\r]", "");
return encoded;
} }
/** /**
* 导出excel * 导出excel
* @param list
* @return
* @throws Exception
*/ */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException { public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx"; String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
...@@ -217,25 +185,26 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { ...@@ -217,25 +185,26 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
} }
public static String getFileType(String type) { public static String getFileType(String type) {
String documents = "txt doc pdf ppt pps xlsx xls"; String documents = "txt doc pdf ppt pps xlsx xls docx";
String music = "mp3 wav wma mpa ram ra aac aif m4a"; String music = "mp3 wav wma mpa ram ra aac aif m4a";
String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg"; String video = "avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg";
String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg"; String image = "bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg";
if(image.indexOf(type) != -1){ if(image.contains(type)){
return "图片"; return "图片";
} else if(documents.indexOf(type) != -1){ } else if(documents.contains(type)){
return "文档"; return "文档";
} else if(music.indexOf(type) != -1){ } else if(music.contains(type)){
return "音乐"; return "音乐";
} else if(video.indexOf(type) != -1){ } else if(video.contains(type)){
return "视频"; return "视频";
} else return "其他"; } else return "其他";
} }
public static String getFileTypeByMimeType(String type) { public static String getFileTypeByMimeType(String type) {
String mimeType = new MimetypesFileTypeMap().getContentType("." + type); String mimeType = new MimetypesFileTypeMap().getContentType("." + type);
return mimeType.split("\\/")[0]; return mimeType.split("/")[0];
} }
public static void checkSize(long maxSize, long size) { public static void checkSize(long maxSize, long size) {
if(size > (maxSize * 1024 * 1024)){ if(size > (maxSize * 1024 * 1024)){
throw new BadRequestException("文件超出规定大小"); throw new BadRequestException("文件超出规定大小");
......
...@@ -12,10 +12,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { ...@@ -12,10 +12,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/** /**
* List 分页 * List 分页
* @param page
* @param size
* @param list
* @return
*/ */
public static List toPage(int page, int size , List list) { public static List toPage(int page, int size , List list) {
int fromIndex = page * size; int fromIndex = page * size;
...@@ -32,8 +28,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { ...@@ -32,8 +28,6 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
/** /**
* Page 数据处理,预防redis反序列化报错 * Page 数据处理,预防redis反序列化报错
* @param page
* @return
*/ */
public static Map toPage(Page page) { public static Map toPage(Page page) {
Map<String,Object> map = new LinkedHashMap<>(2); Map<String,Object> map = new LinkedHashMap<>(2);
...@@ -43,9 +37,7 @@ public class PageUtil extends cn.hutool.core.util.PageUtil { ...@@ -43,9 +37,7 @@ public class PageUtil extends cn.hutool.core.util.PageUtil {
} }
/** /**
* @param object * 自定义分页
* @param totalElements
* @return
*/ */
public static Map toPage(Object object, Object totalElements) { public static Map toPage(Object object, Object totalElements) {
Map<String,Object> map = new LinkedHashMap<>(2); Map<String,Object> map = new LinkedHashMap<>(2);
......
...@@ -15,18 +15,12 @@ import java.util.*; ...@@ -15,18 +15,12 @@ import java.util.*;
@Slf4j @Slf4j
public class QueryHelp { public class QueryHelp {
/**
* @描述 : 转换为Predicate
* @作者 : Dong ZhaoYang
* @日期 : 2017/8/7
* @时间 : 17:25
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) { public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>(); List<Predicate> list = new ArrayList<>();
if(query == null){ if(query == null){
return cb.and(list.toArray(new Predicate[list.size()])); return cb.and(list.toArray(new Predicate[0]));
} }
try { try {
List<Field> fields = getAllFields(query.getClass(), new ArrayList<>()); List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());
...@@ -62,14 +56,14 @@ public class QueryHelp { ...@@ -62,14 +56,14 @@ public class QueryHelp {
for (String name : joinNames) { for (String name : joinNames) {
switch (q.join()) { switch (q.join()) {
case LEFT: case LEFT:
if(ObjectUtil.isNotEmpty(join)){ if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.LEFT); join = join.join(name, JoinType.LEFT);
} else { } else {
join = root.join(name, JoinType.LEFT); join = root.join(name, JoinType.LEFT);
} }
break; break;
case RIGHT: case RIGHT:
if(ObjectUtil.isNotEmpty(join)){ if(ObjectUtil.isNotNull(join)){
join = join.join(name, JoinType.RIGHT); join = join.join(name, JoinType.RIGHT);
} else { } else {
join = root.join(name, JoinType.RIGHT); join = root.join(name, JoinType.RIGHT);
...@@ -137,7 +131,7 @@ public class QueryHelp { ...@@ -137,7 +131,7 @@ public class QueryHelp {
return true; return true;
} }
for (int i = 0; i < strLen; i++) { for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(cs.charAt(i)) == false) { if (!Character.isWhitespace(cs.charAt(i))) {
return false; return false;
} }
} }
......
...@@ -3,6 +3,7 @@ package me.zhengjie.utils; ...@@ -3,6 +3,7 @@ package me.zhengjie.utils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/** /**
* 获取 HttpServletRequest * 获取 HttpServletRequest
...@@ -12,6 +13,6 @@ import javax.servlet.http.HttpServletRequest; ...@@ -12,6 +13,6 @@ import javax.servlet.http.HttpServletRequest;
public class RequestHolder { public class RequestHolder {
public static HttpServletRequest getHttpServletRequest() { public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
} }
} }
...@@ -28,8 +28,7 @@ public class SecurityUtils { ...@@ -28,8 +28,7 @@ public class SecurityUtils {
*/ */
public static String getUsername(){ public static String getUsername(){
Object obj = getUserDetails(); Object obj = getUserDetails();
JSONObject json = new JSONObject(obj); return new JSONObject(obj).get("username", String.class);
return json.get("username", String.class);
} }
/** /**
...@@ -38,7 +37,6 @@ public class SecurityUtils { ...@@ -38,7 +37,6 @@ public class SecurityUtils {
*/ */
public static Long getUserId(){ public static Long getUserId(){
Object obj = getUserDetails(); Object obj = getUserDetails();
JSONObject json = new JSONObject(obj); return new JSONObject(obj).get("id", Long.class);
return json.get("id", Long.class);
} }
} }
...@@ -26,6 +26,7 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB ...@@ -26,6 +26,7 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
/** /**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/ */
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) { public static <T> T getBean(String name) {
assertContextInjected(); assertContextInjected();
return (T) applicationContext.getBean(name); return (T) applicationContext.getBean(name);
......
...@@ -27,7 +27,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -27,7 +27,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* @param strs 字符串组 * @param strs 字符串组
* @return 包含返回true * @return 包含返回true
*/ */
public static boolean inString(String str, String... strs) { static boolean inString(String str, String... strs) {
if (str != null) { if (str != null) {
for (String s : strs) { for (String s : strs) {
if (str.equals(trim(s))) { if (str.equals(trim(s))) {
...@@ -92,7 +92,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -92,7 +92,7 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
* toCapitalizeCamelCase("hello_world") == "HelloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world" * toUnderScoreCase("helloWorld") = "hello_world"
*/ */
public static String toUnderScoreCase(String s) { static String toUnderScoreCase(String s) {
if (s == null) { if (s == null) {
return null; return null;
} }
...@@ -125,10 +125,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -125,10 +125,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** /**
* 获取ip地址 * 获取ip地址
* @param request
* @return
*/ */
public static String getIP(HttpServletRequest request) { public static String getIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for"); 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"); ip = request.getHeader("Proxy-Client-IP");
...@@ -145,32 +143,16 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { ...@@ -145,32 +143,16 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
/** /**
* 根据ip获取详细地址 * 根据ip获取详细地址
* @param ip
* @return
*/ */
public static String getCityInfo(String ip) { public static String getCityInfo(String ip) {
try { try {
String path = "ip2region/ip2region.db"; String path = "ip2region/ip2region.db";
String name = "ip2region.db"; String name = "ip2region.db";
int algorithm = DbSearcher.BTREE_ALGORITHM;
DbConfig config = new DbConfig(); DbConfig config = new DbConfig();
File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name); File file = FileUtil.inputStreamToFile(new ClassPathResource(path).getStream(), name);
DbSearcher searcher = new DbSearcher(config, file.getPath()); DbSearcher searcher = new DbSearcher(config, file.getPath());
Method method = null; Method method = null;
switch (algorithm) { method = searcher.getClass().getMethod("btreeSearch", String.class);
case DbSearcher.BTREE_ALGORITHM:
method = searcher.getClass().getMethod("btreeSearch", String.class);
break;
case DbSearcher.BINARY_ALGORITHM:
method = searcher.getClass().getMethod("binarySearch", String.class);
break;
case DbSearcher.MEMORY_ALGORITYM:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
default:
method = searcher.getClass().getMethod("memorySearch", String.class);
break;
}
DataBlock dataBlock = null; DataBlock dataBlock = null;
dataBlock = (DataBlock) method.invoke(searcher, ip); dataBlock = (DataBlock) method.invoke(searcher, ip);
String address = dataBlock.getRegion().replace("0|",""); String address = dataBlock.getRegion().replace("0|","");
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment