Commit f0211db0 authored by dqjdda's avatar dqjdda
Browse files

优化代码

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