From 8b5c04cb048dc95f0fd392102c79d8464fb13cab Mon Sep 17 00:00:00 2001 From: dqjdda <201507802@qq.com> Date: Sun, 29 Sep 2019 15:12:49 +0800 Subject: [PATCH 1/4] =?UTF-8?q?2.2=20=E4=BB=A3=E7=A0=81=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/me/zhengjie/utils/FileUtil.java | 7 ++----- .../me/zhengjie/service/impl/LocalStorageServiceImpl.java | 4 +++- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java index d0d24649..95f6d1dc 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java @@ -5,10 +5,8 @@ import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.poi.excel.BigExcelWriter; import cn.hutool.poi.excel.ExcelUtil; -import cn.hutool.poi.excel.ExcelWriter; import me.zhengjie.exception.BadRequestException; import org.springframework.web.multipart.MultipartFile; - import javax.activation.MimetypesFileTypeMap; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; @@ -233,11 +231,10 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { return "视频"; } else return "其他"; } + public static String getFileTypeByMimeType(String type) { -// URLConnection.guessContentTypeFromName("." + type) -// way 2 new MimetypesFileTypeMap().getContentType("."+ "txt") 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)){ diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java index fd917699..f0830b5f 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java @@ -63,7 +63,9 @@ public class LocalStorageServiceImpl implements LocalStorageService { public LocalStorageDTO create(String name, MultipartFile multipartFile) { FileUtil.checkSize(maxSize, multipartFile.getSize()); String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename()); - String type = FileUtil.getFileTypeByMimeType(suffix); + // 可自行选择方式 +// String type = FileUtil.getFileTypeByMimeType(suffix); + String type = FileUtil.getFileType(suffix); File file = FileUtil.upload(multipartFile, path + type + File.separator); try { name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name; From 5693f178c662baa4e31ef19eea9214d20de7f176 Mon Sep 17 00:00:00 2001 From: linlihuiyang Date: Thu, 17 Oct 2019 16:21:47 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E8=A7=A3=E5=86=B3Gson=E6=89=BE=E4=B8=8D?= =?UTF-8?q?=E5=88=B0=E5=8C=85=E7=9A=84bug=20(#141)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 解决Gson找不到包的bug * 解决Gson找不到包的bug --- .../me/zhengjie/service/impl/QiNiuServiceImpl.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java index 36888cb1..530a363d 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java @@ -1,6 +1,6 @@ package me.zhengjie.service.impl; -import com.google.gson.Gson; +import com.alibaba.fastjson.JSON; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; @@ -16,7 +16,11 @@ import me.zhengjie.repository.QiNiuConfigRepository; import me.zhengjie.repository.QiniuContentRepository; import me.zhengjie.service.QiNiuService; import me.zhengjie.service.dto.QiniuQueryCriteria; -import me.zhengjie.utils.*; +import me.zhengjie.utils.FileUtil; +import me.zhengjie.utils.PageUtil; +import me.zhengjie.utils.QiNiuUtil; +import me.zhengjie.utils.QueryHelp; +import me.zhengjie.utils.ValidationUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Pageable; @@ -24,6 +28,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; + import java.util.Optional; /** @@ -91,7 +96,8 @@ public class QiNiuServiceImpl implements QiNiuService { } Response response = uploadManager.put(file.getBytes(), key, upToken); //解析上传成功的结果 - DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); + + DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class); //存入数据库 QiniuContent qiniuContent = new QiniuContent(); qiniuContent.setSuffix(FileUtil.getExtensionName(putRet.key)); From a8230bbde7ed8dfb3712a2464b384af395b1eaaa Mon Sep 17 00:00:00 2001 From: ZHAO Jian Date: Mon, 21 Oct 2019 09:34:35 +0800 Subject: [PATCH 3/4] java.io.FileNotFoundException: /tmpip2region.db (Permission denied) (#146) * bug fix java.io.FileNotFoundException: /tmpip2region.db (Permission denied) --- eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java index 95f6d1dc..b6a04ac1 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java @@ -136,7 +136,7 @@ public class FileUtil extends cn.hutool.core.io.FileUtil { * @throws Exception */ public 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()) { return file; } From f0211db02c35941a244592b7d43ff866174b923a Mon Sep 17 00:00:00 2001 From: dqjdda <201507802@qq.com> Date: Thu, 24 Oct 2019 09:31:57 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/me/zhengjie/annotation/Query.java | 19 +++--- .../java/me/zhengjie/aspect/LimitAspect.java | 18 +++--- .../exception/EntityExistException.java | 17 ++---- .../exception/EntityNotFoundException.java | 17 ++---- .../zhengjie/exception/handler/ApiError.java | 2 +- .../handler/GlobalExceptionHandler.java | 25 ++------ .../java/me/zhengjie/mapper/EntityMapper.java | 8 --- .../redis/FastJsonRedisSerializer.java | 11 ++-- .../java/me/zhengjie/redis/RedisConfig.java | 26 ++++---- .../zhengjie/redis/StringRedisSerializer.java | 17 +++--- .../me/zhengjie/swagger2/SwaggerConfig.java | 2 +- .../me/zhengjie/utils/ElAdminConstant.java | 2 +- .../java/me/zhengjie/utils/EncryptUtils.java | 29 ++++----- .../main/java/me/zhengjie/utils/FileUtil.java | 54 ++++------------- .../main/java/me/zhengjie/utils/PageUtil.java | 10 +--- .../java/me/zhengjie/utils/QueryHelp.java | 14 ++--- .../java/me/zhengjie/utils/RequestHolder.java | 3 +- .../java/me/zhengjie/utils/SecurityUtils.java | 6 +- .../zhengjie/utils/SpringContextHolder.java | 1 + .../java/me/zhengjie/utils/StringUtils.java | 26 ++------ .../java/me/zhengjie/utils/ThrowableUtil.java | 14 ++--- .../me/zhengjie/utils/TranslatorUtil.java | 17 ++---- .../me/zhengjie/utils/ValidationUtil.java | 5 +- .../src/main/resources/config/application.yml | 2 +- .../EladminSystemApplicationTests.java | 1 + .../java/me/zhengjie/domain/AlipayConfig.java | 40 ++++--------- .../java/me/zhengjie/domain/EmailConfig.java | 16 ++--- .../main/java/me/zhengjie/domain/Picture.java | 3 - .../java/me/zhengjie/domain/QiniuConfig.java | 20 ++----- .../java/me/zhengjie/domain/QiniuContent.java | 24 ++------ .../me/zhengjie/domain/VerificationCode.java | 21 ++----- .../java/me/zhengjie/domain/vo/EmailVo.java | 4 +- .../java/me/zhengjie/domain/vo/TradeVo.java | 32 +++------- .../repository/LocalStorageRepository.java | 2 +- .../repository/PictureRepository.java | 2 +- .../repository/QiNiuConfigRepository.java | 2 +- .../repository/QiniuContentRepository.java | 6 +- .../me/zhengjie/rest/AliPayController.java | 58 +++++++++--------- .../me/zhengjie/rest/EmailController.java | 26 ++++---- .../zhengjie/rest/LocalStorageController.java | 32 +++++----- .../me/zhengjie/rest/PictureController.java | 47 +++++++-------- .../me/zhengjie/rest/QiniuController.java | 59 +++++++------------ .../rest/VerificationCodeController.java | 20 ++++--- .../me/zhengjie/service/AlipayService.java | 22 +++---- .../me/zhengjie/service/EmailService.java | 12 ++-- .../zhengjie/service/LocalStorageService.java | 28 +++++---- .../me/zhengjie/service/PictureService.java | 16 ++--- .../me/zhengjie/service/QiNiuService.java | 31 +++++----- .../service/VerificationCodeService.java | 5 +- .../service/impl/AlipayServiceImpl.java | 39 ++---------- .../service/impl/EmailServiceImpl.java | 29 ++++----- .../service/impl/LocalStorageServiceImpl.java | 19 +++--- .../service/impl/PictureServiceImpl.java | 15 +++-- .../service/impl/QiNiuServiceImpl.java | 29 ++++----- .../impl/VerificationCodeServiceImpl.java | 7 ++- .../me/zhengjie/utils/AliPayStatusEnum.java | 2 - .../java/me/zhengjie/utils/AlipayUtils.java | 17 ++---- .../java/me/zhengjie/utils/QiNiuUtil.java | 22 +++---- 58 files changed, 387 insertions(+), 666 deletions(-) diff --git a/eladmin-common/src/main/java/me/zhengjie/annotation/Query.java b/eladmin-common/src/main/java/me/zhengjie/annotation/Query.java index dc394b82..2375c266 100644 --- a/eladmin-common/src/main/java/me/zhengjie/annotation/Query.java +++ b/eladmin-common/src/main/java/me/zhengjie/annotation/Query.java @@ -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 } diff --git a/eladmin-common/src/main/java/me/zhengjie/aspect/LimitAspect.java b/eladmin-common/src/main/java/me/zhengjie/aspect/LimitAspect.java index 555774c7..e4d6fb0d 100644 --- a/eladmin-common/src/main/java/me/zhengjie/aspect/LimitAspect.java +++ b/eladmin-common/src/main/java/me/zhengjie/aspect/LimitAspect.java @@ -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(); } } diff --git a/eladmin-common/src/main/java/me/zhengjie/exception/EntityExistException.java b/eladmin-common/src/main/java/me/zhengjie/exception/EntityExistException.java index 23417a72..f9aaa553 100644 --- a/eladmin-common/src/main/java/me/zhengjie/exception/EntityExistException.java +++ b/eladmin-common/src/main/java/me/zhengjie/exception/EntityExistException.java @@ -1,7 +1,6 @@ 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 saveBodyParams) { + private static String generateMessage(String entity, Map saveBodyParams) { return StringUtils.capitalize(entity) + " 已存在 " + saveBodyParams; } - private static Map toMap( - Class keyType, Class 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 toMap(String... entries) { + return new HashMap(){{ put(entries[0], entries[1]); }}; } } \ No newline at end of file diff --git a/eladmin-common/src/main/java/me/zhengjie/exception/EntityNotFoundException.java b/eladmin-common/src/main/java/me/zhengjie/exception/EntityNotFoundException.java index 31e1cbdf..c7e2db6a 100644 --- a/eladmin-common/src/main/java/me/zhengjie/exception/EntityNotFoundException.java +++ b/eladmin-common/src/main/java/me/zhengjie/exception/EntityNotFoundException.java @@ -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 searchParams) { + private static String generateMessage(String entity, Map searchParams) { return StringUtils.capitalize(entity) + " 不存在 " + searchParams; } - private static Map toMap( - Class keyType, Class 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 toMap(String... entries) { + return new HashMap(){{ put(entries[0], entries[1]); }}; } - } \ No newline at end of file diff --git a/eladmin-common/src/main/java/me/zhengjie/exception/handler/ApiError.java b/eladmin-common/src/main/java/me/zhengjie/exception/handler/ApiError.java index db43891e..433104f9 100644 --- a/eladmin-common/src/main/java/me/zhengjie/exception/handler/ApiError.java +++ b/eladmin-common/src/main/java/me/zhengjie/exception/handler/ApiError.java @@ -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; diff --git a/eladmin-common/src/main/java/me/zhengjie/exception/handler/GlobalExceptionHandler.java b/eladmin-common/src/main/java/me/zhengjie/exception/handler/GlobalExceptionHandler.java index 5e58c784..44467412 100644 --- a/eladmin-common/src/main/java/me/zhengjie/exception/handler/GlobalExceptionHandler.java +++ b/eladmin-common/src/main/java/me/zhengjie/exception/handler/GlobalExceptionHandler.java @@ -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 badRequestException(BadRequestException e) { @@ -62,8 +59,6 @@ public class GlobalExceptionHandler { /** * 处理 EntityExist - * @param e - * @return */ @ExceptionHandler(value = EntityExistException.class) public ResponseEntity entityExistException(EntityExistException e) { @@ -75,8 +70,6 @@ public class GlobalExceptionHandler { /** * 处理 EntityNotFound - * @param e - * @return */ @ExceptionHandler(value = EntityNotFoundException.class) public ResponseEntity entityNotFoundException(EntityNotFoundException e) { @@ -88,26 +81,20 @@ public class GlobalExceptionHandler { /** * 处理所有接口数据验证异常 - * @param e - * @returns */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity 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 buildResponseEntity(ApiError apiError) { - return new ResponseEntity(apiError, HttpStatus.valueOf(apiError.getStatus())); + return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus())); } } diff --git a/eladmin-common/src/main/java/me/zhengjie/mapper/EntityMapper.java b/eladmin-common/src/main/java/me/zhengjie/mapper/EntityMapper.java index 98bc55db..be8696dd 100644 --- a/eladmin-common/src/main/java/me/zhengjie/mapper/EntityMapper.java +++ b/eladmin-common/src/main/java/me/zhengjie/mapper/EntityMapper.java @@ -10,29 +10,21 @@ public interface EntityMapper { /** * DTO转Entity - * @param dto - * @return */ E toEntity(D dto); /** * Entity转DTO - * @param entity - * @return */ D toDto(E entity); /** * DTO集合转Entity集合 - * @param dtoList - * @return */ List toEntity(List dtoList); /** * Entity集合转DTO集合 - * @param entityList - * @return */ List toDto(List entityList); } diff --git a/eladmin-common/src/main/java/me/zhengjie/redis/FastJsonRedisSerializer.java b/eladmin-common/src/main/java/me/zhengjie/redis/FastJsonRedisSerializer.java index d2e224c8..23f7e9d7 100644 --- a/eladmin-common/src/main/java/me/zhengjie/redis/FastJsonRedisSerializer.java +++ b/eladmin-common/src/main/java/me/zhengjie/redis/FastJsonRedisSerializer.java @@ -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 implements RedisSerializer { - public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); - private Class clazz; - public FastJsonRedisSerializer(Class clazz) { + FastJsonRedisSerializer(Class clazz) { super(); this.clazz = clazz; } @@ -29,7 +26,7 @@ public class FastJsonRedisSerializer implements RedisSerializer { 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 implements RedisSerializer { 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); } diff --git a/eladmin-common/src/main/java/me/zhengjie/redis/RedisConfig.java b/eladmin-common/src/main/java/me/zhengjie/redis/RedisConfig.java index beb0170a..e84e2af3 100644 --- a/eladmin-common/src/main/java/me/zhengjie/redis/RedisConfig.java +++ b/eladmin-common/src/main/java/me/zhengjie/redis/RedisConfig.java @@ -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; } } diff --git a/eladmin-common/src/main/java/me/zhengjie/redis/StringRedisSerializer.java b/eladmin-common/src/main/java/me/zhengjie/redis/StringRedisSerializer.java index e0f54f10..0419d5cb 100644 --- a/eladmin-common/src/main/java/me/zhengjie/redis/StringRedisSerializer.java +++ b/eladmin-common/src/main/java/me/zhengjie/redis/StringRedisSerializer.java @@ -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 { 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 { @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 diff --git a/eladmin-common/src/main/java/me/zhengjie/swagger2/SwaggerConfig.java b/eladmin-common/src/main/java/me/zhengjie/swagger2/SwaggerConfig.java index 207873cd..d451bea5 100644 --- a/eladmin-common/src/main/java/me/zhengjie/swagger2/SwaggerConfig.java +++ b/eladmin-common/src/main/java/me/zhengjie/swagger2/SwaggerConfig.java @@ -55,7 +55,7 @@ public class SwaggerConfig { private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("eladmin 接口文档") - .version("2.1") + .version("2.2") .build(); } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/ElAdminConstant.java b/eladmin-common/src/main/java/me/zhengjie/utils/ElAdminConstant.java index 89bfeaae..47199dba 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/ElAdminConstant.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/ElAdminConstant.java @@ -14,7 +14,7 @@ public class ElAdminConstant { /** * 用于IP定位转换 */ - public static final String REGION = "内网IP|内网IP"; + static final String REGION = "内网IP|内网IP"; /** * 常用接口 diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/EncryptUtils.java b/eladmin-common/src/main/java/me/zhengjie/utils/EncryptUtils.java index 5bddf3a5..a1d49c3f 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/EncryptUtils.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/EncryptUtils.java @@ -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()); diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java index b6a04ac1..d64475d3 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/FileUtil.java @@ -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> 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)){ diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java index 8ca67b0a..a04e0377 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/PageUtil.java @@ -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 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 map = new LinkedHashMap<>(2); diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/QueryHelp.java b/eladmin-common/src/main/java/me/zhengjie/utils/QueryHelp.java index 0ea14822..c467c47c 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/QueryHelp.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/QueryHelp.java @@ -15,18 +15,12 @@ import java.util.*; @Slf4j public class QueryHelp { - /** - * @描述 : 转换为Predicate - * @作者 : Dong ZhaoYang - * @日期 : 2017/8/7 - * @时间 : 17:25 - */ @SuppressWarnings("unchecked") public static Predicate getPredicate(Root root, Q query, CriteriaBuilder cb) { List 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 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; } } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/RequestHolder.java b/eladmin-common/src/main/java/me/zhengjie/utils/RequestHolder.java index 343b451b..f9458838 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/RequestHolder.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/RequestHolder.java @@ -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(); } } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java b/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java index e040c111..1b0fc75f 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java @@ -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); } } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/SpringContextHolder.java b/eladmin-common/src/main/java/me/zhengjie/utils/SpringContextHolder.java index e4bfcbbc..7e1af48e 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/SpringContextHolder.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/SpringContextHolder.java @@ -26,6 +26,7 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB /** * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型. */ + @SuppressWarnings("unchecked") public static T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/StringUtils.java b/eladmin-common/src/main/java/me/zhengjie/utils/StringUtils.java index fd2647d0..3d6763ed 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/StringUtils.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/StringUtils.java @@ -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|",""); diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/ThrowableUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/ThrowableUtil.java index 6faa8c61..3c1f3f7a 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/ThrowableUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/ThrowableUtil.java @@ -2,30 +2,23 @@ package me.zhengjie.utils; import me.zhengjie.exception.BadRequestException; import org.hibernate.exception.ConstraintViolationException; - import java.io.PrintWriter; import java.io.StringWriter; /** - * 异常工具 + * 异常工具 2019-01-06 * @author Zheng Jie - * @date 2019-01-06 */ public class ThrowableUtil { /** * 获取堆栈信息 - * @param throwable - * @return */ public static String getStackTrace(Throwable throwable){ StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - try { + try (PrintWriter pw = new PrintWriter(sw)) { throwable.printStackTrace(pw); return sw.toString(); - } finally { - pw.close(); } } @@ -34,9 +27,10 @@ public class ThrowableUtil { while ((t != null) && !(t instanceof ConstraintViolationException)) { t = t.getCause(); } - if (t instanceof ConstraintViolationException) { + if (t != null) { throw new BadRequestException(msg); } + assert false; throw new BadRequestException("删除失败:" + t.getMessage()); } } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/TranslatorUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/TranslatorUtil.java index 1f34b54c..623e90b0 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/TranslatorUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/TranslatorUtil.java @@ -1,8 +1,6 @@ package me.zhengjie.utils; import cn.hutool.json.JSONArray; -import lombok.var; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; @@ -26,7 +24,7 @@ public class TranslatorUtil { BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; - StringBuffer response = new StringBuffer(); + StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); @@ -39,14 +37,11 @@ public class TranslatorUtil { } private static String parseResult(String inputJson) throws Exception { - JSONArray jsonArray = new JSONArray(inputJson); - JSONArray jsonArray2 = (JSONArray) jsonArray.get(0); - String result =""; - - for(var i = 0; i < jsonArray2.size(); i ++){ - result += ((JSONArray) jsonArray2.get(i)).get(0).toString(); + JSONArray jsonArray2 = (JSONArray) new JSONArray(inputJson).get(0); + StringBuilder result = new StringBuilder(); + for (Object o : jsonArray2) { + result.append(((JSONArray) o).get(0).toString()); } - return result; + return result.toString(); } - } diff --git a/eladmin-common/src/main/java/me/zhengjie/utils/ValidationUtil.java b/eladmin-common/src/main/java/me/zhengjie/utils/ValidationUtil.java index fa8e7baf..940a1143 100644 --- a/eladmin-common/src/main/java/me/zhengjie/utils/ValidationUtil.java +++ b/eladmin-common/src/main/java/me/zhengjie/utils/ValidationUtil.java @@ -12,7 +12,6 @@ public class ValidationUtil{ /** * 验证空 - * @param optional */ public static void isNull(Optional optional, String entity,String parameter , Object value){ if(!optional.isPresent()){ @@ -25,14 +24,12 @@ public class ValidationUtil{ /** * 验证是否为邮箱 - * @param string - * @return */ public static boolean isEmail(String string) { if (string == null){ return false; } - String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; + String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; return string.matches(regEx1); } } diff --git a/eladmin-system/src/main/resources/config/application.yml b/eladmin-system/src/main/resources/config/application.yml index c45c9529..a98b7945 100644 --- a/eladmin-system/src/main/resources/config/application.yml +++ b/eladmin-system/src/main/resources/config/application.yml @@ -22,7 +22,7 @@ spring: redis: #数据库索引 - database: 0 + database: 1 host: 127.0.0.1 port: 6379 password: diff --git a/eladmin-system/src/test/java/me/zhengjie/EladminSystemApplicationTests.java b/eladmin-system/src/test/java/me/zhengjie/EladminSystemApplicationTests.java index c78714a4..3b6df74d 100644 --- a/eladmin-system/src/test/java/me/zhengjie/EladminSystemApplicationTests.java +++ b/eladmin-system/src/test/java/me/zhengjie/EladminSystemApplicationTests.java @@ -11,6 +11,7 @@ public class EladminSystemApplicationTests { @Test public void contextLoads() { + } } diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/AlipayConfig.java b/eladmin-tools/src/main/java/me/zhengjie/domain/AlipayConfig.java index ac3f4861..914adf75 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/AlipayConfig.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/AlipayConfig.java @@ -18,66 +18,46 @@ public class AlipayConfig implements Serializable { @Id private Long id; - /** - * 应用ID,APPID,收款账号既是APPID对应支付宝账号 - */ + // 应用ID,APPID,收款账号既是APPID对应支付宝账号 @NotBlank @Column(name = "app_id") private String appID; - /** - * 商户私钥,您的PKCS8格式RSA2私钥 - */ + // 商户私钥,您的PKCS8格式RSA2私钥 @NotBlank @Column(name = "private_key", columnDefinition = "text") private String privateKey; - /** - * 支付宝公钥 - */ + // 支付宝公钥 @NotBlank @Column(name = "public_key", columnDefinition = "text") private String publicKey; - /** - * 签名方式,固定格式 - */ + // 签名方式,固定格式 @Column(name = "sign_type") private String signType="RSA2"; - /** - * 支付宝开放安全地址,一般不会变 - */ + // 支付宝开放安全地址,一般不会变 @Column(name = "gateway_url") private String gatewayUrl = "https://openapi.alipaydev.com/gateway.do"; - /** - * 编码,固定格式 - */ + // 编码,固定格式 private String charset= "utf-8"; - /** - * 异步通知地址 - */ + // 异步通知地址 @NotBlank @Column(name = "notify_url") private String notifyUrl; - /** - * 订单完成后返回的页面 - */ + // 订单完成后返回的页面 @NotBlank @Column(name = "return_url") private String returnUrl; - /** - * 类型,固定格式 - */ + // 类型,固定格式 private String format="JSON"; - /** - * 商户号 - */ + // 商户号 @NotBlank @Column(name = "sys_service_provider_id") private String sysServiceProviderId; diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/EmailConfig.java b/eladmin-tools/src/main/java/me/zhengjie/domain/EmailConfig.java index 04157e78..c49131dc 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/EmailConfig.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/EmailConfig.java @@ -19,30 +19,22 @@ public class EmailConfig implements Serializable { @Id private Long id; - /** - *邮件服务器SMTP地址 - */ + // 邮件服务器SMTP地址 @NotBlank private String host; - /** - * 邮件服务器SMTP端口 - */ + // 邮件服务器SMTP端口 @NotBlank private String port; - /** - * 发件者用户名,默认为发件人邮箱前缀 - */ + // 发件者用户名,默认为发件人邮箱前缀 @NotBlank private String user; @NotBlank private String pass; - /** - * 收件人 - */ + // 收件人 @NotBlank @Column(name = "from_user") private String fromUser; diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/Picture.java b/eladmin-tools/src/main/java/me/zhengjie/domain/Picture.java index 8999cd84..289cc08a 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/Picture.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/Picture.java @@ -32,9 +32,6 @@ public class Picture implements Serializable { private String width; - /** - * delete URl - */ @Column(name = "delete_url") private String delete; diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuConfig.java b/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuConfig.java index 0fdd67dc..f4f84858 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuConfig.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuConfig.java @@ -18,23 +18,17 @@ public class QiniuConfig implements Serializable { @Id private Long id; - /** - * 一个账号最多拥有两对密钥(Access/Secret Key) - */ + // 一个账号最多拥有两对密钥(Access/Secret Key) @NotBlank @Column(name = "access_key", columnDefinition = "text") private String accessKey; - /** - * 一个账号最多拥有两对密钥(Access/Secret Key) - */ + // 一个账号最多拥有两对密钥(Access/Secret Key) @NotBlank @Column(name = "secret_key", columnDefinition = "text") private String secretKey; - /** - * 存储空间名称作为唯一的 Bucket 识别符 - */ + // 存储空间名称作为唯一的 Bucket 识别符 @NotBlank private String bucket; @@ -49,14 +43,10 @@ public class QiniuConfig implements Serializable { @NotBlank private String zone; - /** - * 外链域名,可自定义,需在七牛云绑定 - */ + // 外链域名,可自定义,需在七牛云绑定 @NotBlank private String host; - /** - * 空间类型:公开/私有 - */ + // 空间类型:公开/私有 private String type = "公开"; } diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuContent.java b/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuContent.java index 43784e98..20b1ada5 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuContent.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/QiniuContent.java @@ -21,37 +21,25 @@ public class QiniuContent implements Serializable { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - /** - * 文件名,如qiniu.jpg - */ + // 文件名 @Column(name = "name",unique = false) private String key; - /** - * 空间名 - */ + // 空间名 private String bucket; - /** - * 大小 - */ + // 大小 private String size; - /** - * 文件地址 - */ + // 文件地址 private String url; private String suffix; - /** - * 空间类型:公开/私有 - */ + // 空间类型:公开/私有 private String type = "公开"; - /** - * 更新时间 - */ + // 更新时间 @UpdateTimestamp @Column(name = "update_time") private Timestamp updateTime; diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/VerificationCode.java b/eladmin-tools/src/main/java/me/zhengjie/domain/VerificationCode.java index 6fd573a1..c66b9799 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/VerificationCode.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/VerificationCode.java @@ -26,32 +26,21 @@ public class VerificationCode { private String code; - /** - * 使用场景,自己定义 - */ + // 使用场景,自己定义 private String scenes; - /** - * true 为有效,false 为无效,验证时状态+时间+具体的邮箱或者手机号 - */ + // true 为有效,false 为无效,验证时状态+时间+具体的邮箱或者手机号 private Boolean status = true; - - /** - * 类型 :phone 和 email - */ + // 类型 :phone 和 email @NotBlank private String type; - /** - * 具体的phone与email - */ + // 具体的phone与email @NotBlank private String value; - /** - * 创建日期 - */ + // 创建日期 @CreationTimestamp @Column(name = "create_time") private Timestamp createTime; diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/vo/EmailVo.java b/eladmin-tools/src/main/java/me/zhengjie/domain/vo/EmailVo.java index a0767cbb..289aa30d 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/vo/EmailVo.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/vo/EmailVo.java @@ -18,9 +18,7 @@ import java.util.List; @NoArgsConstructor public class EmailVo { - /** - * 收件人,支持多个收件人,用逗号分隔 - */ + // 收件人,支持多个收件人,用逗号分隔 @NotEmpty private List tos; diff --git a/eladmin-tools/src/main/java/me/zhengjie/domain/vo/TradeVo.java b/eladmin-tools/src/main/java/me/zhengjie/domain/vo/TradeVo.java index 6927dafe..638ab9b5 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/domain/vo/TradeVo.java +++ b/eladmin-tools/src/main/java/me/zhengjie/domain/vo/TradeVo.java @@ -15,51 +15,35 @@ import java.sql.Timestamp; @Data public class TradeVo { - /** - * (必填)商品描述 - */ + // (必填)商品描述 @NotBlank private String body; - /** - * (必填)商品名称 - */ + // (必填)商品名称 @NotBlank private String subject; - /** - * (必填)商户订单号,应该由后台生成 - */ + // (必填)商户订单号,应该由后台生成 @ApiModelProperty(hidden = true) private String outTradeNo; - /** - * (必填)第三方订单号 - */ + // (必填)第三方订单号 @ApiModelProperty(hidden = true) private String tradeNo; - /** - * (必填)价格 - */ + // (必填)价格 @NotBlank private String totalAmount; - /** - * 订单状态,已支付,未支付,作废 - */ + // 订单状态,已支付,未支付,作废 @ApiModelProperty(hidden = true) private String state; - /** - * 创建时间,存入数据库时需要 - */ + // 创建时间,存入数据库时需要 @ApiModelProperty(hidden = true) private Timestamp createTime; - /** - * 作废时间,存入数据库时需要 - */ + // 作废时间,存入数据库时需要 @ApiModelProperty(hidden = true) private Date cancelTime; } diff --git a/eladmin-tools/src/main/java/me/zhengjie/repository/LocalStorageRepository.java b/eladmin-tools/src/main/java/me/zhengjie/repository/LocalStorageRepository.java index f540b243..15554451 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/repository/LocalStorageRepository.java +++ b/eladmin-tools/src/main/java/me/zhengjie/repository/LocalStorageRepository.java @@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; * @author Zheng Jie * @date 2019-09-05 */ -public interface LocalStorageRepository extends JpaRepository, JpaSpecificationExecutor { +public interface LocalStorageRepository extends JpaRepository, JpaSpecificationExecutor { } \ No newline at end of file diff --git a/eladmin-tools/src/main/java/me/zhengjie/repository/PictureRepository.java b/eladmin-tools/src/main/java/me/zhengjie/repository/PictureRepository.java index 27ab0351..6f3fbc7b 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/repository/PictureRepository.java +++ b/eladmin-tools/src/main/java/me/zhengjie/repository/PictureRepository.java @@ -8,5 +8,5 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; * @author Zheng Jie * @date 2018-12-27 */ -public interface PictureRepository extends JpaRepository, JpaSpecificationExecutor { +public interface PictureRepository extends JpaRepository, JpaSpecificationExecutor { } diff --git a/eladmin-tools/src/main/java/me/zhengjie/repository/QiNiuConfigRepository.java b/eladmin-tools/src/main/java/me/zhengjie/repository/QiNiuConfigRepository.java index 31bd91e7..86ff49c7 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/repository/QiNiuConfigRepository.java +++ b/eladmin-tools/src/main/java/me/zhengjie/repository/QiNiuConfigRepository.java @@ -12,6 +12,6 @@ import org.springframework.data.jpa.repository.Query; public interface QiNiuConfigRepository extends JpaRepository { @Modifying - @Query(value = "update qiniu_content set type = ?1", nativeQuery = true) + @Query(value = "update QiniuConfig set type = ?1") void update(String type); } diff --git a/eladmin-tools/src/main/java/me/zhengjie/repository/QiniuContentRepository.java b/eladmin-tools/src/main/java/me/zhengjie/repository/QiniuContentRepository.java index 1bd887e6..f6fdb1da 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/repository/QiniuContentRepository.java +++ b/eladmin-tools/src/main/java/me/zhengjie/repository/QiniuContentRepository.java @@ -8,12 +8,12 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; * @author Zheng Jie * @date 2018-12-31 */ -public interface QiniuContentRepository extends JpaRepository, JpaSpecificationExecutor { +public interface QiniuContentRepository extends JpaRepository, JpaSpecificationExecutor { /** * 根据key查询 - * @param key - * @return + * @param key 文件名 + * @return QiniuContent */ QiniuContent findByKey(String key); } diff --git a/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java b/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java index 681a07c7..1bb063cb 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java +++ b/eladmin-tools/src/main/java/me/zhengjie/rest/AliPayController.java @@ -1,5 +1,6 @@ package me.zhengjie.rest; +import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import me.zhengjie.aop.log.Log; @@ -16,6 +17,7 @@ import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.nio.charset.StandardCharsets; import java.util.Map; /** @@ -24,22 +26,26 @@ import java.util.Map; */ @Slf4j @RestController -@RequestMapping("/api") +@RequestMapping("/api/aliPay") +@Api(tags = "支付宝支付管理") public class AliPayController { - @Autowired - AlipayUtils alipayUtils; + private final AlipayUtils alipayUtils; - @Autowired - private AlipayService alipayService; + private final AlipayService alipayService; - @GetMapping(value = "/aliPay") + public AliPayController(AlipayUtils alipayUtils, AlipayService alipayService) { + this.alipayUtils = alipayUtils; + this.alipayService = alipayService; + } + + @GetMapping public ResponseEntity get(){ return new ResponseEntity<>(alipayService.find(),HttpStatus.OK); } @Log("配置支付宝") - @PutMapping(value = "/aliPay") + @PutMapping public ResponseEntity payConfig(@Validated @RequestBody AlipayConfig alipayConfig){ alipayConfig.setId(1L); alipayService.update(alipayConfig); @@ -48,7 +54,7 @@ public class AliPayController { @Log("支付宝PC网页支付") @ApiOperation(value = "PC网页支付") - @PostMapping(value = "/aliPay/toPayAsPC") + @PostMapping(value = "/toPayAsPC") public ResponseEntity toPayAsPC(@Validated@RequestBody TradeVo trade) throws Exception{ AlipayConfig alipay = alipayService.find(); trade.setOutTradeNo(alipayUtils.getOrderCode()); @@ -58,7 +64,7 @@ public class AliPayController { @Log("支付宝手机网页支付") @ApiOperation(value = "手机网页支付") - @PostMapping(value = "/aliPay/toPayAsWeb") + @PostMapping(value = "/toPayAsWeb") public ResponseEntity toPayAsWeb(@Validated @RequestBody TradeVo trade) throws Exception{ AlipayConfig alipay = alipayService.find(); trade.setOutTradeNo(alipayUtils.getOrderCode()); @@ -67,7 +73,7 @@ public class AliPayController { } @ApiIgnore - @GetMapping("/aliPay/return") + @GetMapping("/return") @ApiOperation(value = "支付之后跳转的链接") public ResponseEntity returnPage(HttpServletRequest request, HttpServletResponse response) throws Exception { AlipayConfig alipay = alipayService.find(); @@ -75,47 +81,39 @@ public class AliPayController { //内容验签,防止黑客篡改参数 if(alipayUtils.rsaCheck(request,alipay)){ //商户订单号 - String outTradeNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"); + String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //支付宝交易号 - String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"); + String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); System.out.println("商户订单号"+outTradeNo+" "+"第三方交易号"+tradeNo); - /** - * 根据业务需要返回数据,这里统一返回OK - */ + // 根据业务需要返回数据,这里统一返回OK return new ResponseEntity<>("payment successful",HttpStatus.OK); }else{ - /** - * 根据业务需要返回数据 - */ + // 根据业务需要返回数据 return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } @ApiIgnore - @RequestMapping("/aliPay/notify") + @RequestMapping("/notify") @ApiOperation(value = "支付异步通知(要公网访问),接收异步通知,检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致,根据trade_status进行后续业务处理") public ResponseEntity notify(HttpServletRequest request) throws Exception{ AlipayConfig alipay = alipayService.find(); Map parameterMap = request.getParameterMap(); - StringBuilder notifyBuild = new StringBuilder("/****************************** pay notify ******************************/\n"); - parameterMap.forEach((key, value) -> notifyBuild.append(key + "=" + value[0] + "\n") ); //内容验签,防止黑客篡改参数 if (alipayUtils.rsaCheck(request,alipay)) { //交易状态 - String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8"); + String tradeStatus = new String(request.getParameter("trade_status").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); // 商户订单号 - String outTradeNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8"); + String outTradeNo = new String(request.getParameter("out_trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //支付宝交易号 - String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8"); + String tradeNo = new String(request.getParameter("trade_no").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //付款金额 - String totalAmount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8"); + String totalAmount = new String(request.getParameter("total_amount").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); //验证 - if(tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue())||tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())){ - /** - * 验证通过后应该根据业务需要处理订单 - */ - } +// if(tradeStatus.equals(AliPayStatusEnum.SUCCESS.getValue())||tradeStatus.equals(AliPayStatusEnum.FINISHED.getValue())){ +// // 验证通过后应该根据业务需要处理订单 +// } return new ResponseEntity(HttpStatus.OK); } return new ResponseEntity(HttpStatus.BAD_REQUEST); diff --git a/eladmin-tools/src/main/java/me/zhengjie/rest/EmailController.java b/eladmin-tools/src/main/java/me/zhengjie/rest/EmailController.java index 4efcf4c8..ff3f15f1 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/rest/EmailController.java +++ b/eladmin-tools/src/main/java/me/zhengjie/rest/EmailController.java @@ -1,11 +1,11 @@ package me.zhengjie.rest; -import lombok.extern.slf4j.Slf4j; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import me.zhengjie.aop.log.Log; import me.zhengjie.domain.EmailConfig; import me.zhengjie.domain.vo.EmailVo; import me.zhengjie.service.EmailService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -16,30 +16,34 @@ import org.springframework.web.bind.annotation.*; * @author 郑杰 * @date 2018/09/28 6:55:53 */ -@Slf4j @RestController -@RequestMapping("api") +@RequestMapping("api/email") +@Api(tags = "邮件管理") public class EmailController { - @Autowired - private EmailService emailService; + private final EmailService emailService; - @GetMapping(value = "/email") + public EmailController(EmailService emailService) { + this.emailService = emailService; + } + + @GetMapping public ResponseEntity get(){ - return new ResponseEntity(emailService.find(),HttpStatus.OK); + return new ResponseEntity<>(emailService.find(),HttpStatus.OK); } @Log("配置邮件") - @PutMapping(value = "/email") + @PutMapping + @ApiOperation(value = "配置邮件") public ResponseEntity emailConfig(@Validated @RequestBody EmailConfig emailConfig){ emailService.update(emailConfig,emailService.find()); return new ResponseEntity(HttpStatus.OK); } @Log("发送邮件") - @PostMapping(value = "/email") + @PostMapping + @ApiOperation(value = "发送邮件") public ResponseEntity send(@Validated @RequestBody EmailVo emailVo) throws Exception { - log.warn("REST request to send Email : {}" +emailVo); emailService.send(emailVo,emailService.find()); return new ResponseEntity(HttpStatus.OK); } diff --git a/eladmin-tools/src/main/java/me/zhengjie/rest/LocalStorageController.java b/eladmin-tools/src/main/java/me/zhengjie/rest/LocalStorageController.java index 6b91cbec..425cef30 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/rest/LocalStorageController.java +++ b/eladmin-tools/src/main/java/me/zhengjie/rest/LocalStorageController.java @@ -4,7 +4,6 @@ import me.zhengjie.aop.log.Log; import me.zhengjie.domain.LocalStorage; import me.zhengjie.service.LocalStorageService; import me.zhengjie.service.dto.LocalStorageQueryCriteria; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -20,28 +19,31 @@ import org.springframework.web.multipart.MultipartFile; */ @Api(tags = "本地存储管理") @RestController -@RequestMapping("api") +@RequestMapping("/api/localStorage") public class LocalStorageController { - @Autowired - private LocalStorageService localStorageService; + private final LocalStorageService localStorageService; + + public LocalStorageController(LocalStorageService localStorageService) { + this.localStorageService = localStorageService; + } @ApiOperation(value = "查询文件") - @GetMapping(value = "/localStorage") + @GetMapping @PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_SELECT')") public ResponseEntity getLocalStorages(LocalStorageQueryCriteria criteria, Pageable pageable){ - return new ResponseEntity(localStorageService.queryAll(criteria,pageable),HttpStatus.OK); + return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK); } @ApiOperation(value = "上传文件") - @PostMapping(value = "/localStorage") + @PostMapping @PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_CREATE')") public ResponseEntity create(@RequestParam String name, @RequestParam("file") MultipartFile file){ - return new ResponseEntity(localStorageService.create(name, file),HttpStatus.CREATED); + return new ResponseEntity<>(localStorageService.create(name, file),HttpStatus.CREATED); } @ApiOperation(value = "修改文件") - @PutMapping(value = "/localStorage") + @PutMapping @PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_EDIT')") public ResponseEntity update(@Validated @RequestBody LocalStorage resources){ localStorageService.update(resources); @@ -49,20 +51,16 @@ public class LocalStorageController { } @ApiOperation(value = "删除文件") - @DeleteMapping(value = "/localStorage/{id}") + @DeleteMapping(value = "/{id}") @PreAuthorize("hasAnyRole('ADMIN','LOCALSTORAGE_ALL','LOCALSTORAGE_DELETE')") public ResponseEntity delete(@PathVariable Long id){ localStorageService.delete(id); return new ResponseEntity(HttpStatus.OK); } - /** - * 删除多张图片 - * @param ids - * @return - */ - @Log("删除图片") - @DeleteMapping(value = "/localStorage") + @Log("多选删除") + @DeleteMapping + @ApiOperation(value = "多选删除") public ResponseEntity deleteAll(@RequestBody Long[] ids) { localStorageService.deleteAll(ids); return new ResponseEntity(HttpStatus.OK); diff --git a/eladmin-tools/src/main/java/me/zhengjie/rest/PictureController.java b/eladmin-tools/src/main/java/me/zhengjie/rest/PictureController.java index 543ee3a2..f5168f13 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/rest/PictureController.java +++ b/eladmin-tools/src/main/java/me/zhengjie/rest/PictureController.java @@ -1,11 +1,12 @@ package me.zhengjie.rest; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import me.zhengjie.aop.log.Log; import me.zhengjie.domain.Picture; import me.zhengjie.service.PictureService; import me.zhengjie.service.dto.PictureQueryCriteria; import me.zhengjie.utils.SecurityUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -20,28 +21,28 @@ import java.util.Map; * @date 2018/09/20 14:13:32 */ @RestController -@RequestMapping("/api") +@RequestMapping("/api/pictures") +@Api(tags = "免费图床管理") public class PictureController { - @Autowired - private PictureService pictureService; + private final PictureService pictureService; + + public PictureController(PictureService pictureService) { + this.pictureService = pictureService; + } @Log("查询图片") @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')") - @GetMapping(value = "/pictures") + @GetMapping + @ApiOperation(value = "查询图片") public ResponseEntity getRoles(PictureQueryCriteria criteria, Pageable pageable){ - return new ResponseEntity(pictureService.queryAll(criteria,pageable),HttpStatus.OK); + return new ResponseEntity<>(pictureService.queryAll(criteria,pageable),HttpStatus.OK); } - /** - * 上传图片 - * @param file - * @return - * @throws Exception - */ @Log("上传图片") @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_UPLOAD')") - @PostMapping(value = "/pictures") + @PostMapping + @ApiOperation(value = "上传图片") public ResponseEntity upload(@RequestParam MultipartFile file){ String userName = SecurityUtils.getUsername(); Picture picture = pictureService.upload(file,userName); @@ -49,30 +50,22 @@ public class PictureController { map.put("errno",0); map.put("id",picture.getId()); map.put("data",new String[]{picture.getUrl()}); - return new ResponseEntity(map,HttpStatus.OK); + return new ResponseEntity<>(map,HttpStatus.OK); } - /** - * 删除图片 - * @param id - * @return - */ @Log("删除图片") + @ApiOperation(value = "删除图片") @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')") - @DeleteMapping(value = "/pictures/{id}") + @DeleteMapping(value = "/{id}") public ResponseEntity delete(@PathVariable Long id) { pictureService.delete(pictureService.findById(id)); return new ResponseEntity(HttpStatus.OK); } - /** - * 删除多张图片 - * @param ids - * @return - */ - @Log("删除图片") + @Log("多选删除图片") + @ApiOperation(value = "多选删除图片") @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')") - @DeleteMapping(value = "/pictures") + @DeleteMapping public ResponseEntity deleteAll(@RequestBody Long[] ids) { pictureService.deleteAll(ids); return new ResponseEntity(HttpStatus.OK); diff --git a/eladmin-tools/src/main/java/me/zhengjie/rest/QiniuController.java b/eladmin-tools/src/main/java/me/zhengjie/rest/QiniuController.java index e327618f..371c0506 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/rest/QiniuController.java +++ b/eladmin-tools/src/main/java/me/zhengjie/rest/QiniuController.java @@ -1,12 +1,13 @@ package me.zhengjie.rest; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import me.zhengjie.aop.log.Log; import me.zhengjie.domain.QiniuConfig; import me.zhengjie.domain.QiniuContent; import me.zhengjie.service.QiNiuService; import me.zhengjie.service.dto.QiniuQueryCriteria; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -24,17 +25,22 @@ import java.util.Map; @Slf4j @RestController @RequestMapping("api") +@Api(tags = "七牛云存储管理") public class QiniuController { - @Autowired - private QiNiuService qiNiuService; + private final QiNiuService qiNiuService; + + public QiniuController(QiNiuService qiNiuService) { + this.qiNiuService = qiNiuService; + } @GetMapping(value = "/qiNiuConfig") public ResponseEntity get(){ - return new ResponseEntity(qiNiuService.find(), HttpStatus.OK); + return new ResponseEntity<>(qiNiuService.find(), HttpStatus.OK); } @Log("配置七牛云存储") + @ApiOperation(value = "配置七牛云存储") @PutMapping(value = "/qiNiuConfig") public ResponseEntity emailConfig(@Validated @RequestBody QiniuConfig qiniuConfig){ qiNiuService.update(qiniuConfig); @@ -43,72 +49,51 @@ public class QiniuController { } @Log("查询文件") + @ApiOperation(value = "查询文件") @GetMapping(value = "/qiNiuContent") public ResponseEntity getRoles(QiniuQueryCriteria criteria, Pageable pageable){ - return new ResponseEntity(qiNiuService.queryAll(criteria,pageable),HttpStatus.OK); + return new ResponseEntity<>(qiNiuService.queryAll(criteria,pageable),HttpStatus.OK); } - /** - * 上传文件到七牛云 - * @param file - * @return - */ @Log("上传文件") + @ApiOperation(value = "上传文件") @PostMapping(value = "/qiNiuContent") public ResponseEntity upload(@RequestParam MultipartFile file){ QiniuContent qiniuContent = qiNiuService.upload(file,qiNiuService.find()); - Map map = new HashMap(3); + Map map = new HashMap<>(3); map.put("id",qiniuContent.getId()); map.put("errno",0); map.put("data",new String[]{qiniuContent.getUrl()}); - return new ResponseEntity(map,HttpStatus.OK); + return new ResponseEntity<>(map,HttpStatus.OK); } - /** - * 同步七牛云数据到数据库 - * @return - */ @Log("同步七牛云数据") + @ApiOperation(value = "同步七牛云数据") @PostMapping(value = "/qiNiuContent/synchronize") public ResponseEntity synchronize(){ - log.warn("REST request to synchronize qiNiu : {}"); qiNiuService.synchronize(qiNiuService.find()); return new ResponseEntity(HttpStatus.OK); } - /** - * 下载七牛云文件 - * @param id - * @return - * @throws Exception - */ @Log("下载文件") + @ApiOperation(value = "下载文件") @GetMapping(value = "/qiNiuContent/download/{id}") public ResponseEntity download(@PathVariable Long id){ - Map map = new HashMap(1); + Map map = new HashMap<>(1); map.put("url", qiNiuService.download(qiNiuService.findByContentId(id),qiNiuService.find())); - return new ResponseEntity(map,HttpStatus.OK); + return new ResponseEntity<>(map,HttpStatus.OK); } - /** - * 删除七牛云文件 - * @param id - * @return - * @throws Exception - */ @Log("删除文件") + @ApiOperation(value = "删除文件") @DeleteMapping(value = "/qiNiuContent/{id}") public ResponseEntity delete(@PathVariable Long id){ qiNiuService.delete(qiNiuService.findByContentId(id),qiNiuService.find()); return new ResponseEntity(HttpStatus.OK); } - /** - * 删除多张图片 - * @param ids - * @return - */ - @Log("删除图片") + @Log("删除多张图片") + @ApiOperation(value = "删除多张图片") @DeleteMapping(value = "/qiNiuContent") public ResponseEntity deleteAll(@RequestBody Long[] ids) { qiNiuService.deleteAll(ids, qiNiuService.find()); diff --git a/eladmin-tools/src/main/java/me/zhengjie/rest/VerificationCodeController.java b/eladmin-tools/src/main/java/me/zhengjie/rest/VerificationCodeController.java index 557631ad..718b2579 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/rest/VerificationCodeController.java +++ b/eladmin-tools/src/main/java/me/zhengjie/rest/VerificationCodeController.java @@ -1,11 +1,12 @@ package me.zhengjie.rest; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; import me.zhengjie.domain.VerificationCode; import me.zhengjie.domain.vo.EmailVo; import me.zhengjie.service.EmailService; import me.zhengjie.service.VerificationCodeService; import me.zhengjie.utils.ElAdminConstant; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -18,19 +19,20 @@ import org.springframework.web.bind.annotation.*; */ @RestController @RequestMapping("api") +@Api(tags = "验证码管理") public class VerificationCodeController { - @Autowired - private VerificationCodeService verificationCodeService; + private final VerificationCodeService verificationCodeService; - @Autowired - @Qualifier("jwtUserDetailsService") - private UserDetailsService userDetailsService; + private final EmailService emailService; - @Autowired - private EmailService emailService; + public VerificationCodeController(VerificationCodeService verificationCodeService, @Qualifier("jwtUserDetailsService") UserDetailsService userDetailsService, EmailService emailService) { + this.verificationCodeService = verificationCodeService; + this.emailService = emailService; + } @PostMapping(value = "/code/resetEmail") + @ApiOperation(value = "重置邮箱,发送验证码") public ResponseEntity resetEmail(@RequestBody VerificationCode code) throws Exception { code.setScenes(ElAdminConstant.RESET_MAIL); EmailVo emailVo = verificationCodeService.sendEmail(code); @@ -39,6 +41,7 @@ public class VerificationCodeController { } @PostMapping(value = "/code/email/resetPass") + @ApiOperation(value = "重置密码,发送验证码") public ResponseEntity resetPass(@RequestParam String email) throws Exception { VerificationCode code = new VerificationCode(); code.setType("email"); @@ -50,6 +53,7 @@ public class VerificationCodeController { } @GetMapping(value = "/code/validated") + @ApiOperation(value = "验证码验证") public ResponseEntity validated(VerificationCode code){ verificationCodeService.validated(code); return new ResponseEntity(HttpStatus.OK); diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/AlipayService.java b/eladmin-tools/src/main/java/me/zhengjie/service/AlipayService.java index f4e09423..69629d38 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/AlipayService.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/AlipayService.java @@ -15,33 +15,33 @@ public interface AlipayService { /** * 处理来自PC的交易请求 - * @param alipay - * @param trade - * @return - * @throws Exception + * @param alipay 支付宝配置 + * @param trade 交易详情 + * @return String + * @throws Exception 异常 */ String toPayAsPC(AlipayConfig alipay, TradeVo trade) throws Exception; /** * 处理来自手机网页的交易请求 - * @param alipay - * @param trade - * @return - * @throws Exception + * @param alipay 支付宝配置 + * @param trade 交易详情 + * @return String + * @throws Exception 异常 */ String toPayAsWeb(AlipayConfig alipay, TradeVo trade) throws Exception; /** * 查询配置 - * @return + * @return AlipayConfig */ @Cacheable(key = "'1'") AlipayConfig find(); /** * 更新配置 - * @param alipayConfig - * @return + * @param alipayConfig 支付宝配置 + * @return AlipayConfig */ @CachePut(key = "'1'") AlipayConfig update(AlipayConfig alipayConfig); diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/EmailService.java b/eladmin-tools/src/main/java/me/zhengjie/service/EmailService.java index deae90c1..ed0d9432 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/EmailService.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/EmailService.java @@ -16,24 +16,24 @@ public interface EmailService { /** * 更新邮件配置 - * @param emailConfig - * @param old - * @return + * @param emailConfig 邮件配置 + * @param old 旧的配置 + * @return EmailConfig */ @CachePut(key = "'1'") EmailConfig update(EmailConfig emailConfig, EmailConfig old); /** * 查询配置 - * @return + * @return EmailConfig 邮件配置 */ @Cacheable(key = "'1'") EmailConfig find(); /** * 发送邮件 - * @param emailVo - * @param emailConfig + * @param emailVo 邮件发送的内容 + * @param emailConfig 邮件配置 * @throws Exception */ @Async diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/LocalStorageService.java b/eladmin-tools/src/main/java/me/zhengjie/service/LocalStorageService.java index 6636cd0f..504997e5 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/LocalStorageService.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/LocalStorageService.java @@ -18,52 +18,56 @@ public interface LocalStorageService { /** * queryAll 分页 - * @param criteria - * @param pageable - * @return + * @param criteria 条件参数 + * @param pageable 分页参数 + * @return Object */ @Cacheable Object queryAll(LocalStorageQueryCriteria criteria, Pageable pageable); /** * queryAll 不分页 - * @param criteria - * @return + * @param criteria 条件参数 + * @return Object */ @Cacheable - public Object queryAll(LocalStorageQueryCriteria criteria); + Object queryAll(LocalStorageQueryCriteria criteria); /** * findById * @param id - * @return + * @return LocalStorageDTO */ @Cacheable(key = "#p0") LocalStorageDTO findById(Long id); /** * create - * @param name - * @param file - * @return + * @param name 文件名称 + * @param file 文件资源 + * @return LocalStorageDTO */ @CacheEvict(allEntries = true) LocalStorageDTO create(String name, MultipartFile file); /** * update - * @param resources + * @param resources 资源实体 */ @CacheEvict(allEntries = true) void update(LocalStorage resources); /** * delete - * @param id + * @param id 文件ID */ @CacheEvict(allEntries = true) void delete(Long id); + /** + * 多文件删除 + * @param ids 文件数组 + */ @CacheEvict(allEntries = true) void deleteAll(Long[] ids); } \ No newline at end of file diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/PictureService.java b/eladmin-tools/src/main/java/me/zhengjie/service/PictureService.java index 8d299ea5..eb8a0e5f 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/PictureService.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/PictureService.java @@ -16,17 +16,17 @@ public interface PictureService { /** * 查询图片 - * @param criteria - * @param pageable - * @return + * @param criteria 条件参数 + * @param pageable 分页参数 + * @return Object */ @Cacheable Object queryAll(PictureQueryCriteria criteria, Pageable pageable); /** * 上传图片 - * @param file - * @param username + * @param file 文件 + * @param username 用户名 * @return */ @CacheEvict(allEntries = true) @@ -34,7 +34,7 @@ public interface PictureService { /** * 根据ID查询 - * @param id + * @param id 文件ID * @return */ @Cacheable(key = "#p0") @@ -42,14 +42,14 @@ public interface PictureService { /** * 删除图片 - * @param picture + * @param picture 图片实体 */ @CacheEvict(allEntries = true) void delete(Picture picture); /** * 删除图片 - * @param ids + * @param ids 文件ID数组 */ @CacheEvict(allEntries = true) void deleteAll(Long[] ids); diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/QiNiuService.java b/eladmin-tools/src/main/java/me/zhengjie/service/QiNiuService.java index a161640e..16e37ad0 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/QiNiuService.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/QiNiuService.java @@ -20,16 +20,16 @@ public interface QiNiuService { /** * 查询文件 - * @param criteria - * @param pageable - * @return + * @param criteria 条件参数 + * @param pageable 分页参数 + * @return Object */ @Cacheable Object queryAll(QiniuQueryCriteria criteria, Pageable pageable); /** * 查配置 - * @return + * @return Cacheable */ @Cacheable(cacheNames = "qiNiuConfig", key = "'1'") QiniuConfig find(); @@ -37,7 +37,7 @@ public interface QiNiuService { /** * 修改配置 * @param qiniuConfig - * @return + * @return QiniuConfig */ @CachePut(cacheNames = "qiNiuConfig", key = "'1'") QiniuConfig update(QiniuConfig qiniuConfig); @@ -46,7 +46,7 @@ public interface QiNiuService { * 上传文件 * @param file * @param qiniuConfig - * @return + * @return QiniuContent */ @CacheEvict(allEntries = true) QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig); @@ -54,7 +54,7 @@ public interface QiNiuService { /** * 查询文件 * @param id - * @return + * @return QiniuContent */ @Cacheable(key = "'content:'+#p0") QiniuContent findByContentId(Long id); @@ -63,34 +63,37 @@ public interface QiNiuService { * 下载文件 * @param content * @param config - * @return + * @return String */ String download(QiniuContent content, QiniuConfig config); /** * 删除文件 - * @param content - * @param config - * @return + * @param content 文件 + * @param config 配置 */ @CacheEvict(allEntries = true) void delete(QiniuContent content, QiniuConfig config); /** * 同步数据 - * @param config + * @param config 配置 */ @CacheEvict(allEntries = true) void synchronize(QiniuConfig config); /** * 删除文件 - * @param ids - * @param config + * @param ids 文件ID数组 + * @param config 配置 */ @CacheEvict(allEntries = true) void deleteAll(Long[] ids, QiniuConfig config); + /** + * 更新数据 + * @param type 类型 + */ @CacheEvict(allEntries = true) void update(String type); } diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/VerificationCodeService.java b/eladmin-tools/src/main/java/me/zhengjie/service/VerificationCodeService.java index eaf8f0ec..058947f5 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/VerificationCodeService.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/VerificationCodeService.java @@ -11,13 +11,14 @@ public interface VerificationCodeService { /** * 发送邮件验证码 - * @param code + * @param code 验证码 + * @return EmailVo */ EmailVo sendEmail(VerificationCode code); /** * 验证 - * @param code + * @param code 验证码 */ void validated(VerificationCode code); } diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/AlipayServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/AlipayServiceImpl.java index 63715b5a..611b9a05 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/AlipayServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/AlipayServiceImpl.java @@ -40,19 +40,13 @@ public class AlipayServiceImpl implements AlipayService { double money = Double.parseDouble(trade.getTotalAmount()); - /** - * 创建API对应的request(电脑网页版) - */ + // 创建API对应的request(电脑网页版) AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); - /** - * 订单完成后返回的页面和异步通知地址 - */ + // 订单完成后返回的页面和异步通知地址 request.setReturnUrl(alipay.getReturnUrl()); request.setNotifyUrl(alipay.getNotifyUrl()); - /** - * 填充订单参数 - */ + // 填充订单参数 request.setBizContent("{" + " \"out_trade_no\":\""+trade.getOutTradeNo()+"\"," + " \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + @@ -63,10 +57,7 @@ public class AlipayServiceImpl implements AlipayService { " \"sys_service_provider_id\":\""+alipay.getSysServiceProviderId()+"\"" + " }"+ " }");//填充业务参数 - /** - * 调用SDK生成表单 - * 通过GET方式,口可以获取url - */ + // 调用SDK生成表单, 通过GET方式,口可以获取url return alipayClient.pageExecute(request, "GET").getBody(); } @@ -82,20 +73,10 @@ public class AlipayServiceImpl implements AlipayService { if(money <= 0 || money >= 5000){ throw new BadRequestException("测试金额过大"); } - - /** - * 创建API对应的request(手机网页版) - */ + // 创建API对应的request(手机网页版) AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest(); - - /** - * 订单完成后返回的页面和异步通知地址 - */ request.setReturnUrl(alipay.getReturnUrl()); request.setNotifyUrl(alipay.getNotifyUrl()); - /** - * 填充订单参数 - */ request.setBizContent("{" + " \"out_trade_no\":\""+trade.getOutTradeNo()+"\"," + " \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + @@ -106,21 +87,13 @@ public class AlipayServiceImpl implements AlipayService { " \"sys_service_provider_id\":\""+alipay.getSysServiceProviderId()+"\"" + " }"+ " }");//填充业务参数 - /** - * 调用SDK生成表单 - * 通过GET方式,口可以获取url - */ return alipayClient.pageExecute(request, "GET").getBody(); } @Override public AlipayConfig find() { Optional alipayConfig = alipayRepository.findById(1L); - if (alipayConfig.isPresent()){ - return alipayConfig.get(); - } else { - return new AlipayConfig(); - } + return alipayConfig.orElseGet(AlipayConfig::new); } @Override diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java index a0da7efd..56ac2ac2 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/EmailServiceImpl.java @@ -2,15 +2,12 @@ package me.zhengjie.service.impl; import cn.hutool.extra.mail.Mail; import cn.hutool.extra.mail.MailAccount; -import cn.hutool.extra.mail.MailUtil; import me.zhengjie.domain.EmailConfig; import me.zhengjie.domain.vo.EmailVo; import me.zhengjie.exception.BadRequestException; import me.zhengjie.repository.EmailRepository; import me.zhengjie.service.EmailService; -import me.zhengjie.utils.ElAdminConstant; import me.zhengjie.utils.EncryptUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @@ -24,8 +21,11 @@ import java.util.Optional; @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class EmailServiceImpl implements EmailService { - @Autowired - private EmailRepository emailRepository; + private final EmailRepository emailRepository; + + public EmailServiceImpl(EmailRepository emailRepository) { + this.emailRepository = emailRepository; + } @Override @Transactional(rollbackFor = Exception.class) @@ -44,11 +44,7 @@ public class EmailServiceImpl implements EmailService { @Override public EmailConfig find() { Optional emailConfig = emailRepository.findById(1L); - if(emailConfig.isPresent()){ - return emailConfig.get(); - } else { - return new EmailConfig(); - } + return emailConfig.orElseGet(EmailConfig::new); } @Override @@ -57,9 +53,7 @@ public class EmailServiceImpl implements EmailService { if(emailConfig == null){ throw new BadRequestException("请先配置,再操作"); } - /** - * 封装 - */ + // 封装 MailAccount account = new MailAccount(); account.setHost(emailConfig.getHost()); account.setPort(Integer.parseInt(emailConfig.getPort())); @@ -71,15 +65,14 @@ public class EmailServiceImpl implements EmailService { throw new BadRequestException(e.getMessage()); } account.setFrom(emailConfig.getUser()+"<"+emailConfig.getFromUser()+">"); - //ssl方式发送 + // ssl方式发送 account.setSslEnable(true); String content = emailVo.getContent(); - /** - * 发送 - */ + // 发送 try { + int size = emailVo.getTos().size(); Mail.create(account) - .setTos(emailVo.getTos().toArray(new String[emailVo.getTos().size()])) + .setTos(emailVo.getTos().toArray(new String[size])) .setTitle(emailVo.getSubject()) .setContent(content) .setHtml(true) diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java index f0830b5f..e3119df8 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/LocalStorageServiceImpl.java @@ -1,19 +1,16 @@ package me.zhengjie.service.impl; import me.zhengjie.domain.LocalStorage; -import me.zhengjie.exception.BadRequestException; import me.zhengjie.utils.*; import me.zhengjie.repository.LocalStorageRepository; import me.zhengjie.service.LocalStorageService; import me.zhengjie.service.dto.LocalStorageDTO; import me.zhengjie.service.dto.LocalStorageQueryCriteria; import me.zhengjie.service.mapper.LocalStorageMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; - import java.io.File; import java.util.Optional; import org.springframework.data.domain.Page; @@ -28,11 +25,9 @@ import org.springframework.web.multipart.MultipartFile; @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class LocalStorageServiceImpl implements LocalStorageService { - @Autowired - private LocalStorageRepository localStorageRepository; + private final LocalStorageRepository localStorageRepository; - @Autowired - private LocalStorageMapper localStorageMapper; + private final LocalStorageMapper localStorageMapper; @Value("${file.path}") private String path; @@ -40,6 +35,11 @@ public class LocalStorageServiceImpl implements LocalStorageService { @Value("${file.maxSize}") private long maxSize; + public LocalStorageServiceImpl(LocalStorageRepository localStorageRepository, LocalStorageMapper localStorageMapper) { + this.localStorageRepository = localStorageRepository; + this.localStorageMapper = localStorageMapper; + } + @Override public Object queryAll(LocalStorageQueryCriteria criteria, Pageable pageable){ Page page = localStorageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); @@ -85,11 +85,6 @@ public class LocalStorageServiceImpl implements LocalStorageService { } } - public static void main(String[] args) { - File file = new File("C:\\Users\\Jie\\Pictures\\Saved Pictures\\demo1.jpg"); - System.out.println(FileUtil.getType(file)); - } - @Override @Transactional(rollbackFor = Exception.class) public void update(LocalStorage resources) { diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/PictureServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/PictureServiceImpl.java index 2c128ca5..185ff147 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/PictureServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/PictureServiceImpl.java @@ -30,14 +30,17 @@ import java.util.Optional; @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class PictureServiceImpl implements PictureService { - @Autowired - private PictureRepository pictureRepository; + private final PictureRepository pictureRepository; - public static final String SUCCESS = "success"; + private static final String SUCCESS = "success"; - public static final String CODE = "code"; + private static final String CODE = "code"; - public static final String MSG = "message"; + private static final String MSG = "message"; + + public PictureServiceImpl(PictureRepository pictureRepository) { + this.pictureRepository = pictureRepository; + } @Override public Object queryAll(PictureQueryCriteria criteria, Pageable pageable){ @@ -60,7 +63,7 @@ public class PictureServiceImpl implements PictureService { } //转成实体类 picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class); - picture.setSize(FileUtil.getSize(Integer.valueOf(picture.getSize()))); + picture.setSize(FileUtil.getSize(Integer.parseInt(picture.getSize()))); picture.setUsername(username); picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+"."+FileUtil.getExtensionName(multipartFile.getOriginalFilename())); pictureRepository.save(picture); diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java index 530a363d..505dfc37 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/QiNiuServiceImpl.java @@ -29,6 +29,7 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; +import java.util.Map; import java.util.Optional; /** @@ -39,17 +40,18 @@ import java.util.Optional; @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class QiNiuServiceImpl implements QiNiuService { - @Autowired - private QiNiuConfigRepository qiNiuConfigRepository; + private final QiNiuConfigRepository qiNiuConfigRepository; - @Autowired - private QiniuContentRepository qiniuContentRepository; + private final QiniuContentRepository qiniuContentRepository; + + public QiNiuServiceImpl(QiNiuConfigRepository qiNiuConfigRepository, QiniuContentRepository qiniuContentRepository) { + this.qiNiuConfigRepository = qiNiuConfigRepository; + this.qiniuContentRepository = qiniuContentRepository; + } @Value("${qiniu.max-size}") private Long maxSize; - private final String TYPE = "公开"; - @Override public Object queryAll(QiniuQueryCriteria criteria, Pageable pageable){ return PageUtil.toPage(qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable)); @@ -58,11 +60,7 @@ public class QiNiuServiceImpl implements QiNiuService { @Override public QiniuConfig find() { Optional qiniuConfig = qiNiuConfigRepository.findById(1L); - if(qiniuConfig.isPresent()){ - return qiniuConfig.get(); - } else { - return new QiniuConfig(); - } + return qiniuConfig.orElseGet(QiniuConfig::new); } @Override @@ -82,9 +80,7 @@ public class QiNiuServiceImpl implements QiNiuService { if(qiniuConfig.getId() == null){ throw new BadRequestException("请先添加相应配置,再操作"); } - /** - * 构造一个带指定Zone对象的配置类 - */ + // 构造一个带指定Zone对象的配置类 Configuration cfg = new Configuration(QiNiuUtil.getRegion(qiniuConfig.getZone())); UploadManager uploadManager = new UploadManager(cfg); Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey()); @@ -122,13 +118,12 @@ public class QiNiuServiceImpl implements QiNiuService { @Override public String download(QiniuContent content,QiniuConfig config){ String finalUrl = null; + String TYPE = "公开"; if(TYPE.equals(content.getType())){ finalUrl = content.getUrl(); } else { Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey()); - /** - * 1小时,可以自定义链接过期时间 - */ + // 1小时,可以自定义链接过期时间 long expireInSeconds = 3600; finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds); } diff --git a/eladmin-tools/src/main/java/me/zhengjie/service/impl/VerificationCodeServiceImpl.java b/eladmin-tools/src/main/java/me/zhengjie/service/impl/VerificationCodeServiceImpl.java index ebac5e1a..0dda045c 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/service/impl/VerificationCodeServiceImpl.java +++ b/eladmin-tools/src/main/java/me/zhengjie/service/impl/VerificationCodeServiceImpl.java @@ -17,6 +17,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; +import java.util.Collections; import java.util.concurrent.*; /** @@ -45,12 +46,12 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { if(verificationCode == null){ code.setCode(RandomUtil.randomNumbers (6)); content = template.render(Dict.create().set("code",code.getCode())); - emailVo = new EmailVo(Arrays.asList(code.getValue()),"eladmin后台管理系统",content); + emailVo = new EmailVo(Collections.singletonList(code.getValue()),"eladmin后台管理系统",content); timedDestruction(verificationCodeRepository.save(code)); // 存在就再次发送原来的验证码 } else { content = template.render(Dict.create().set("code",verificationCode.getCode())); - emailVo = new EmailVo(Arrays.asList(verificationCode.getValue()),"eladmin后台管理系统",content); + emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()),"eladmin后台管理系统",content); } return emailVo; } @@ -68,7 +69,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { /** * 定时任务,指定分钟后改变验证码状态 - * @param verifyCode + * @param verifyCode 验证码 */ private void timedDestruction(VerificationCode verifyCode) { //以下示例为程序调用结束继续运行 diff --git a/eladmin-tools/src/main/java/me/zhengjie/utils/AliPayStatusEnum.java b/eladmin-tools/src/main/java/me/zhengjie/utils/AliPayStatusEnum.java index 46e6b7cf..39713cd5 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/utils/AliPayStatusEnum.java +++ b/eladmin-tools/src/main/java/me/zhengjie/utils/AliPayStatusEnum.java @@ -27,11 +27,9 @@ public enum AliPayStatusEnum { */ CLOSED("交易关闭", "TRADE_CLOSED"); - private String name; private String value; AliPayStatusEnum(String name, String value) { - this.name = name; this.value = value; } diff --git a/eladmin-tools/src/main/java/me/zhengjie/utils/AlipayUtils.java b/eladmin-tools/src/main/java/me/zhengjie/utils/AlipayUtils.java index 6c6b2dcc..5b7d6dbd 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/utils/AlipayUtils.java +++ b/eladmin-tools/src/main/java/me/zhengjie/utils/AlipayUtils.java @@ -22,7 +22,6 @@ public class AlipayUtils { /** * 生成订单号 - * @return */ public String getOrderCode() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @@ -35,24 +34,19 @@ public class AlipayUtils { String[] split1 = s.split(" "); String s1 = split1[0] + split1[1]; String[] split2 = s1.split(":"); - String s2 = split2[0] + split2[1] + split2[2] + a; - return s2; + return split2[0] + split2[1] + split2[2] + a; } /** * 校验签名 - * @param request - * @return */ public boolean rsaCheck(HttpServletRequest request, AlipayConfig alipay){ - /** - * 获取支付宝POST过来反馈信息 - */ + // 获取支付宝POST过来反馈信息 Map params = new HashMap<>(1); Map requestParams = request.getParameterMap(); - for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) { - String name = (String) iter.next(); + for (Object o : requestParams.keySet()) { + String name = (String) o; String[] values = (String[]) requestParams.get(name); String valueStr = ""; for (int i = 0; i < values.length; i++) { @@ -63,11 +57,10 @@ public class AlipayUtils { } try { - boolean verifyResult = AlipaySignature.rsaCheckV1(params, + return AlipaySignature.rsaCheckV1(params, alipay.getPublicKey(), alipay.getCharset(), alipay.getSignType()); - return verifyResult; } catch (AlipayApiException e) { return false; } diff --git a/eladmin-tools/src/main/java/me/zhengjie/utils/QiNiuUtil.java b/eladmin-tools/src/main/java/me/zhengjie/utils/QiNiuUtil.java index 4ff7dc83..8ae059b8 100644 --- a/eladmin-tools/src/main/java/me/zhengjie/utils/QiNiuUtil.java +++ b/eladmin-tools/src/main/java/me/zhengjie/utils/QiNiuUtil.java @@ -11,18 +11,16 @@ import java.util.Date; */ public class QiNiuUtil { - public static final String HUAD = "华东"; + private static final String HUAD = "华东"; - public static final String HUAB = "华北"; + private static final String HUAB = "华北"; - public static final String HUAN = "华南"; + private static final String HUAN = "华南"; - public static final String BEIM = "北美"; + private static final String BEIM = "北美"; /** * 得到机房的对应关系 - * @param zone - * @return */ public static Region getRegion(String zone){ @@ -42,17 +40,13 @@ public class QiNiuUtil { /** * 默认不指定key的情况下,以文件内容的hash值作为文件名 - * @param file - * @return */ public static String getKey(String file){ - StringBuffer key = new StringBuffer(FileUtil.getFileNameNoEx(file)); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); Date date = new Date(); - key.append("-"); - key.append(sdf.format(date)); - key.append("."); - key.append(FileUtil.getExtensionName(file)); - return key.toString(); + return FileUtil.getFileNameNoEx(file) + "-" + + sdf.format(date) + + "." + + FileUtil.getExtensionName(file); } }