From 9b4f7ca57412cb628d1b746e8ced8b22546ce99a Mon Sep 17 00:00:00 2001 From: tuyp Date: Thu, 8 May 2025 14:02:33 +0800 Subject: [PATCH] 加密解密加盐工具类 --- src/main/java/com/template/ZhongzhiApplication.java | 17 +++++++++++++++++ src/main/java/com/template/common/JwtUtil.java | 101 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/annotate/ExcelColumn.java | 13 +++++++++++++ src/main/java/com/template/common/annotate/LoginRequired.java | 21 +++++++++++++++++++++ src/main/java/com/template/common/annotate/SysLog.java | 19 +++++++++++++++++++ src/main/java/com/template/common/configure/AliyunSmsProperties.java | 28 ++++++++++++++++++++++++++++ src/main/java/com/template/common/configure/MybatisPlusConfig.java | 36 ++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/configure/RemoteProperties.java | 36 ++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/configure/SwaggerConfig.java | 38 ++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/configure/VODConfig.java | 27 +++++++++++++++++++++++++++ src/main/java/com/template/common/configure/WebConfig.java | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/constant/Code.java | 33 +++++++++++++++++++++++++++++++++ src/main/java/com/template/common/constant/Platform.java | 32 ++++++++++++++++++++++++++++++++ src/main/java/com/template/common/exception/GlobalExceptionHandler.java | 121 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/exception/HttpException.java | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/generator/CodeGenerator.java | 126 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/common/handler/MetaHandler.java | 27 +++++++++++++++++++++++++++ src/main/java/com/template/common/interceptor/AuthenticationInterceptor.java | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/controller/OssController.java | 179 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/model/base/BaseModel.java | 35 +++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/AliyunSmsUtil.java | 211 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/ApplicationContextUtil.java | 25 +++++++++++++++++++++++++ src/main/java/com/template/utils/DateFormatUtil.java | 187 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/EasyExcelUtil.java | 34 ++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/EncryptionUtil.java | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/ExcelUtil.java | 335 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/IpAddressUtil.java | 36 ++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/LocalstorageUtil.java | 33 +++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/PDFUtil.java | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/RandomUtil.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/utils/VodUtil.java | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/vo/ExcelFieldVO.java | 11 +++++++++++ src/main/java/com/template/vo/ResponseData.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/template/vo/ResponseVO.java | 21 +++++++++++++++++++++ src/main/java/com/template/vo/oss/GetSecretVO.java | 13 +++++++++++++ src/main/java/com/template/vo/oss/UploadFileVO.java | 12 ++++++++++++ src/main/java/com/zhongzhi/ZhongzhiApplication.java | 17 ----------------- src/main/java/com/zhongzhi/common/JwtUtil.java | 101 ----------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/common/annotate/ExcelColumn.java | 13 ------------- src/main/java/com/zhongzhi/common/annotate/LoginRequired.java | 21 --------------------- src/main/java/com/zhongzhi/common/annotate/SysLog.java | 19 ------------------- src/main/java/com/zhongzhi/common/configure/AliyunSmsProperties.java | 28 ---------------------------- src/main/java/com/zhongzhi/common/configure/MybatisPlusConfig.java | 36 ------------------------------------ src/main/java/com/zhongzhi/common/configure/RemoteProperties.java | 36 ------------------------------------ src/main/java/com/zhongzhi/common/configure/SwaggerConfig.java | 38 -------------------------------------- src/main/java/com/zhongzhi/common/configure/VODConfig.java | 27 --------------------------- src/main/java/com/zhongzhi/common/configure/WebConfig.java | 75 --------------------------------------------------------------------------- src/main/java/com/zhongzhi/common/constant/Code.java | 33 --------------------------------- src/main/java/com/zhongzhi/common/constant/Platform.java | 32 -------------------------------- src/main/java/com/zhongzhi/common/exception/GlobalExceptionHandler.java | 121 ------------------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/common/exception/HttpException.java | 45 --------------------------------------------- src/main/java/com/zhongzhi/common/generator/CodeGenerator.java | 126 ------------------------------------------------------------------------------------------------------------------------------ src/main/java/com/zhongzhi/common/handler/MetaHandler.java | 27 --------------------------- src/main/java/com/zhongzhi/common/interceptor/AuthenticationInterceptor.java | 78 ------------------------------------------------------------------------------ src/main/java/com/zhongzhi/controller/OssController.java | 213 --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/model/base/BaseModel.java | 35 ----------------------------------- src/main/java/com/zhongzhi/utils/AliyunSmsUtil.java | 211 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/utils/ApplicationContextUtil.java | 25 ------------------------- src/main/java/com/zhongzhi/utils/DateFormatUtil.java | 187 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/utils/EncryptionUtil.java | 99 --------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/utils/ExcelUtil.java | 335 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/utils/IpAddressUtil.java | 36 ------------------------------------ src/main/java/com/zhongzhi/utils/LocalstorageUtil.java | 33 --------------------------------- src/main/java/com/zhongzhi/utils/PDFUtil.java | 109 ------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/utils/RandomUtil.java | 58 ---------------------------------------------------------- src/main/java/com/zhongzhi/utils/VodUtil.java | 116 -------------------------------------------------------------------------------------------------------------------- src/main/java/com/zhongzhi/vo/ExcelFieldVO.java | 11 ----------- src/main/java/com/zhongzhi/vo/ResponseData.java | 55 ------------------------------------------------------- src/main/java/com/zhongzhi/vo/ResponseVO.java | 21 --------------------- src/main/java/com/zhongzhi/vo/oss/GetSecretVO.java | 13 ------------- src/main/java/com/zhongzhi/vo/oss/UploadFileVO.java | 12 ------------ src/main/resources/logback-spring.xml | 6 +++--- 72 files changed, 2444 insertions(+), 2445 deletions(-) create mode 100644 src/main/java/com/template/ZhongzhiApplication.java create mode 100644 src/main/java/com/template/common/JwtUtil.java create mode 100644 src/main/java/com/template/common/annotate/ExcelColumn.java create mode 100644 src/main/java/com/template/common/annotate/LoginRequired.java create mode 100644 src/main/java/com/template/common/annotate/SysLog.java create mode 100644 src/main/java/com/template/common/configure/AliyunSmsProperties.java create mode 100644 src/main/java/com/template/common/configure/MybatisPlusConfig.java create mode 100644 src/main/java/com/template/common/configure/RemoteProperties.java create mode 100644 src/main/java/com/template/common/configure/SwaggerConfig.java create mode 100644 src/main/java/com/template/common/configure/VODConfig.java create mode 100644 src/main/java/com/template/common/configure/WebConfig.java create mode 100644 src/main/java/com/template/common/constant/Code.java create mode 100644 src/main/java/com/template/common/constant/Platform.java create mode 100644 src/main/java/com/template/common/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/template/common/exception/HttpException.java create mode 100644 src/main/java/com/template/common/generator/CodeGenerator.java create mode 100644 src/main/java/com/template/common/handler/MetaHandler.java create mode 100644 src/main/java/com/template/common/interceptor/AuthenticationInterceptor.java create mode 100644 src/main/java/com/template/controller/OssController.java create mode 100644 src/main/java/com/template/model/base/BaseModel.java create mode 100644 src/main/java/com/template/utils/AliyunSmsUtil.java create mode 100644 src/main/java/com/template/utils/ApplicationContextUtil.java create mode 100644 src/main/java/com/template/utils/DateFormatUtil.java create mode 100644 src/main/java/com/template/utils/EasyExcelUtil.java create mode 100644 src/main/java/com/template/utils/EncryptionUtil.java create mode 100644 src/main/java/com/template/utils/ExcelUtil.java create mode 100644 src/main/java/com/template/utils/IpAddressUtil.java create mode 100644 src/main/java/com/template/utils/LocalstorageUtil.java create mode 100644 src/main/java/com/template/utils/PDFUtil.java create mode 100644 src/main/java/com/template/utils/RandomUtil.java create mode 100644 src/main/java/com/template/utils/VodUtil.java create mode 100644 src/main/java/com/template/vo/ExcelFieldVO.java create mode 100644 src/main/java/com/template/vo/ResponseData.java create mode 100644 src/main/java/com/template/vo/ResponseVO.java create mode 100644 src/main/java/com/template/vo/oss/GetSecretVO.java create mode 100644 src/main/java/com/template/vo/oss/UploadFileVO.java delete mode 100644 src/main/java/com/zhongzhi/ZhongzhiApplication.java delete mode 100644 src/main/java/com/zhongzhi/common/JwtUtil.java delete mode 100644 src/main/java/com/zhongzhi/common/annotate/ExcelColumn.java delete mode 100644 src/main/java/com/zhongzhi/common/annotate/LoginRequired.java delete mode 100644 src/main/java/com/zhongzhi/common/annotate/SysLog.java delete mode 100644 src/main/java/com/zhongzhi/common/configure/AliyunSmsProperties.java delete mode 100644 src/main/java/com/zhongzhi/common/configure/MybatisPlusConfig.java delete mode 100644 src/main/java/com/zhongzhi/common/configure/RemoteProperties.java delete mode 100644 src/main/java/com/zhongzhi/common/configure/SwaggerConfig.java delete mode 100644 src/main/java/com/zhongzhi/common/configure/VODConfig.java delete mode 100644 src/main/java/com/zhongzhi/common/configure/WebConfig.java delete mode 100644 src/main/java/com/zhongzhi/common/constant/Code.java delete mode 100644 src/main/java/com/zhongzhi/common/constant/Platform.java delete mode 100644 src/main/java/com/zhongzhi/common/exception/GlobalExceptionHandler.java delete mode 100644 src/main/java/com/zhongzhi/common/exception/HttpException.java delete mode 100644 src/main/java/com/zhongzhi/common/generator/CodeGenerator.java delete mode 100644 src/main/java/com/zhongzhi/common/handler/MetaHandler.java delete mode 100644 src/main/java/com/zhongzhi/common/interceptor/AuthenticationInterceptor.java delete mode 100644 src/main/java/com/zhongzhi/controller/OssController.java delete mode 100644 src/main/java/com/zhongzhi/model/base/BaseModel.java delete mode 100644 src/main/java/com/zhongzhi/utils/AliyunSmsUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/ApplicationContextUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/DateFormatUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/EncryptionUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/ExcelUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/IpAddressUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/LocalstorageUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/PDFUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/RandomUtil.java delete mode 100644 src/main/java/com/zhongzhi/utils/VodUtil.java delete mode 100644 src/main/java/com/zhongzhi/vo/ExcelFieldVO.java delete mode 100644 src/main/java/com/zhongzhi/vo/ResponseData.java delete mode 100644 src/main/java/com/zhongzhi/vo/ResponseVO.java delete mode 100644 src/main/java/com/zhongzhi/vo/oss/GetSecretVO.java delete mode 100644 src/main/java/com/zhongzhi/vo/oss/UploadFileVO.java diff --git a/src/main/java/com/template/ZhongzhiApplication.java b/src/main/java/com/template/ZhongzhiApplication.java new file mode 100644 index 0000000..a3546df --- /dev/null +++ b/src/main/java/com/template/ZhongzhiApplication.java @@ -0,0 +1,17 @@ +package com.template; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@MapperScan(basePackages = {"com.template.dao"}) +@SpringBootApplication +public class ZhongzhiApplication { + + public static void main(String[] args) { + SpringApplication.run(ZhongzhiApplication.class, args); + } + +} \ No newline at end of file diff --git a/src/main/java/com/template/common/JwtUtil.java b/src/main/java/com/template/common/JwtUtil.java new file mode 100644 index 0000000..75b332a --- /dev/null +++ b/src/main/java/com/template/common/JwtUtil.java @@ -0,0 +1,101 @@ +package com.template.common; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.JWTVerifier; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.interfaces.Claim; + +import java.util.Date; +import java.util.Map; + +/** + *

+ * Token工具 + *

+ * + * @author DengMin + * @since 2021/4/14 + */ +public class JwtUtil { + + private static final Long EXPIRE_TIME = 24 * 60 * 60 * 1000L; + + private static final String SECRET = "PBKDF2SHA256:64000:18:24:N:GFHZ6Y0PTEUDYCJI3K6SOOXWYEKPOZED:WBWFJMX5DF252E0HR3BF3P/D"; + + /** + * 生成Token + * + * @param id + * @return + */ + public static String generateToken(Long id, String type) { + Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME); + return JWT.create() + .withClaim("id", id) + .withClaim("type", type) + .withAudience() + .withExpiresAt(expireDate) + .withIssuedAt(new Date()) + .sign(Algorithm.HMAC256(SECRET)); + } + + /** + * 检验token是否正确 + * + * @param token + * @return + */ + public static boolean verifyToken(String token) { + try { + Algorithm algorithm = Algorithm.HMAC256(SECRET); + JWTVerifier verifier = JWT.require(algorithm).build(); + verifier.verify(token); + return true; + } catch (Exception e) { + return false; + } + } + + /** + * 获取用户自定义Claim集合 + * + * @param token + * @return + */ + public static Map getClaims(String token) { + Algorithm algorithm = Algorithm.HMAC256(SECRET); + JWTVerifier verifier = JWT.require(algorithm).build(); + Map claims = verifier.verify(token).getClaims(); + return claims; + } + + /** + * 获取过期时间 + * + * @param token + * @return + */ + public static Date getExpiresAt(String token) { + Algorithm algorithm = Algorithm.HMAC256(SECRET); + return JWT + .require(algorithm) + .build() + .verify(token) + .getExpiresAt(); + } + + /** + * 验证token是否失效 + * + * @param token + * @return true: 过期, false: 没过期 + */ + public static boolean isExpired(String token) { + try { + final Date expiration = getExpiresAt(token); + return expiration.before(new Date()); + } catch (Exception e) { + return true; + } + } +} diff --git a/src/main/java/com/template/common/annotate/ExcelColumn.java b/src/main/java/com/template/common/annotate/ExcelColumn.java new file mode 100644 index 0000000..fc88e71 --- /dev/null +++ b/src/main/java/com/template/common/annotate/ExcelColumn.java @@ -0,0 +1,13 @@ +package com.template.common.annotate; + +import java.lang.annotation.*; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface ExcelColumn { + + String value() default ""; + + int col() default 1; +} diff --git a/src/main/java/com/template/common/annotate/LoginRequired.java b/src/main/java/com/template/common/annotate/LoginRequired.java new file mode 100644 index 0000000..4b412ed --- /dev/null +++ b/src/main/java/com/template/common/annotate/LoginRequired.java @@ -0,0 +1,21 @@ +package com.template.common.annotate; + +import java.lang.annotation.*; + +/** + *

+ * 自定义验证登陆注解 + *

+ * + * @author DengMin + * @since 2020/12/18 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface LoginRequired { + + String[] value(); + +} \ No newline at end of file diff --git a/src/main/java/com/template/common/annotate/SysLog.java b/src/main/java/com/template/common/annotate/SysLog.java new file mode 100644 index 0000000..31e6175 --- /dev/null +++ b/src/main/java/com/template/common/annotate/SysLog.java @@ -0,0 +1,19 @@ +package com.template.common.annotate; + +import java.lang.annotation.*; + +/** + *

+ * 自定义日志注解 + *

+ * + * @author DengMin + * @since 2020/12/18 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface SysLog { + + String value() default ""; +} diff --git a/src/main/java/com/template/common/configure/AliyunSmsProperties.java b/src/main/java/com/template/common/configure/AliyunSmsProperties.java new file mode 100644 index 0000000..b2b33da --- /dev/null +++ b/src/main/java/com/template/common/configure/AliyunSmsProperties.java @@ -0,0 +1,28 @@ +package com.template.common.configure; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "sms") +public class AliyunSmsProperties { + + private String product; + + private String domain; + + private String accessKeyId; + + private String accessKeySecret; + + private String cpcode; + + private String excode; + + private String key; + + private String rcsapi; + +} diff --git a/src/main/java/com/template/common/configure/MybatisPlusConfig.java b/src/main/java/com/template/common/configure/MybatisPlusConfig.java new file mode 100644 index 0000000..4b8ee72 --- /dev/null +++ b/src/main/java/com/template/common/configure/MybatisPlusConfig.java @@ -0,0 +1,36 @@ +package com.template.common.configure; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.core.config.GlobalConfig; +import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; +import com.template.common.handler.MetaHandler; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class MybatisPlusConfig { + + /** + * 分页 + * + * @return + */ + @Bean + public PaginationInterceptor paginationInterceptor() { + PaginationInterceptor page = new PaginationInterceptor(); + page.setDialectType(DbType.MYSQL.getDb()); + return page; + } + + /** + * 自动填充功能 + * + * @return + */ + @Bean + public GlobalConfig globalConfig() { + GlobalConfig globalConfig = new GlobalConfig(); + globalConfig.setMetaObjectHandler(new MetaHandler()); + return globalConfig; + } +} \ No newline at end of file diff --git a/src/main/java/com/template/common/configure/RemoteProperties.java b/src/main/java/com/template/common/configure/RemoteProperties.java new file mode 100644 index 0000000..366bfe3 --- /dev/null +++ b/src/main/java/com/template/common/configure/RemoteProperties.java @@ -0,0 +1,36 @@ +package com.template.common.configure; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +/** + *

+ * 读取状态码 + *

+ * + * @author DengMin + * @date Created in 2020/08/24 + */ +@Component +@ConfigurationProperties(prefix = "c") +@PropertySource(value = "classpath:code.properties", encoding = "UTF-8") +public class RemoteProperties { + + private static Map codeMessage = new HashMap<>(); + + public static String getMessage(Integer code) { + return codeMessage.get(code); + } + + public Map getCodeMessage() { + return codeMessage; + } + + public void setCodeMessage(Map codeMessage) { + RemoteProperties.codeMessage = codeMessage; + } +} \ No newline at end of file diff --git a/src/main/java/com/template/common/configure/SwaggerConfig.java b/src/main/java/com/template/common/configure/SwaggerConfig.java new file mode 100644 index 0000000..5641808 --- /dev/null +++ b/src/main/java/com/template/common/configure/SwaggerConfig.java @@ -0,0 +1,38 @@ +package com.template.common.configure; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + *

+ * swagger2 + *

+ * + * @author DengMin + * @since 2020/12/8 + */ +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .pathMapping("/") + .select() + .apis(RequestHandlerSelectors.basePackage("com.template.controller")) + .paths(PathSelectors.any()) + .build() + .apiInfo(new ApiInfoBuilder() + .title("模板") + .description("接口文档") + .version("1.0") + .build()); + } +} diff --git a/src/main/java/com/template/common/configure/VODConfig.java b/src/main/java/com/template/common/configure/VODConfig.java new file mode 100644 index 0000000..33e7ec6 --- /dev/null +++ b/src/main/java/com/template/common/configure/VODConfig.java @@ -0,0 +1,27 @@ +package com.template.common.configure; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * @author: tuyp + * @create: 2020-06-01 16:46 + */ +@Component +@Data +@ConfigurationProperties(prefix = "vod") +public class VODConfig { + + private String appId; + + private String secretId; + + private String secretKey; + + private String api; + + private String region; + + private Integer classId; +} diff --git a/src/main/java/com/template/common/configure/WebConfig.java b/src/main/java/com/template/common/configure/WebConfig.java new file mode 100644 index 0000000..72f8213 --- /dev/null +++ b/src/main/java/com/template/common/configure/WebConfig.java @@ -0,0 +1,75 @@ +package com.template.common.configure; + +import com.template.common.interceptor.AuthenticationInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; +import org.springframework.web.servlet.config.annotation.*; + +/** + * @author DengMin + * @date 2020/07/06 + **/ +@Configuration +public class WebConfig extends WebMvcConfigurationSupport { + + @Autowired + private AuthenticationInterceptor authenticationInterceptor; + + /** + * 跨域支持 + * + * @param registry + */ + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowCredentials(true) + .allowedOrigins("*") + .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") + .maxAge(3600); + } + + @Bean + public CorsFilter corsFilter() { + CorsConfiguration config = new CorsConfiguration(); + config.setMaxAge(3600L); + config.addAllowedOrigin("*"); + config.addAllowedMethod("*"); + config.addAllowedHeader("*"); + UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); + configSource.registerCorsConfiguration("/**", config); + return new CorsFilter(configSource); + } + + /** + * Swagger + * + * @param registry + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/**") + .addResourceLocations("classpath:/static/"); + registry.addResourceHandler("swagger-ui.html") + .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + super.addResourceHandlers(registry); + } + + /** + * 鉴权 + * + * @param registry + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(authenticationInterceptor) + .excludePathPatterns("/static/*") + .addPathPatterns("/**"); + } +} \ No newline at end of file diff --git a/src/main/java/com/template/common/constant/Code.java b/src/main/java/com/template/common/constant/Code.java new file mode 100644 index 0000000..0a1325e --- /dev/null +++ b/src/main/java/com/template/common/constant/Code.java @@ -0,0 +1,33 @@ +package com.template.common.constant; + +import lombok.Getter; + +@Getter +public enum Code { + + USERNAMENOTFOUND(1001, "用户不存在"), + BADCREDENTIALS(1002, "账户或者密码错误"), + ACCOUNTEXPIRED(1003, "账户过期"), + LOCKEDEXCEPTION(1004, "账户已锁定"), + DISABLEDEXCEPTION(1005, "账户已禁用"), + ACCESSDENIED(1006, "无权限访问"), + AUTHENTICATION(1007, "身份验证异常"), + NOHANDLERFOUND(1008, "找不到相应的视图处理器"), + PARAM_INVALID(1009, "参数不合法"), + TOKEN_EXCEPTION(1010, "无效的令牌"), + TOKEN_EXPIRED(1011, "令牌已过期"), + TOKEN_VERIFICATION_FAILED(1012, "令牌验证失败"), + OSS_ERROR(1013, "OSS文件上传异常"), + Network_ERROR(9000, "网络请求失败"), + SERVER_INTERNAL_ERROR(99999, "服务器内部错误"), + ; + + private final Integer code; + + private final String message; + + Code(Integer code, String message) { + this.code = code; + this.message = message; + } +} diff --git a/src/main/java/com/template/common/constant/Platform.java b/src/main/java/com/template/common/constant/Platform.java new file mode 100644 index 0000000..5bfe0c2 --- /dev/null +++ b/src/main/java/com/template/common/constant/Platform.java @@ -0,0 +1,32 @@ +package com.template.common.constant; + +/** + *

+ * 平台标识 + *

+ * + * @author DengMin + * @since 2021/6/9 + */ +public class Platform { + + /* + 学生端 + */ + public static final String student = "student"; + + /* + 院校端 + */ + public static final String school = "school"; + + /* + 中心端 + */ + public static final String center = "center"; + + /* + 评审端 + */ + public static final String review = "review"; +} diff --git a/src/main/java/com/template/common/exception/GlobalExceptionHandler.java b/src/main/java/com/template/common/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..96da3ab --- /dev/null +++ b/src/main/java/com/template/common/exception/GlobalExceptionHandler.java @@ -0,0 +1,121 @@ +package com.template.common.exception; + +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.template.common.configure.RemoteProperties; +import com.template.common.constant.Code; +import com.template.vo.ResponseData; +import com.template.vo.ResponseVO; +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.formula.functions.T; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.validation.BindException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.NoHandlerFoundException; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + /** + * 自定义异常 + * + * @param e + * @return + */ + @ExceptionHandler(value = HttpException.class) + public ResponseVO handlerException(HttpServletRequest request, HttpException e) { + String message = RemoteProperties.getMessage(e.getCode()); + if (StringUtils.isBlank(message)) { + message = e.getMessage(); + } + String url = request.getRequestURI(); + return ResponseData.generateCreatedResponse(e.getCode(), message, url); + } + + /** + * 404 + * + * @param request + * @return + */ + @ExceptionHandler(value = NoHandlerFoundException.class) + public ResponseVO NoHandlerFoundException(HttpServletRequest request) { + String url = request.getRequestURI(); + return ResponseData.generateCreatedResponse(Code.NOHANDLERFOUND.getCode(), Code.NOHANDLERFOUND.getMessage(), url); + } + + /** + * 请求方式错误 + * + * @param request + * @return + */ + @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) + public ResponseVO HttpRequestMethodNotSupportedException(HttpServletRequest request) { + String url = request.getRequestURI(); + return ResponseData.generateCreatedResponse(Code.NOHANDLERFOUND.getCode(), Code.NOHANDLERFOUND.getMessage(), url); + } + + /** + * 参数不合法 + * + * @param e + * @return + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseVO validateException(MethodArgumentNotValidException e) { + final List errList = new ArrayList<>(); + e.getBindingResult().getAllErrors().stream().forEach(x -> { + errList.add(x.getDefaultMessage()); + }); + return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage(), errList.toString()); + } + + /** + * JSON 序列化异常 + * + * @param e + * @return + */ + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseVO exceptionHandler(HttpMessageNotReadableException e) { + log.error(e.getMessage()); + return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage() + ":{" + e.getMessage() + "}"); + } + + /** + * 校验异常 + * + * @param e + * @return + */ + @ExceptionHandler(BindException.class) + public ResponseVO BindException(BindException e) { + final List errList = new ArrayList<>(); + e.getBindingResult().getAllErrors().stream().forEach(x -> { + errList.add(x.getDefaultMessage()); + }); + return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage(), errList.toString()); + } + + /** + * 服务器内部错误 + * + * @return + */ + @ExceptionHandler(value = Exception.class) + public ResponseVO serverInternalError(Exception e, HttpServletRequest request) { + String url = request.getRequestURI(); + log.error("path:" + url); + log.error("error:"+ e.getClass()); + log.error("error message:"+ e.getLocalizedMessage() + e.getStackTrace()[0] + System.getProperty("line.separator")); + return ResponseData.generateCreatedResponse(Code.SERVER_INTERNAL_ERROR.getCode(), Code.SERVER_INTERNAL_ERROR.getMessage(), url); + } +} \ No newline at end of file diff --git a/src/main/java/com/template/common/exception/HttpException.java b/src/main/java/com/template/common/exception/HttpException.java new file mode 100644 index 0000000..f187a44 --- /dev/null +++ b/src/main/java/com/template/common/exception/HttpException.java @@ -0,0 +1,45 @@ +package com.template.common.exception; + +import com.template.common.configure.RemoteProperties; + +/** + * 异常处理 + * + * @author DengMin + * @date 2020/08/12 + **/ +public class HttpException extends RuntimeException { + + private Integer code; + + private String message; + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + @Override + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public HttpException(Integer code) { + super(RemoteProperties.getMessage(code)); + String message = RemoteProperties.getMessage(code); + this.message = message; + this.code = code; + } + + public HttpException(Integer code, String message) { + this.message = message; + this.code = code; + } +} diff --git a/src/main/java/com/template/common/generator/CodeGenerator.java b/src/main/java/com/template/common/generator/CodeGenerator.java new file mode 100644 index 0000000..f9d269f --- /dev/null +++ b/src/main/java/com/template/common/generator/CodeGenerator.java @@ -0,0 +1,126 @@ +package com.template.common.generator; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; +import com.baomidou.mybatisplus.core.toolkit.StringPool; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.generator.AutoGenerator; +import com.baomidou.mybatisplus.generator.InjectionConfig; +import com.baomidou.mybatisplus.generator.config.*; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; +import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; +import com.template.model.base.BaseModel; + +import java.util.ArrayList; +import java.util.List; +import java.util.ResourceBundle; +import java.util.Scanner; + +/** + *

+ * 项目生成器 + *

+ * + * @author DengMin + */ +public class CodeGenerator { + + public static String scanner(String tip) { + StringBuilder help = new StringBuilder(); + help.append("1.生成全部表 2.输入需要生成表名"); + System.out.println(help); + Scanner scanner = new Scanner(System.in); + Integer ipt = Integer.valueOf(scanner.next()); + if (ipt == 1) { + return ""; + } else if (ipt == 2) { + StringBuilder help1 = new StringBuilder(); + help1.append("请输入" + tip + ":"); + System.out.println(help1); + Scanner scanner1 = new Scanner(System.in); + if (scanner1.hasNext()) { + String name = scanner1.next(); + if (StringUtils.isNotEmpty(name)) { + return name; + } + } + throw new MybatisPlusException("请输入正确的" + tip + "!"); + } + return scanner(tip); + } + + public static void main(String[] args) { + final ResourceBundle rb = ResourceBundle.getBundle("mybatis-generator"); + // 代码生成器 + AutoGenerator mpg = new AutoGenerator(); + + // 全局配置 + GlobalConfig gc = new GlobalConfig(); + gc.setOutputDir(System.getProperty("user.dir") + rb.getString("outputDir")); + gc.setOpen(false); + gc.setBaseResultMap(true); + gc.setBaseColumnList(true); + gc.setAuthor(rb.getString("author")); + gc.setMapperName("%sMapper"); + gc.setEntityName("%sDO"); + gc.setServiceName("%sService"); + gc.setServiceImplName("%sServiceImpl"); + gc.setControllerName("%sController"); + mpg.setGlobalConfig(gc); + + // 数据源配置 + DataSourceConfig dsc = new DataSourceConfig(); + dsc.setDbType(DbType.MYSQL); + dsc.setUrl(rb.getString("url")); + dsc.setDriverName(rb.getString("driverName")); + dsc.setUsername(rb.getString("userName")); + dsc.setPassword(rb.getString("password")); + mpg.setDataSource(dsc); + + // 包配置 + PackageConfig pc = new PackageConfig(); + pc.setParent(rb.getString("setParent")); + pc.setController("controller"); + pc.setService("service"); + pc.setServiceImpl("service.impl"); + pc.setEntity("model"); + pc.setMapper("mapper"); + mpg.setPackageInfo(pc); + + // 自定义配置 + InjectionConfig cfg = new InjectionConfig() { + @Override + public void initMap() { + // to do nothing + } + }; + List focList = new ArrayList<>(); + focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { + @Override + public String outputFile(TableInfo tableInfo) { + // 自定义输入文件名称 + return System.getProperty("user.dir") + rb.getString("mapperPath") + tableInfo.getMapperName() + StringPool.DOT_XML; + } + }); + cfg.setFileOutConfigList(focList); + mpg.setCfg(cfg); + mpg.setTemplate(new TemplateConfig().setXml(null)); + + // 策略配置 + StrategyConfig strategy = new StrategyConfig(); + strategy.setNaming(NamingStrategy.underline_to_camel); + strategy.setColumnNaming(NamingStrategy.underline_to_camel); + strategy.setSuperEntityClass(BaseModel.class); + strategy.setEntityLombokModel(true); + strategy.setRestControllerStyle(true); + String[] tables = scanner("表名,多个英文逗号分割").split(","); + if (StringUtils.isNotBlank(tables[0])) { + strategy.setInclude(tables); + } + strategy.setControllerMappingHyphenStyle(true); + mpg.setStrategy(strategy); + mpg.setTemplateEngine(new FreemarkerTemplateEngine()); + mpg.execute(); + } +} diff --git a/src/main/java/com/template/common/handler/MetaHandler.java b/src/main/java/com/template/common/handler/MetaHandler.java new file mode 100644 index 0000000..5895868 --- /dev/null +++ b/src/main/java/com/template/common/handler/MetaHandler.java @@ -0,0 +1,27 @@ +package com.template.common.handler; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.time.LocalDateTime; + +/** + * 填充配置 + * + * @author DengMin + * @date 2020/07/21 + **/ +@Component +public class MetaHandler implements MetaObjectHandler { + + @Override + public void insertFill(MetaObject metaObject) { + this.setFieldValByName("createDate", LocalDateTime.now(), metaObject); + } + + @Override + public void updateFill(MetaObject metaObject) { + this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject); + } +} diff --git a/src/main/java/com/template/common/interceptor/AuthenticationInterceptor.java b/src/main/java/com/template/common/interceptor/AuthenticationInterceptor.java new file mode 100644 index 0000000..6a6c2a2 --- /dev/null +++ b/src/main/java/com/template/common/interceptor/AuthenticationInterceptor.java @@ -0,0 +1,78 @@ +package com.template.common.interceptor; + +import com.auth0.jwt.interfaces.Claim; +import com.template.common.constant.Code; +import com.template.common.exception.HttpException; +import com.template.common.annotate.LoginRequired; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Map; +import com.template.common.JwtUtil; + +/** + *

+ * 鉴权拦截器 + *

+ * + * @author DengMin + * @since 2021/4/26 + */ +@Component +public class AuthenticationInterceptor implements HandlerInterceptor { + + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + if (!(handler instanceof HandlerMethod)) { + return true; + } + + HandlerMethod handlerMethod = (HandlerMethod) handler; + Method method = handlerMethod.getMethod(); + LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class); + if (methodAnnotation != null) { + String authorization = request.getHeader("Authorization"); + if (StringUtils.isBlank(authorization)) { + throw new HttpException(Code.TOKEN_EXCEPTION.getCode(), Code.TOKEN_EXCEPTION.getMessage()); + } + + String token = authorization; + if (authorization.startsWith("Bearer")) { + token = authorization.replace("Bearer ", ""); + } + + if (token == null || JwtUtil.isExpired(token) || !JwtUtil.verifyToken(token)) { + throw new HttpException(Code.TOKEN_EXCEPTION.getCode(), Code.TOKEN_EXCEPTION.getMessage()); + } + + Map claimMap = JwtUtil.getClaims(token); + if (claimMap != null) { + String[] role = methodAnnotation.value(); + String type = claimMap.get("type").asString(); + if (role.length > 0) { + if (Arrays.asList(role).contains(type)) { +// if (SmsCode.student.equals(type)) { +// StudentDO studentDO = studentService.getById(claimMap.get("id").asLong()); +// if (studentDO != null) { +// Localstorage.setUser(studentDO, type); +// return true; +// } else { +// Localstorage.remove(); +// throw new HttpException(Code.USERNAMENOTFOUND.getCode(), Code.USERNAMENOTFOUND.getMessage()); +// } +// } + } + throw new HttpException(Code.ACCESSDENIED.getCode(), Code.ACCESSDENIED.getMessage()); + } + } + } + return true; + } +} diff --git a/src/main/java/com/template/controller/OssController.java b/src/main/java/com/template/controller/OssController.java new file mode 100644 index 0000000..fea25a9 --- /dev/null +++ b/src/main/java/com/template/controller/OssController.java @@ -0,0 +1,179 @@ +package com.template.controller; + + +import com.aliyun.oss.ClientException; +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import com.aliyun.oss.OSSException; +import com.aliyun.oss.model.*; +import com.template.vo.ResponseData; +import com.template.vo.ResponseVO; +import com.template.vo.oss.GetSecretVO; +import com.template.vo.oss.UploadFileVO; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +@Api(tags = "oss") +@RestController +@RequestMapping("/oss") +public class OssController { + + public static final String keyId = "LTAI5tPAH7P7WQVeowo517BE"; + + + public static final String secret = "0ueqhIfdAZyw5lWlBVSLpAxTtx37RY"; + + +// @Value("${spring.profiles.active}") +// private String env; + + @PostMapping("getSecret") + @ApiOperation("oss秘钥") + public ResponseVO getSecret() { + GetSecretVO getSecretVO = new GetSecretVO(); + getSecretVO.setKey(keyId); + getSecretVO.setSecret(secret); + return ResponseData.generateCreatedResponse(0, getSecretVO); + } + + + @PostMapping("uploadFile") + @ApiOperation("分片上传") + public ResponseVO fenpian(@RequestParam("file") MultipartFile file) { + + UploadFileVO uploadFileVO = new UploadFileVO(); + + // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 + String endpoint = "http://oss-cn-beijing.aliyuncs.com"; + // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 + String accessKeyId = keyId; + String accessKeySecret = secret; + // 填写Bucket名称,例如examplebucket。 + String bucketName = "mass-entrepreneurship"; + // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。 + String objectName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); + + // 创建OSSClient实例。 + OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + try { + // 创建InitiateMultipartUploadRequest对象。 + InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName); + + // 如果需要在初始化分片时设置请求头,请参考以下示例代码。 + ObjectMetadata metadata = new ObjectMetadata(); +// + metadata.setContentType(file.getContentType()); + if ("pdf".equals(file.getContentType())){ + metadata.setContentType("application/x-pcx"); + } + + metadata.setContentDisposition("inline"); +// metadata.setHeader("x-oss-force-download", false); + request.setObjectMetadata(metadata); + // 返回uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。 + // 初始化分片。 + InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request); + String uploadId = upresult.getUploadId(); + + // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。 + List partETags = new ArrayList(); + // 每个分片的大小,用于计算文件有多少个分片。单位为字节。 + final long partSize = 1 * 1024 * 1024L; //1 MB。 + + // 根据上传的数据大小计算分片数。以本地文件为例,说明如何通过File.length()获取上传数据的大小。 +// final File sampleFile = new File("D:\\localpath\\examplefile.txt"); +// long fileLength = sampleFile.length(); +// int partCount = (int) (fileLength / partSize); +// if (fileLength % partSize != 0) { +// partCount++; +// } + + long fileLength = file.getSize(); + int partCount = (int) (fileLength / partSize); + if (fileLength % partSize != 0) { + partCount++; + } + + // 遍历分片上传。 + for (int i = 0; i < partCount; i++) { + long startPos = i * partSize; + long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize; + UploadPartRequest uploadPartRequest = new UploadPartRequest(); + uploadPartRequest.setBucketName(bucketName); + uploadPartRequest.setKey(objectName); + uploadPartRequest.setUploadId(uploadId); + // 设置上传的分片流。 + // 以本地文件为例说明如何创建FIleInputstream,并通过InputStream.skip()方法跳过指定数据。 + InputStream instream = file.getInputStream(); + instream.skip(startPos); + uploadPartRequest.setInputStream(instream); + // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。 + uploadPartRequest.setPartSize(curPartSize); + // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。 + uploadPartRequest.setPartNumber(i + 1); + // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 + UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); + // 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。 + partETags.add(uploadPartResult.getPartETag()); + } + + + // 创建CompleteMultipartUploadRequest对象。 + // 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 + CompleteMultipartUploadRequest completeMultipartUploadRequest = + new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags); + + // 如果需要在完成分片上传的同时设置文件访问权限,请参考以下示例代码。 + // completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.Private); + // 指定是否列举当前UploadId已上传的所有Part。仅在Java SDK为3.14.0及以上版本时,支持通过服务端List分片数据来合并完整文件时,将CompleteMultipartUploadRequest中的partETags设置为null。 + // Map headers = new HashMap(); + // 如果指定了x-oss-complete-all:yes,则OSS会列举当前UploadId已上传的所有Part,然后按照PartNumber的序号排序并执行CompleteMultipartUpload操作。 + // 如果指定了x-oss-complete-all:yes,则不允许继续指定body,否则报错。 + // headers.put("x-oss-complete-all","yes"); + // completeMultipartUploadRequest.setHeaders(headers); + + // 完成分片上传。 + CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest); + uploadFileVO.setUrl(completeMultipartUploadResult.getLocation().replace("http","https")); + uploadFileVO.setRequestId(completeMultipartUploadResult.getRequestId()); + System.out.println(completeMultipartUploadResult.getLocation()); + } catch (OSSException oe) { + System.out.println("Caught an OSSException, which means your request made it to OSS, " + + "but was rejected with an error response for some reason."); + System.out.println("Error Message:" + oe.getErrorMessage()); + System.out.println("Error Code:" + oe.getErrorCode()); + System.out.println("Request ID:" + oe.getRequestId()); + System.out.println("Host ID:" + oe.getHostId()); + oe.printStackTrace(); + } catch (ClientException ce) { + System.out.println("Caught an ClientException, which means the client encountered " + + "a serious internal problem while trying to communicate with OSS, " + + "such as not being able to access the network."); + System.out.println("Error Message:" + ce.getMessage()); + ce.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (ossClient != null) { + ossClient.shutdown(); + } + } + + return ResponseData.generateCreatedResponse(0, uploadFileVO); + } + + +} diff --git a/src/main/java/com/template/model/base/BaseModel.java b/src/main/java/com/template/model/base/BaseModel.java new file mode 100644 index 0000000..4fa0920 --- /dev/null +++ b/src/main/java/com/template/model/base/BaseModel.java @@ -0,0 +1,35 @@ +package com.template.model.base; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.FieldStrategy; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class BaseModel { + + /** + * 创建时间 + */ + @JsonIgnore + @TableField(insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER, value = "create_date", fill = FieldFill.INSERT) + private LocalDateTime createDate; + + /** + * 更新时间 + */ + @JsonIgnore + @TableField(insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER, value = "update_date", fill = FieldFill.UPDATE) + private LocalDateTime updateDate; + + /** + * 删除时间 + */ + @JsonIgnore + @TableLogic + private LocalDateTime deleteTime; +} diff --git a/src/main/java/com/template/utils/AliyunSmsUtil.java b/src/main/java/com/template/utils/AliyunSmsUtil.java new file mode 100644 index 0000000..db2003f --- /dev/null +++ b/src/main/java/com/template/utils/AliyunSmsUtil.java @@ -0,0 +1,211 @@ +package com.template.utils; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.aliyuncs.DefaultAcsClient; +import com.aliyuncs.IAcsClient; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; +import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; +import com.template.common.configure.AliyunSmsProperties; +import com.aliyuncs.profile.DefaultProfile; +import com.aliyuncs.profile.IClientProfile; +import com.template.common.exception.HttpException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.Map; + +/** + *

+ * 阿里云短信 + *

+ * + * @author DengMin + * @since 2021/1/27 + */ + +@Slf4j +@Component +public class AliyunSmsUtil { + + @Autowired + private AliyunSmsProperties aliyunSmsProperties; + + /** + * 阿里云短信 -- 验证码 + * @param phone + * @param code + * @return + */ + public SendSmsResponse send(String phone, int code) { + try { + System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); + System.setProperty("sun.net.client.defaultReadTimeout", "10000"); + + //初始化acsClient,暂不支持region化 + IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret()); + DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain()); + IAcsClient acsClient = new DefaultAcsClient(profile); + + //组装请求对象-具体描述见控制台-文档部分内容 + SendSmsRequest request = new SendSmsRequest(); + //必填:待发送手机号 + request.setPhoneNumbers(phone); + //必填:短信签名-可在短信控制台中找到 + request.setSignName("双创平台"); + //必填:短信模板-可在短信控制台中找到 + request.setTemplateCode("SMS_229640297"); + //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 + request.setTemplateParam("{\"code\":\"" + code + "\"}"); + + //hint 此处可能会抛出异常,注意catch + SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); + if (sendSmsResponse != null && sendSmsResponse.getCode().equals("OK")) { + return sendSmsResponse; + } + + throw new Exception(sendSmsResponse.getMessage()); + } catch (Exception e) { + log.error("---短信发送失败:" + e); + throw new HttpException(10011); + } + } + + public static void main(String[] args) { +// AliyunSmsUtil.sendNew("15201936167",000123); + } + + + /** + * 三网平台短信 + * @param msg + * @param phone + * @param templateId + */ + public void sendTemplateMsg(String msg, String phone, String templateId) { + Map map = new HashMap<>(); + try { + map.put("cpcode", aliyunSmsProperties.getCpcode()); + map.put("msg", msg); + map.put("mobiles", phone); + map.put("excode", aliyunSmsProperties.getExcode()); + map.put("templetid", templateId); + String md5source = aliyunSmsProperties.getCpcode() + msg + phone + aliyunSmsProperties.getExcode() + templateId + aliyunSmsProperties.getKey(); + map.put("sign", makeMD5(new String(md5source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)).toLowerCase()); + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity responseEntity = restTemplate.postForEntity(aliyunSmsProperties.getRcsapi(), map, String.class); + String body = responseEntity.getBody(); + JSONObject object = JSON.parseObject(body); + if (Integer.valueOf(object.get("resultcode").toString()) != 0) { + log.error(object.get("resultmsg").toString()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +// /** +// * 三网平台短信 新版本 https://flaginfo-cloud.yuque.com/staff-rozzgq/ofcpak +// * @param msg +// * @param phone +// * @param templateId +// */ +// public static void sendTemplateMsgNew(String msg, String phone, String templateId) { +// String info = null; +// try{ +// HttpClient httpclient = new HttpClient(); +// PostMethod post = new PostMethod("https://opassapi.infocloud.cc/sms/Api/SendGBK.do");// +// post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"gb2312"); +// post.addParameter("SpCode", templateId); +// post.addParameter("LoginName", "7db124d0baf189d1e485350xxx"); +// post.addParameter("Password", "3df50b24fb8288b9da99d16bf527e9dbf13659748534dca6e0820xxx"); +// post.addParameter("MessageContent", msg); +// post.addParameter("UserNumber", phone); +// post.addParameter("SerialNumber", ""); +// post.addParameter("f", "1"); +// httpclient.executeMethod(post); +// info = new String(post.getResponseBody(),"gbk"); +// System.out.println(info); +// }catch (Exception e) { +// e.printStackTrace(); +// } +// } + + + public void sendTemplateMsgP(String msg, String phone, String templateId) { + Map map = new HashMap<>(); + try { + map.put("cpcode", aliyunSmsProperties.getCpcode()); + map.put("msg", msg); + map.put("mobiles", phone); + map.put("excode", aliyunSmsProperties.getExcode()); + map.put("templetid", templateId); + String md5source = aliyunSmsProperties.getCpcode() + msg + phone + aliyunSmsProperties.getExcode() + templateId + aliyunSmsProperties.getKey(); + map.put("sign", makeMD5(new String(md5source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)).toLowerCase()); + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity responseEntity = restTemplate.postForEntity(aliyunSmsProperties.getRcsapi(), map, String.class); + String body = responseEntity.getBody(); + JSONObject object = JSON.parseObject(body); + if (Integer.valueOf(object.get("resultcode").toString()) != 0) { + log.error(object.get("resultmsg").toString()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public String makeMD5(String plainText) { + String re_md5 = ""; + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(plainText.getBytes(StandardCharsets.UTF_8)); + byte[] b = md.digest(); + int i; + StringBuffer buf = new StringBuffer(); + for (int offset = 0; offset < b.length; offset++) { + i = b[offset]; + if (i < 0) { + i += 256; + } + + if (i < 16) { + buf.append("0"); + } + buf.append(Integer.toHexString(i)); + } + re_md5 = buf.toString().toLowerCase(); + } catch (Exception e) { + e.printStackTrace(); + } + return re_md5; + } + + +// public static String getByteString( byte[] buff_out ) +// { +// StringBuffer strBuf = new StringBuffer(buff_out.length * 3); +// strBuf.append("Length["); +// strBuf.append(buff_out.length); +// strBuf.append("];Content["); +// for ( int i = 0 ; i < buff_out.length ; ++i ) { +// int l = buff_out[i] & 0x0F; +// int h = (buff_out[i] & 0xF0) >> 4; +// +// char ll = (char) (l > 9 ? 'a' + l - 10 : '0' + l); +// char hh = (char) (h > 9 ? 'a' + h - 10 : '0' + h); +// +// strBuf.append(hh); +// strBuf.append(ll); +// strBuf.append(" "); +// } +// strBuf.append("]"); +// return strBuf.toString().toUpperCase(); +// } + +} \ No newline at end of file diff --git a/src/main/java/com/template/utils/ApplicationContextUtil.java b/src/main/java/com/template/utils/ApplicationContextUtil.java new file mode 100644 index 0000000..e35d71d --- /dev/null +++ b/src/main/java/com/template/utils/ApplicationContextUtil.java @@ -0,0 +1,25 @@ +package com.template.utils; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationContextUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + ApplicationContextUtil.applicationContext = applicationContext; + } + + public static T getBean(Class clazz) { + return applicationContext.getBean(clazz); + } + + public static T getBean(String name) { + return (T) applicationContext.getBean(name); + } +} diff --git a/src/main/java/com/template/utils/DateFormatUtil.java b/src/main/java/com/template/utils/DateFormatUtil.java new file mode 100644 index 0000000..64cb5ae --- /dev/null +++ b/src/main/java/com/template/utils/DateFormatUtil.java @@ -0,0 +1,187 @@ +package com.template.utils; + +import com.baomidou.mybatisplus.core.toolkit.StringUtils; + +import java.text.SimpleDateFormat; +import java.time.*; +import java.util.Date; + +/** + * Date格式工具 + * + * @author DengMin + * @date 2020/08/03 + **/ +public class DateFormatUtil { + + public final static String FMT_sdf14_L = "yyyy/MM/dd HH:mm:ss"; + public final static String FMT_sdf_yMd = "yyyy/MM/dd"; + public final static String FMT_sdf_Hm = "H:mm"; + public final static String cron = "s m H d M ? yyyy"; + + /** + * Date转String,自定义格式 + * + * @param date + * @param pattern + * @return + */ + public static String format(Date date, String pattern) { + try { + if (date == null) { + return null; + } + + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + return sdf.format(date); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * String转Date,自定义格式 + * + * @param date + * @param pattern + * @return + */ + public static Date parse(String date, String pattern) { + try { + if (StringUtils.isBlank(date)) { + return null; + } + + SimpleDateFormat sdf = new SimpleDateFormat(pattern); + return sdf.parse(date); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + /** + * LocalDate转Date + * + * @param localDate + * @return + */ + public static Date localDateToDate(LocalDate localDate) { + if (localDate == null) { + return null; + } + + ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); + return Date.from(zonedDateTime.toInstant()); + } + + /** + * LocalDate转String + * + * @param localDate + * @return + */ + public static String localDateToString(LocalDate localDate) { + if (localDate == null) { + return null; + } + + ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); + return format(Date.from(zonedDateTime.toInstant()), FMT_sdf_yMd); + } + + public static Date localDateTimeToDate(LocalDateTime localDateTime) { + if (localDateTime == null) { + return null; + } + + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + /** + * date转localDate + * + * @param date + * @return + */ + public static LocalDate dateTOLocalDate(Date date) { + if (date == null) { + return null; + } + return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + } + + /** + * String转LocalDate + * + * @param date + * @return + */ + public static LocalDate localDateParse(String date) { + if (StringUtils.isBlank(date)) { + return null; + } + return LocalDate.parse(date); + } + + /** + * 时间戳转LocalDate + * + * @param timestamp + * @return + */ + public static LocalDate timestampTOLocalDate(Long timestamp) { + return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(0)).toLocalDate(); + } + + /** + * 时间字符串转Cron + * + * @param date + * @return + */ + public static String getCron(String date) { + try { + Date d = parse(date, FMT_sdf14_L); + SimpleDateFormat sdf = new SimpleDateFormat(cron); + return sdf.format(d); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 时间戳转日期字符串 + * + * @param timestamp 时间戳 + * @return 日期字符串 + * @author ALiang + */ + public static String timestampToDateString(Long timestamp) { + Date date = new Date(timestamp); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FMT_sdf14_L); + return simpleDateFormat.format(date); + } + + /** + * Date转LocalTime + * + * @param date + * @return + */ + public static LocalTime dateToLocalTime(Date date) { + Instant instant = date.toInstant(); + ZoneId zoneId = ZoneId.systemDefault(); + LocalTime localTime = instant.atZone(zoneId).toLocalTime(); + return localTime; + } + + public static LocalDateTime dateToLocalDateTime(Date date) { + Instant instant = date.toInstant(); + ZoneId zoneId = ZoneId.systemDefault(); + LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime(); + return localDateTime; + } +} diff --git a/src/main/java/com/template/utils/EasyExcelUtil.java b/src/main/java/com/template/utils/EasyExcelUtil.java new file mode 100644 index 0000000..3a2af9c --- /dev/null +++ b/src/main/java/com/template/utils/EasyExcelUtil.java @@ -0,0 +1,34 @@ +package com.template.utils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.poi.ss.formula.functions.T; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URLEncoder; +import java.util.List; + +@Slf4j +public class EasyExcelUtil { + + /** + * EasyExcel导出 + * + * @ExcelProperty("字符串标题") + * private String string; + */ + public void export(List list,Class cls) throws IOException { + + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletResponse response = servletRequestAttributes.getResponse(); + String fileName = System.currentTimeMillis()+".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8")); + +// EasyExcel.write(response.getOutputStream(), cls).sheet("sheet").doWrite(list); + } + +} diff --git a/src/main/java/com/template/utils/EncryptionUtil.java b/src/main/java/com/template/utils/EncryptionUtil.java new file mode 100644 index 0000000..e34e325 --- /dev/null +++ b/src/main/java/com/template/utils/EncryptionUtil.java @@ -0,0 +1,99 @@ +package com.template.utils; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.security.MessageDigest; +import java.util.Base64; +import java.util.Random; + +/** + * 敏感数据加密解密 + */ +public class EncryptionUtil { + + // AES加密 + public static String encrypt(String data, String key, String salt) throws Exception { + // 生成密钥 + byte[] keyBytes = generateKey(key, salt); + SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES"); + + // 初始化向量 + byte[] ivBytes = new byte[16]; + System.arraycopy(keyBytes, 0, ivBytes, 0, Math.min(keyBytes.length, ivBytes.length)); + IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes); + + // 加密 + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); + byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8")); + + // 返回Base64编码的密文 + return Base64.getEncoder().encodeToString(encryptedBytes); + } + + // AES解密 + public static String decrypt(String encryptedData, String key, String salt) throws Exception { + // 生成密钥 + byte[] keyBytes = generateKey(key, salt); + SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES"); + + // 初始化向量 + byte[] ivBytes = new byte[16]; + System.arraycopy(keyBytes, 0, ivBytes, 0, Math.min(keyBytes.length, ivBytes.length)); + IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes); + + // 解密 + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); + byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); + + // 返回解密后的字符串 + return new String(decryptedBytes, "UTF-8"); + } + + // 生成密钥(加盐) + private static byte[] generateKey(String key, String salt) throws Exception { + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + byte[] keyBytes = (key + salt).getBytes("UTF-8"); + keyBytes = sha.digest(keyBytes); + return keyBytes; + } + + // 方法:生成指定长度的随机字符串 + public static String generateRandomString(int length) { + // 定义字符集(可以根据需要修改字符集) + String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + // 创建一个随机数生成器 + Random random = new Random(); + StringBuilder sb = new StringBuilder(length); + + // 随机选择字符并拼接 + for (int i = 0; i < length; i++) { + int index = random.nextInt(characters.length()); + sb.append(characters.charAt(index)); + } + + return sb.toString(); + } + + public static void main(String[] args) { + try { + String data = "Hello, World!"; + String key = "youhehulian"; // 密钥 + String salt = generateRandomString(8); // 盐值 + System.out.println("salt:"+salt); + + // 加密 + String encryptedData = encrypt(data, key, salt); + System.out.println("Encrypted Data: " + encryptedData); + + // 解密 + String decryptedData = decrypt(encryptedData, key, salt); + System.out.println("Decrypted Data: " + decryptedData); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/template/utils/ExcelUtil.java b/src/main/java/com/template/utils/ExcelUtil.java new file mode 100644 index 0000000..ad86334 --- /dev/null +++ b/src/main/java/com/template/utils/ExcelUtil.java @@ -0,0 +1,335 @@ +package com.template.utils; + +import com.template.common.annotate.ExcelColumn; +import com.template.common.exception.HttpException; +import com.template.vo.ExcelFieldVO; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.hssf.usermodel.HSSFCellStyle; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.net.URLEncoder; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@Component +public class ExcelUtil { + + private final static String EXCEL2003 = "xls"; + + private final static String EXCEL2007 = "xlsx"; + + public static List readExcel(Class cls, MultipartFile file) { + String fileName = file.getOriginalFilename(); + if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { + throw new HttpException(10800); + } + + Workbook workbook = null; + List list = new ArrayList<>(); + try { + InputStream stream = file.getInputStream(); + if (fileName.endsWith(EXCEL2003)) { + workbook = new HSSFWorkbook(stream); + } else if (fileName.endsWith(EXCEL2007)) { + workbook = new XSSFWorkbook(stream); + } + + if (workbook != null) { + Map> classMap = new HashMap<>(); + List fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList()); + fields.forEach(field -> { + ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); + if (annotation != null) { + String value = annotation.value(); + if (StringUtils.isBlank(value)) { + return; + } + + if (!classMap.containsKey(value)) { + classMap.put(value, new ArrayList<>()); + } + field.setAccessible(true); + classMap.get(value).add(field); + } + }); + + boolean title = true; + Map> reflectionMap = new HashMap<>(); + Sheet sheet = workbook.getSheetAt(0); + for (int i = 0; i <= sheet.getLastRowNum(); i++) { + Row row = sheet.getRow(i); + if (title) { + for (int j = 0; j <= row.getLastCellNum(); j++) { + Cell cell = row.getCell(j); + if (cell != null) { + String cellValue = cell.getStringCellValue(); + if (StringUtils.isNotBlank(cellValue)) { + if (classMap.containsKey(cellValue)) { + reflectionMap.put(j, classMap.get(cellValue)); + } else { + throw new HttpException(10802); + } + } + } + } + title = false; + } else { + if (row == null) { + continue; + } + + boolean isBlank = true; + T t = cls.newInstance(); + for (int j = 0; j <= row.getLastCellNum(); j++) { + if (reflectionMap.containsKey(j)) { + List fieldList = reflectionMap.get(j); + for (Field field : fieldList) { + Cell cell = row.getCell(j); + Class type = field.getType(); + Object cellValue = getCellValue(cell, type); + if (cellValue != null) { + isBlank = false; + } + handleField(t, cellValue, field); + } + } + } + if (!isBlank) { + list.add(t); + } + } + } + } + } catch (InstantiationException | IOException | IllegalAccessException e) { + e.printStackTrace(); + } + return list; + } + + public static void writeExcel(String title, List fields, List list) { + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletResponse response = servletRequestAttributes.getResponse(); + + Workbook wb = new XSSFWorkbook(); + Sheet sheet = wb.createSheet(); + AtomicInteger ai = new AtomicInteger(); + { + sheet.addMergedRegion(new CellRangeAddress(0,0, 0, 6)); + Row t = sheet.createRow(ai.getAndIncrement()); + AtomicInteger tat = new AtomicInteger(); + Cell tcl = t.createCell(tat.getAndIncrement()); + CellStyle style = wb.createCellStyle(); + style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); + style.setAlignment(HSSFCellStyle.ALIGN_CENTER); + style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); + Font f = wb.createFont(); + f.setFontHeightInPoints((short) 13); + f.setBoldweight(Font.BOLDWEIGHT_NORMAL); + style.setFont(f); + tcl.setCellStyle(style); + tcl.setCellValue(title); + + Row row = sheet.createRow(ai.getAndIncrement()); + AtomicInteger at = new AtomicInteger(); + fields.forEach(field -> { + Cell cell = row.createCell(at.getAndIncrement()); + CellStyle cellStyle = wb.createCellStyle(); + cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); + Font font = wb.createFont(); + font.setBoldweight(Font.BOLDWEIGHT_NORMAL); + cellStyle.setFont(font); + cell.setCellStyle(cellStyle); + cell.setCellValue(field.getName()); + }); + + if (list != null) { + for (Map map : list) { + Row r = sheet.createRow(ai.getAndIncrement()); + AtomicInteger a = new AtomicInteger(); + fields.forEach(field -> { + Object value = map.get(field.getField()); + Cell cell = r.createCell(a.getAndIncrement()); + if (value != null) { + cell.setCellValue(value.toString()); + } + }); + } + } + sheet.autoSizeColumn(1); + String fileName = String.valueOf(new Date().getTime()); + buildExcelDocument(fileName + "." + EXCEL2007, wb, response); + } + } + + public static void writeExcel(List fields, List list) { + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletResponse response = servletRequestAttributes.getResponse(); + + Workbook wb = new XSSFWorkbook(); + Sheet sheet = wb.createSheet(); + AtomicInteger ai = new AtomicInteger(); + { + Row row = sheet.createRow(ai.getAndIncrement()); + AtomicInteger at = new AtomicInteger(); + fields.forEach(field -> { + Cell cell = row.createCell(at.getAndIncrement()); + CellStyle cellStyle = wb.createCellStyle(); + cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); + Font font = wb.createFont(); + font.setBoldweight(Font.BOLDWEIGHT_BOLD); + cellStyle.setFont(font); + cell.setCellStyle(cellStyle); + cell.setCellValue(field.getName()); + }); + + if (list != null) { + list.forEach(map -> { + Row r = sheet.createRow(ai.getAndIncrement()); + AtomicInteger a = new AtomicInteger(); + fields.forEach(field -> { + Object value = map.get(field.getField()); + Cell cell = r.createCell(a.getAndIncrement()); + if (value != null) { + cell.setCellValue(value.toString()); + } + }); + }); + for (int i = 0; i < list.size(); i++) { + sheet.autoSizeColumn(i); + } + } + String fileName = String.valueOf(new Date().getTime()); + buildExcelDocument(fileName + "." + EXCEL2007, wb, response); + } + } + + public static List getField(Class cls) { + List fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList()); + List list = new ArrayList<>(); + fields.forEach(field -> { + ExcelFieldVO excelFieldVO = new ExcelFieldVO(); + ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); + if (annotation != null) { + + String value = annotation.value(); + if (StringUtils.isBlank(value)) { + return; + } + + excelFieldVO.setField(field.getName()); + excelFieldVO.setName(value); + field.setAccessible(true); + list.add(excelFieldVO); + } + }); + return list; + } + + private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) { + try { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); + response.flushBuffer(); + wb.write(response.getOutputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static Object getCellValue(Cell cell, Class type) { + if (cell == null) { + return null; + } + + if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { + if (DateUtil.isCellDateFormatted(cell)) { + if ("h:mm".equals(cell.getCellStyle().getDataFormatString()) || "hh:mm".equals(cell.getCellStyle().getDataFormatString())) { + return DateFormatUtil.format(cell.getDateCellValue(), DateFormatUtil.FMT_sdf_Hm); + } + return cell.getDateCellValue(); + } else { + if (type != null) { + if (type == String.class) { + cell.setCellType(Cell.CELL_TYPE_STRING); + return cell.getStringCellValue(); + } else { + return cell.getNumericCellValue(); + } + } else { + cell.setCellType(Cell.CELL_TYPE_STRING); + return cell.getStringCellValue(); + } + + } + } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { + return cell.getStringCellValue(); + } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { + return cell.getCellFormula(); + } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) { + return ""; + } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { + return String.valueOf(cell.getBooleanCellValue()); + } else { + return cell; + } + } + + private static void handleField(T t, Object value, Field field) { + try { + Class type = field.getType(); + if (type == null || type == void.class || value == null) { + return; + } + + if (type == Object.class) { + field.set(t, value); + } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) { + if (type == BigDecimal.class) { + field.set(t, new BigDecimal(value.toString())); + } else { + field.set(t, value); + } + } else if (type == Boolean.class) { + field.set(t, BooleanUtils.toBoolean(value.toString())); + } else if (type == Date.class || type == LocalTime.class || type == LocalDateTime.class) { + if (type == Date.class) { + field.set(t, value); + } else if (type == LocalTime.class) { + if (value != null && value != "") { + field.set(t, DateFormatUtil.dateToLocalTime(DateFormatUtil.parse(value.toString(), DateFormatUtil.FMT_sdf_yMd))); + } + } else if (type == LocalDateTime.class) { + if (value != null && value != "") { + field.set(t, DateFormatUtil.dateToLocalDateTime(DateFormatUtil.parse(value.toString(), DateFormatUtil.FMT_sdf_yMd))); + } + } + } else if (type == String.class) { + field.set(t, value.toString()); + } else { + Constructor constructor = type.getConstructor(String.class); + field.set(t, constructor.newInstance(value)); + } + } catch (Exception e) { + e.printStackTrace(); + throw new HttpException(10801); + } + } +} diff --git a/src/main/java/com/template/utils/IpAddressUtil.java b/src/main/java/com/template/utils/IpAddressUtil.java new file mode 100644 index 0000000..c54407c --- /dev/null +++ b/src/main/java/com/template/utils/IpAddressUtil.java @@ -0,0 +1,36 @@ +package com.template.utils; + +import javax.servlet.http.HttpServletRequest; +import java.net.InetAddress; +import java.net.UnknownHostException; + +public class IpAddressUtil { + + public static String getIpAddress(HttpServletRequest request) { + String ipAddress = request.getHeader("x-forwarded-for"); + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("WL-Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getRemoteAddr(); + if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { + InetAddress inet = null; + try { + inet = InetAddress.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + ipAddress = inet.getHostAddress(); + } + } + if (ipAddress != null && ipAddress.length() > 15) { + if (ipAddress.indexOf(",") > 0) { + ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); + } + } + return ipAddress; + } +} diff --git a/src/main/java/com/template/utils/LocalstorageUtil.java b/src/main/java/com/template/utils/LocalstorageUtil.java new file mode 100644 index 0000000..189568d --- /dev/null +++ b/src/main/java/com/template/utils/LocalstorageUtil.java @@ -0,0 +1,33 @@ +package com.template.utils; + +import org.springframework.web.bind.annotation.RestController; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +@RestController +public class LocalstorageUtil { + + private static final ThreadLocal local = ThreadLocal.withInitial(() -> null); + private static ConcurrentHashMap map = new ConcurrentHashMap<>(); + public static void setUser(Object obj, String type) { + Map map = new HashMap<>(); + map.put("user", obj); + map.put("type", type); + LocalstorageUtil.local.set(map); + } + + public static Map getMap() { + return (Map) LocalstorageUtil.local.get(); + } + + public static Object getUser() { + Map map = (Map) LocalstorageUtil.local.get(); + return map.get("user"); + } + + public static void remove() { + LocalstorageUtil.local.remove(); + } +} diff --git a/src/main/java/com/template/utils/PDFUtil.java b/src/main/java/com/template/utils/PDFUtil.java new file mode 100644 index 0000000..92f9502 --- /dev/null +++ b/src/main/java/com/template/utils/PDFUtil.java @@ -0,0 +1,109 @@ +package com.template.utils; + +import com.itextpdf.text.*; +import com.itextpdf.text.pdf.BaseFont; +import com.itextpdf.text.pdf.PdfPTable; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +@Slf4j +@Component +public class PDFUtil { + + static BaseFont baseFont; + + { + try { + baseFont = BaseFont.createFont("https://zhongzhi-cms.oss-cn-shanghai.aliyuncs.com/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void tableStyle(PdfPTable table, int[] cellsWidth) throws DocumentException { + table.setWidths(cellsWidth); + table.setWidthPercentage(100); + table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); + table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); + table.getDefaultCell().setFixedHeight(30); + table.getDefaultCell().setBackgroundColor(BaseColor.BLUE); + table.getDefaultCell().setPadding(0); + table.getDefaultCell().setBorderWidth(0); + } + + /** + * 流化下载 + * + * @param bytes + * @param filename + */ + public static void renderPdf(final byte[] bytes, final String filename, String type) { + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletResponse response = servletRequestAttributes.getResponse(); + initResponseHeader(response, "application/" + type); + setFileDownloadHeader(response, filename, "." + type); + if (null != bytes) { + try { + response.getOutputStream().write(bytes); + response.getOutputStream().flush(); + } catch (IOException e) { + throw new IllegalArgumentException(e); + } + } + } + + /** + * 分析并设置contentType与headers. + */ + private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) { + // 分析headers参数 + String encoding = "utf-8"; + boolean noCache = true; + for (String header : headers) { + String headerName = StringUtils.substringBefore(header, ":"); + String headerValue = StringUtils.substringAfter(header, ":"); + if (StringUtils.equalsIgnoreCase(headerName, "utf-8")) { + encoding = headerValue; + } else if (StringUtils.equalsIgnoreCase(headerName, "no-cache")) { + noCache = Boolean.parseBoolean(headerValue); + } else { + throw new IllegalArgumentException(headerName + "不是一个合法的header类型"); + } + } + // 设置headers参数 + String fullContentType = contentType + ";charset=" + encoding; + response.setContentType(fullContentType); + if (noCache) { + // Http 1.0 header + response.setDateHeader("Expires", 0); + response.addHeader("Pragma", "no-cache"); + // Http 1.1 header + response.setHeader("Cache-Control", "no-cache"); + } + return response; + } + + /** + * 设置让浏览器弹出下载对话框的Header. + * + * @param + */ + public static void setFileDownloadHeader(HttpServletResponse response, String fileName, String fileType) { + try { + // 中文文件名支持 + String encodedfileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"); + response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + fileType + "\""); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/template/utils/RandomUtil.java b/src/main/java/com/template/utils/RandomUtil.java new file mode 100644 index 0000000..3ef7a83 --- /dev/null +++ b/src/main/java/com/template/utils/RandomUtil.java @@ -0,0 +1,58 @@ +package com.template.utils; + +import java.util.Date; +import java.util.Random; + +public class RandomUtil { + + public static int getCode() { + return (int) ((Math.random() * 9 + 1) * 100000); + } + + public static String randomPass(Integer count) { + StringBuffer stringBuffer = new StringBuffer(); + Random random = new Random(new Date().getTime()); + String flag = type[random.nextInt(type.length)]; + int length = count; + for (int i = 0; i < length; i++) { + switch (flag) { + case "word": + stringBuffer.append(word[random.nextInt(word.length)]); + break; + case "num": + stringBuffer.append(num[random.nextInt(num.length)]); + break; + case "symbol": + stringBuffer.append(symbol[random.nextInt(symbol.length)]); + break; + default: + break; + } + flag = type[random.nextInt(type.length)]; + } + return stringBuffer.toString(); + } + + public final static String[] type = { + "word", "num", "symbol" + }; + + public final static String[] word = { + "a", "b", "c", "d", "e", "f", "g", + "h", "j", "k", "m", "n", + "p", "q", "r", "s", "t", + "u", "v", "w", "x", "y", "z", + "A", "B", "C", "D", "E", "F", "G", + "H", "J", "K", "M", "N", + "P", "Q", "R", "S", "T", + "U", "V", "W", "X", "Y", "Z" + }; + + public final static String[] num = { + "1", "2", "3", "4", "5", "6", "7", "8", "9" + }; + + public final static String[] symbol = { + "!", "@", "#", "$", "%", "&" + }; +} diff --git a/src/main/java/com/template/utils/VodUtil.java b/src/main/java/com/template/utils/VodUtil.java new file mode 100644 index 0000000..b858dc8 --- /dev/null +++ b/src/main/java/com/template/utils/VodUtil.java @@ -0,0 +1,116 @@ +package com.template.utils; + +import com.tencentcloudapi.common.Credential; +import com.tencentcloudapi.common.exception.TencentCloudSDKException; +import com.tencentcloudapi.common.profile.ClientProfile; +import com.tencentcloudapi.common.profile.HttpProfile; +import com.tencentcloudapi.vod.v20180717.VodClient; +import com.tencentcloudapi.vod.v20180717.models.*; +import com.template.common.configure.VODConfig; +import com.template.common.exception.HttpException; +import org.springframework.stereotype.Component; + +/** + *

+ * 腾讯云 - 云点播API + *

+ * + * @author DengMin + * @since 2022/8/1 + */ +@Component +public class VodUtil { + + private static String endpoint = "vod.tencentcloudapi.com"; + + /** + * 根据视频模版进行转码 + * @param vodCode + * @return + */ + public static ProcessMediaResponse processMedia(VODConfig vodConfig, String vodCode) { + try { + //上传后直接转码 + Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey()); + HttpProfile httpProfile = new HttpProfile(); + httpProfile.setEndpoint(endpoint); + + ClientProfile clientProfile = new ClientProfile(); + clientProfile.setHttpProfile(httpProfile); + + VodClient client = new VodClient(cred, "", clientProfile); + + ProcessMediaRequest processMediaRequest = new ProcessMediaRequest(); + MediaProcessTaskInput mediaProcessTaskInput1 = new MediaProcessTaskInput(); + TranscodeTaskInput[] transcodeTaskInputs1 = new TranscodeTaskInput[1]; + TranscodeTaskInput transcodeTaskInput1 = new TranscodeTaskInput(); + transcodeTaskInput1.setDefinition(100030L); + transcodeTaskInputs1[0] = transcodeTaskInput1; + mediaProcessTaskInput1.setTranscodeTaskSet(transcodeTaskInputs1); + processMediaRequest.setMediaProcessTask(mediaProcessTaskInput1); + processMediaRequest.setFileId(vodCode); + return client.ProcessMedia(processMediaRequest); + } catch (Exception ex) { + throw new HttpException(50001); + } + } + + /** + * 删除腾讯云上原视频 + * @param vodCode + */ + public static void deleteMedia(VODConfig vodConfig, String vodCode) { + try { + //删除原视频 + Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey()); + HttpProfile httpProfile = new HttpProfile(); + httpProfile.setEndpoint(endpoint); + + ClientProfile clientProfile = new ClientProfile(); + clientProfile.setHttpProfile(httpProfile); + + VodClient client = new VodClient(cred, "", clientProfile); + // 实例化一个请求对象,每个接口都会对应一个request对象 + DeleteMediaRequest req = new DeleteMediaRequest(); + req.setFileId(vodCode); + // 返回的resp是一个DeleteMediaResponse的实例,与请求对象对应 + client.DeleteMedia(req); + } catch (TencentCloudSDKException e) { + throw new HttpException(99999, e.getMessage()); + } + } + + /** + * 云点播域名的CDN统计数据 + * @param vodConfig + * @param DataType + * @param startTime + * @param endTime + * @return + */ + public static StatDataItem[] DescribeCDNStatDetails(VODConfig vodConfig, String DataType, String startTime, String endTime) { + try { + Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey()); + // 实例化一个http选项,可选的,没有特殊需求可以跳过 + HttpProfile httpProfile = new HttpProfile(); + httpProfile.setEndpoint(endpoint); + // 实例化一个client选项,可选的,没有特殊需求可以跳过 + ClientProfile clientProfile = new ClientProfile(); + clientProfile.setHttpProfile(httpProfile); + // 实例化要请求产品的client对象,clientProfile是可选的 + VodClient client = new VodClient(cred, "", clientProfile); + // 实例化一个请求对象,每个接口都会对应一个request对象 + DescribeCDNUsageDataRequest req = new DescribeCDNUsageDataRequest(); + req.setStartTime(startTime); + req.setEndTime(endTime); + req.setDataType(DataType); + // 返回的resp是一个DescribeCDNUsageDataResponse的实例,与请求对象对应 + DescribeCDNUsageDataResponse resp = client.DescribeCDNUsageData(req); + // 返回的resp是一个DescribeCDNStatDetailsResponse的实例,与请求对象对应 + return resp.getData(); + } catch (TencentCloudSDKException e) { + e.printStackTrace(); + throw new HttpException(99999, e.getMessage()); + } + } +} diff --git a/src/main/java/com/template/vo/ExcelFieldVO.java b/src/main/java/com/template/vo/ExcelFieldVO.java new file mode 100644 index 0000000..d6cef13 --- /dev/null +++ b/src/main/java/com/template/vo/ExcelFieldVO.java @@ -0,0 +1,11 @@ +package com.template.vo; + +import lombok.Data; + +@Data +public class ExcelFieldVO { + + private String field; + + private String name; +} diff --git a/src/main/java/com/template/vo/ResponseData.java b/src/main/java/com/template/vo/ResponseData.java new file mode 100644 index 0000000..b6afcb1 --- /dev/null +++ b/src/main/java/com/template/vo/ResponseData.java @@ -0,0 +1,54 @@ +package com.template.vo; + +import com.template.common.configure.RemoteProperties; +import lombok.Data; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +/** + * 返回数据 + * + * @author DengMin + * @date 2019/08/27 13:57 + **/ +@Data +@EnableConfigurationProperties(RemoteProperties.class) +public class ResponseData { + + public static ResponseVO generateCreatedResponse(int code) { + return (ResponseVO) ResponseVO.builder() + .code(code) + .message(RemoteProperties.getMessage(code)) + .build(); + } + + public static ResponseVO generateCreatedResponse(int code, String message) { + return (ResponseVO) ResponseVO.builder() + .code(code) + .message(message) + .build(); + } + + public static ResponseVO generateCreatedResponse(int code, T data) { + return (ResponseVO) ResponseVO.builder() + .code(code) + .message(RemoteProperties.getMessage(code)) + .data(data) + .build(); + } + + public static ResponseVO generateCreatedResponse(int code, String message, T data) { + return (ResponseVO) ResponseVO.builder() + .code(code) + .message(message) + .data(data) + .build(); + } + + public static ResponseVO generateCreatedResponse(int code, String message, String path) { + return (ResponseVO) ResponseVO.builder() + .code(code) + .message(message) + .path(path) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/template/vo/ResponseVO.java b/src/main/java/com/template/vo/ResponseVO.java new file mode 100644 index 0000000..01d7fcf --- /dev/null +++ b/src/main/java/com/template/vo/ResponseVO.java @@ -0,0 +1,21 @@ +package com.template.vo; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ResponseVO { + + private Integer code; + + private String message; + + private T data; + + private String path; +} diff --git a/src/main/java/com/template/vo/oss/GetSecretVO.java b/src/main/java/com/template/vo/oss/GetSecretVO.java new file mode 100644 index 0000000..b49d6bc --- /dev/null +++ b/src/main/java/com/template/vo/oss/GetSecretVO.java @@ -0,0 +1,13 @@ +package com.template.vo.oss; + +import lombok.Data; + +@Data +public class GetSecretVO { + + private String key; + + private String secret; + + +} diff --git a/src/main/java/com/template/vo/oss/UploadFileVO.java b/src/main/java/com/template/vo/oss/UploadFileVO.java new file mode 100644 index 0000000..7302354 --- /dev/null +++ b/src/main/java/com/template/vo/oss/UploadFileVO.java @@ -0,0 +1,12 @@ +package com.template.vo.oss; + +import lombok.Data; + +@Data +public class UploadFileVO { + + private String url; + + private String requestId; + +} diff --git a/src/main/java/com/zhongzhi/ZhongzhiApplication.java b/src/main/java/com/zhongzhi/ZhongzhiApplication.java deleted file mode 100644 index b790a2a..0000000 --- a/src/main/java/com/zhongzhi/ZhongzhiApplication.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.zhongzhi; - -import org.mybatis.spring.annotation.MapperScan; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@MapperScan(basePackages = {"com.zhongzhi.dao"}) -@SpringBootApplication -public class ZhongzhiApplication { - - public static void main(String[] args) { - SpringApplication.run(ZhongzhiApplication.class, args); - } - -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/common/JwtUtil.java b/src/main/java/com/zhongzhi/common/JwtUtil.java deleted file mode 100644 index e1604eb..0000000 --- a/src/main/java/com/zhongzhi/common/JwtUtil.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.zhongzhi.common; - -import com.auth0.jwt.JWT; -import com.auth0.jwt.JWTVerifier; -import com.auth0.jwt.algorithms.Algorithm; -import com.auth0.jwt.interfaces.Claim; - -import java.util.Date; -import java.util.Map; - -/** - *

- * Token工具 - *

- * - * @author DengMin - * @since 2021/4/14 - */ -public class JwtUtil { - - private static final Long EXPIRE_TIME = 24 * 60 * 60 * 1000L; - - private static final String SECRET = "PBKDF2SHA256:64000:18:24:N:GFHZ6Y0PTEUDYCJI3K6SOOXWYEKPOZED:WBWFJMX5DF252E0HR3BF3P/D"; - - /** - * 生成Token - * - * @param id - * @return - */ - public static String generateToken(Long id, String type) { - Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME); - return JWT.create() - .withClaim("id", id) - .withClaim("type", type) - .withAudience() - .withExpiresAt(expireDate) - .withIssuedAt(new Date()) - .sign(Algorithm.HMAC256(SECRET)); - } - - /** - * 检验token是否正确 - * - * @param token - * @return - */ - public static boolean verifyToken(String token) { - try { - Algorithm algorithm = Algorithm.HMAC256(SECRET); - JWTVerifier verifier = JWT.require(algorithm).build(); - verifier.verify(token); - return true; - } catch (Exception e) { - return false; - } - } - - /** - * 获取用户自定义Claim集合 - * - * @param token - * @return - */ - public static Map getClaims(String token) { - Algorithm algorithm = Algorithm.HMAC256(SECRET); - JWTVerifier verifier = JWT.require(algorithm).build(); - Map claims = verifier.verify(token).getClaims(); - return claims; - } - - /** - * 获取过期时间 - * - * @param token - * @return - */ - public static Date getExpiresAt(String token) { - Algorithm algorithm = Algorithm.HMAC256(SECRET); - return JWT - .require(algorithm) - .build() - .verify(token) - .getExpiresAt(); - } - - /** - * 验证token是否失效 - * - * @param token - * @return true: 过期, false: 没过期 - */ - public static boolean isExpired(String token) { - try { - final Date expiration = getExpiresAt(token); - return expiration.before(new Date()); - } catch (Exception e) { - return true; - } - } -} diff --git a/src/main/java/com/zhongzhi/common/annotate/ExcelColumn.java b/src/main/java/com/zhongzhi/common/annotate/ExcelColumn.java deleted file mode 100644 index e0bb256..0000000 --- a/src/main/java/com/zhongzhi/common/annotate/ExcelColumn.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.zhongzhi.common.annotate; - -import java.lang.annotation.*; - -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface ExcelColumn { - - String value() default ""; - - int col() default 1; -} diff --git a/src/main/java/com/zhongzhi/common/annotate/LoginRequired.java b/src/main/java/com/zhongzhi/common/annotate/LoginRequired.java deleted file mode 100644 index b2e84b1..0000000 --- a/src/main/java/com/zhongzhi/common/annotate/LoginRequired.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.zhongzhi.common.annotate; - -import java.lang.annotation.*; - -/** - *

- * 自定义验证登陆注解 - *

- * - * @author DengMin - * @since 2020/12/18 - */ -@Target({ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -public @interface LoginRequired { - - String[] value(); - -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/common/annotate/SysLog.java b/src/main/java/com/zhongzhi/common/annotate/SysLog.java deleted file mode 100644 index 3d1bebe..0000000 --- a/src/main/java/com/zhongzhi/common/annotate/SysLog.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.zhongzhi.common.annotate; - -import java.lang.annotation.*; - -/** - *

- * 自定义日志注解 - *

- * - * @author DengMin - * @since 2020/12/18 - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface SysLog { - - String value() default ""; -} diff --git a/src/main/java/com/zhongzhi/common/configure/AliyunSmsProperties.java b/src/main/java/com/zhongzhi/common/configure/AliyunSmsProperties.java deleted file mode 100644 index 8bf4bc1..0000000 --- a/src/main/java/com/zhongzhi/common/configure/AliyunSmsProperties.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.zhongzhi.common.configure; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -@Data -@Component -@ConfigurationProperties(prefix = "sms") -public class AliyunSmsProperties { - - private String product; - - private String domain; - - private String accessKeyId; - - private String accessKeySecret; - - private String cpcode; - - private String excode; - - private String key; - - private String rcsapi; - -} diff --git a/src/main/java/com/zhongzhi/common/configure/MybatisPlusConfig.java b/src/main/java/com/zhongzhi/common/configure/MybatisPlusConfig.java deleted file mode 100644 index 4ca9b62..0000000 --- a/src/main/java/com/zhongzhi/common/configure/MybatisPlusConfig.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.zhongzhi.common.configure; - -import com.baomidou.mybatisplus.annotation.DbType; -import com.baomidou.mybatisplus.core.config.GlobalConfig; -import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; -import com.zhongzhi.common.handler.MetaHandler; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class MybatisPlusConfig { - - /** - * 分页 - * - * @return - */ - @Bean - public PaginationInterceptor paginationInterceptor() { - PaginationInterceptor page = new PaginationInterceptor(); - page.setDialectType(DbType.MYSQL.getDb()); - return page; - } - - /** - * 自动填充功能 - * - * @return - */ - @Bean - public GlobalConfig globalConfig() { - GlobalConfig globalConfig = new GlobalConfig(); - globalConfig.setMetaObjectHandler(new MetaHandler()); - return globalConfig; - } -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/common/configure/RemoteProperties.java b/src/main/java/com/zhongzhi/common/configure/RemoteProperties.java deleted file mode 100644 index 46b5fa0..0000000 --- a/src/main/java/com/zhongzhi/common/configure/RemoteProperties.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.zhongzhi.common.configure; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.PropertySource; -import org.springframework.stereotype.Component; - -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 读取状态码 - *

- * - * @author DengMin - * @date Created in 2020/08/24 - */ -@Component -@ConfigurationProperties(prefix = "c") -@PropertySource(value = "classpath:code.properties", encoding = "UTF-8") -public class RemoteProperties { - - private static Map codeMessage = new HashMap<>(); - - public static String getMessage(Integer code) { - return codeMessage.get(code); - } - - public Map getCodeMessage() { - return codeMessage; - } - - public void setCodeMessage(Map codeMessage) { - RemoteProperties.codeMessage = codeMessage; - } -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/common/configure/SwaggerConfig.java b/src/main/java/com/zhongzhi/common/configure/SwaggerConfig.java deleted file mode 100644 index 6cd020d..0000000 --- a/src/main/java/com/zhongzhi/common/configure/SwaggerConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.zhongzhi.common.configure; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -/** - *

- * swagger2 - *

- * - * @author DengMin - * @since 2020/12/8 - */ -@Configuration -@EnableSwagger2 -public class SwaggerConfig { - - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .pathMapping("/") - .select() - .apis(RequestHandlerSelectors.basePackage("com.zhongzhi.controller")) - .paths(PathSelectors.any()) - .build() - .apiInfo(new ApiInfoBuilder() - .title("国泰君安") - .description("接口文档") - .version("1.0") - .build()); - } -} diff --git a/src/main/java/com/zhongzhi/common/configure/VODConfig.java b/src/main/java/com/zhongzhi/common/configure/VODConfig.java deleted file mode 100644 index aec1353..0000000 --- a/src/main/java/com/zhongzhi/common/configure/VODConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.zhongzhi.common.configure; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -/** - * @author: tuyp - * @create: 2020-06-01 16:46 - */ -@Component -@Data -@ConfigurationProperties(prefix = "vod") -public class VODConfig { - - private String appId; - - private String secretId; - - private String secretKey; - - private String api; - - private String region; - - private Integer classId; -} diff --git a/src/main/java/com/zhongzhi/common/configure/WebConfig.java b/src/main/java/com/zhongzhi/common/configure/WebConfig.java deleted file mode 100644 index 3c656ea..0000000 --- a/src/main/java/com/zhongzhi/common/configure/WebConfig.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.zhongzhi.common.configure; - -import com.zhongzhi.common.interceptor.AuthenticationInterceptor; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import org.springframework.web.filter.CorsFilter; -import org.springframework.web.servlet.config.annotation.*; - -/** - * @author DengMin - * @date 2020/07/06 - **/ -@Configuration -public class WebConfig extends WebMvcConfigurationSupport { - - @Autowired - private AuthenticationInterceptor authenticationInterceptor; - - /** - * 跨域支持 - * - * @param registry - */ - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowCredentials(true) - .allowedOrigins("*") - .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") - .maxAge(3600); - } - - @Bean - public CorsFilter corsFilter() { - CorsConfiguration config = new CorsConfiguration(); - config.setMaxAge(3600L); - config.addAllowedOrigin("*"); - config.addAllowedMethod("*"); - config.addAllowedHeader("*"); - UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); - configSource.registerCorsConfiguration("/**", config); - return new CorsFilter(configSource); - } - - /** - * Swagger - * - * @param registry - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/**") - .addResourceLocations("classpath:/static/"); - registry.addResourceHandler("swagger-ui.html") - .addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**") - .addResourceLocations("classpath:/META-INF/resources/webjars/"); - super.addResourceHandlers(registry); - } - - /** - * 鉴权 - * - * @param registry - */ - @Override - public void addInterceptors(InterceptorRegistry registry) { - registry.addInterceptor(authenticationInterceptor) - .excludePathPatterns("/static/*") - .addPathPatterns("/**"); - } -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/common/constant/Code.java b/src/main/java/com/zhongzhi/common/constant/Code.java deleted file mode 100644 index 69d55f2..0000000 --- a/src/main/java/com/zhongzhi/common/constant/Code.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.zhongzhi.common.constant; - -import lombok.Getter; - -@Getter -public enum Code { - - USERNAMENOTFOUND(1001, "用户不存在"), - BADCREDENTIALS(1002, "账户或者密码错误"), - ACCOUNTEXPIRED(1003, "账户过期"), - LOCKEDEXCEPTION(1004, "账户已锁定"), - DISABLEDEXCEPTION(1005, "账户已禁用"), - ACCESSDENIED(1006, "无权限访问"), - AUTHENTICATION(1007, "身份验证异常"), - NOHANDLERFOUND(1008, "找不到相应的视图处理器"), - PARAM_INVALID(1009, "参数不合法"), - TOKEN_EXCEPTION(1010, "无效的令牌"), - TOKEN_EXPIRED(1011, "令牌已过期"), - TOKEN_VERIFICATION_FAILED(1012, "令牌验证失败"), - OSS_ERROR(1013, "OSS文件上传异常"), - Network_ERROR(9000, "网络请求失败"), - SERVER_INTERNAL_ERROR(99999, "服务器内部错误"), - ; - - private final Integer code; - - private final String message; - - Code(Integer code, String message) { - this.code = code; - this.message = message; - } -} diff --git a/src/main/java/com/zhongzhi/common/constant/Platform.java b/src/main/java/com/zhongzhi/common/constant/Platform.java deleted file mode 100644 index 00bcb93..0000000 --- a/src/main/java/com/zhongzhi/common/constant/Platform.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.zhongzhi.common.constant; - -/** - *

- * 平台标识 - *

- * - * @author DengMin - * @since 2021/6/9 - */ -public class Platform { - - /* - 学生端 - */ - public static final String student = "student"; - - /* - 院校端 - */ - public static final String school = "school"; - - /* - 中心端 - */ - public static final String center = "center"; - - /* - 评审端 - */ - public static final String review = "review"; -} diff --git a/src/main/java/com/zhongzhi/common/exception/GlobalExceptionHandler.java b/src/main/java/com/zhongzhi/common/exception/GlobalExceptionHandler.java deleted file mode 100644 index 6ed351c..0000000 --- a/src/main/java/com/zhongzhi/common/exception/GlobalExceptionHandler.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.zhongzhi.common.exception; - -import com.baomidou.mybatisplus.core.toolkit.StringUtils; -import com.zhongzhi.common.configure.RemoteProperties; -import com.zhongzhi.common.constant.Code; -import com.zhongzhi.vo.ResponseData; -import com.zhongzhi.vo.ResponseVO; -import lombok.extern.slf4j.Slf4j; -import org.apache.poi.ss.formula.functions.T; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.validation.BindException; -import org.springframework.web.HttpRequestMethodNotSupportedException; -import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RestControllerAdvice; -import org.springframework.web.servlet.NoHandlerFoundException; - -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.List; - -@Slf4j -@RestControllerAdvice -public class GlobalExceptionHandler { - - /** - * 自定义异常 - * - * @param e - * @return - */ - @ExceptionHandler(value = HttpException.class) - public ResponseVO handlerException(HttpServletRequest request, HttpException e) { - String message = RemoteProperties.getMessage(e.getCode()); - if (StringUtils.isBlank(message)) { - message = e.getMessage(); - } - String url = request.getRequestURI(); - return ResponseData.generateCreatedResponse(e.getCode(), message, url); - } - - /** - * 404 - * - * @param request - * @return - */ - @ExceptionHandler(value = NoHandlerFoundException.class) - public ResponseVO NoHandlerFoundException(HttpServletRequest request) { - String url = request.getRequestURI(); - return ResponseData.generateCreatedResponse(Code.NOHANDLERFOUND.getCode(), Code.NOHANDLERFOUND.getMessage(), url); - } - - /** - * 请求方式错误 - * - * @param request - * @return - */ - @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) - public ResponseVO HttpRequestMethodNotSupportedException(HttpServletRequest request) { - String url = request.getRequestURI(); - return ResponseData.generateCreatedResponse(Code.NOHANDLERFOUND.getCode(), Code.NOHANDLERFOUND.getMessage(), url); - } - - /** - * 参数不合法 - * - * @param e - * @return - */ - @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseVO validateException(MethodArgumentNotValidException e) { - final List errList = new ArrayList<>(); - e.getBindingResult().getAllErrors().stream().forEach(x -> { - errList.add(x.getDefaultMessage()); - }); - return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage(), errList.toString()); - } - - /** - * JSON 序列化异常 - * - * @param e - * @return - */ - @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseVO exceptionHandler(HttpMessageNotReadableException e) { - log.error(e.getMessage()); - return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage() + ":{" + e.getMessage() + "}"); - } - - /** - * 校验异常 - * - * @param e - * @return - */ - @ExceptionHandler(BindException.class) - public ResponseVO BindException(BindException e) { - final List errList = new ArrayList<>(); - e.getBindingResult().getAllErrors().stream().forEach(x -> { - errList.add(x.getDefaultMessage()); - }); - return ResponseData.generateCreatedResponse(Code.PARAM_INVALID.getCode(), Code.PARAM_INVALID.getMessage(), errList.toString()); - } - - /** - * 服务器内部错误 - * - * @return - */ - @ExceptionHandler(value = Exception.class) - public ResponseVO serverInternalError(Exception e, HttpServletRequest request) { - String url = request.getRequestURI(); - log.error("path:" + url); - log.error("error:"+ e.getClass()); - log.error("error message:"+ e.getLocalizedMessage() + e.getStackTrace()[0] + System.getProperty("line.separator")); - return ResponseData.generateCreatedResponse(Code.SERVER_INTERNAL_ERROR.getCode(), Code.SERVER_INTERNAL_ERROR.getMessage(), url); - } -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/common/exception/HttpException.java b/src/main/java/com/zhongzhi/common/exception/HttpException.java deleted file mode 100644 index b14bcc0..0000000 --- a/src/main/java/com/zhongzhi/common/exception/HttpException.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.zhongzhi.common.exception; - -import com.zhongzhi.common.configure.RemoteProperties; - -/** - * 异常处理 - * - * @author DengMin - * @date 2020/08/12 - **/ -public class HttpException extends RuntimeException { - - private Integer code; - - private String message; - - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - @Override - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public HttpException(Integer code) { - super(RemoteProperties.getMessage(code)); - String message = RemoteProperties.getMessage(code); - this.message = message; - this.code = code; - } - - public HttpException(Integer code, String message) { - this.message = message; - this.code = code; - } -} diff --git a/src/main/java/com/zhongzhi/common/generator/CodeGenerator.java b/src/main/java/com/zhongzhi/common/generator/CodeGenerator.java deleted file mode 100644 index 7f325fb..0000000 --- a/src/main/java/com/zhongzhi/common/generator/CodeGenerator.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.zhongzhi.common.generator; - -import com.baomidou.mybatisplus.annotation.DbType; -import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; -import com.baomidou.mybatisplus.core.toolkit.StringPool; -import com.baomidou.mybatisplus.core.toolkit.StringUtils; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.*; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; -import com.zhongzhi.model.base.BaseModel; - -import java.util.ArrayList; -import java.util.List; -import java.util.ResourceBundle; -import java.util.Scanner; - -/** - *

- * 项目生成器 - *

- * - * @author DengMin - */ -public class CodeGenerator { - - public static String scanner(String tip) { - StringBuilder help = new StringBuilder(); - help.append("1.生成全部表 2.输入需要生成表名"); - System.out.println(help); - Scanner scanner = new Scanner(System.in); - Integer ipt = Integer.valueOf(scanner.next()); - if (ipt == 1) { - return ""; - } else if (ipt == 2) { - StringBuilder help1 = new StringBuilder(); - help1.append("请输入" + tip + ":"); - System.out.println(help1); - Scanner scanner1 = new Scanner(System.in); - if (scanner1.hasNext()) { - String name = scanner1.next(); - if (StringUtils.isNotEmpty(name)) { - return name; - } - } - throw new MybatisPlusException("请输入正确的" + tip + "!"); - } - return scanner(tip); - } - - public static void main(String[] args) { - final ResourceBundle rb = ResourceBundle.getBundle("mybatis-generator"); - // 代码生成器 - AutoGenerator mpg = new AutoGenerator(); - - // 全局配置 - GlobalConfig gc = new GlobalConfig(); - gc.setOutputDir(System.getProperty("user.dir") + rb.getString("outputDir")); - gc.setOpen(false); - gc.setBaseResultMap(true); - gc.setBaseColumnList(true); - gc.setAuthor(rb.getString("author")); - gc.setMapperName("%sMapper"); - gc.setEntityName("%sDO"); - gc.setServiceName("%sService"); - gc.setServiceImplName("%sServiceImpl"); - gc.setControllerName("%sController"); - mpg.setGlobalConfig(gc); - - // 数据源配置 - DataSourceConfig dsc = new DataSourceConfig(); - dsc.setDbType(DbType.MYSQL); - dsc.setUrl(rb.getString("url")); - dsc.setDriverName(rb.getString("driverName")); - dsc.setUsername(rb.getString("userName")); - dsc.setPassword(rb.getString("password")); - mpg.setDataSource(dsc); - - // 包配置 - PackageConfig pc = new PackageConfig(); - pc.setParent(rb.getString("setParent")); - pc.setController("controller"); - pc.setService("service"); - pc.setServiceImpl("service.impl"); - pc.setEntity("model"); - pc.setMapper("mapper"); - mpg.setPackageInfo(pc); - - // 自定义配置 - InjectionConfig cfg = new InjectionConfig() { - @Override - public void initMap() { - // to do nothing - } - }; - List focList = new ArrayList<>(); - focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { - @Override - public String outputFile(TableInfo tableInfo) { - // 自定义输入文件名称 - return System.getProperty("user.dir") + rb.getString("mapperPath") + tableInfo.getMapperName() + StringPool.DOT_XML; - } - }); - cfg.setFileOutConfigList(focList); - mpg.setCfg(cfg); - mpg.setTemplate(new TemplateConfig().setXml(null)); - - // 策略配置 - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); - strategy.setSuperEntityClass(BaseModel.class); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - String[] tables = scanner("表名,多个英文逗号分割").split(","); - if (StringUtils.isNotBlank(tables[0])) { - strategy.setInclude(tables); - } - strategy.setControllerMappingHyphenStyle(true); - mpg.setStrategy(strategy); - mpg.setTemplateEngine(new FreemarkerTemplateEngine()); - mpg.execute(); - } -} diff --git a/src/main/java/com/zhongzhi/common/handler/MetaHandler.java b/src/main/java/com/zhongzhi/common/handler/MetaHandler.java deleted file mode 100644 index 00d055f..0000000 --- a/src/main/java/com/zhongzhi/common/handler/MetaHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.zhongzhi.common.handler; - -import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; -import org.apache.ibatis.reflection.MetaObject; -import org.springframework.stereotype.Component; - -import java.time.LocalDateTime; - -/** - * 填充配置 - * - * @author DengMin - * @date 2020/07/21 - **/ -@Component -public class MetaHandler implements MetaObjectHandler { - - @Override - public void insertFill(MetaObject metaObject) { - this.setFieldValByName("createDate", LocalDateTime.now(), metaObject); - } - - @Override - public void updateFill(MetaObject metaObject) { - this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject); - } -} diff --git a/src/main/java/com/zhongzhi/common/interceptor/AuthenticationInterceptor.java b/src/main/java/com/zhongzhi/common/interceptor/AuthenticationInterceptor.java deleted file mode 100644 index 01e8816..0000000 --- a/src/main/java/com/zhongzhi/common/interceptor/AuthenticationInterceptor.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.zhongzhi.common.interceptor; - -import com.auth0.jwt.interfaces.Claim; -import com.zhongzhi.common.constant.Code; -import com.zhongzhi.common.exception.HttpException; -import com.zhongzhi.common.annotate.LoginRequired; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Component; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.HandlerInterceptor; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Map; -import com.zhongzhi.common.JwtUtil; - -/** - *

- * 鉴权拦截器 - *

- * - * @author DengMin - * @since 2021/4/26 - */ -@Component -public class AuthenticationInterceptor implements HandlerInterceptor { - - - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { - if (!(handler instanceof HandlerMethod)) { - return true; - } - - HandlerMethod handlerMethod = (HandlerMethod) handler; - Method method = handlerMethod.getMethod(); - LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class); - if (methodAnnotation != null) { - String authorization = request.getHeader("Authorization"); - if (StringUtils.isBlank(authorization)) { - throw new HttpException(Code.TOKEN_EXCEPTION.getCode(), Code.TOKEN_EXCEPTION.getMessage()); - } - - String token = authorization; - if (authorization.startsWith("Bearer")) { - token = authorization.replace("Bearer ", ""); - } - - if (token == null || JwtUtil.isExpired(token) || !JwtUtil.verifyToken(token)) { - throw new HttpException(Code.TOKEN_EXCEPTION.getCode(), Code.TOKEN_EXCEPTION.getMessage()); - } - - Map claimMap = JwtUtil.getClaims(token); - if (claimMap != null) { - String[] role = methodAnnotation.value(); - String type = claimMap.get("type").asString(); - if (role.length > 0) { - if (Arrays.asList(role).contains(type)) { -// if (SmsCode.student.equals(type)) { -// StudentDO studentDO = studentService.getById(claimMap.get("id").asLong()); -// if (studentDO != null) { -// Localstorage.setUser(studentDO, type); -// return true; -// } else { -// Localstorage.remove(); -// throw new HttpException(Code.USERNAMENOTFOUND.getCode(), Code.USERNAMENOTFOUND.getMessage()); -// } -// } - } - throw new HttpException(Code.ACCESSDENIED.getCode(), Code.ACCESSDENIED.getMessage()); - } - } - } - return true; - } -} diff --git a/src/main/java/com/zhongzhi/controller/OssController.java b/src/main/java/com/zhongzhi/controller/OssController.java deleted file mode 100644 index 4aa0cbe..0000000 --- a/src/main/java/com/zhongzhi/controller/OssController.java +++ /dev/null @@ -1,213 +0,0 @@ -package com.zhongzhi.controller; - - -import com.aliyun.oss.ClientException; -import com.aliyun.oss.OSS; -import com.aliyun.oss.OSSClientBuilder; -import com.aliyun.oss.OSSException; -import com.aliyun.oss.model.*; -import com.zhongzhi.vo.ResponseData; -import com.zhongzhi.vo.ResponseVO; -import com.zhongzhi.vo.oss.GetSecretVO; -import com.zhongzhi.vo.oss.UploadFileVO; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -@Api(tags = "oss") -@RestController -@RequestMapping("/oss") -public class OssController { - - public static final String keyId = "LTAI5tPAH7P7WQVeowo517BE"; - - - public static final String secret = "0ueqhIfdAZyw5lWlBVSLpAxTtx37RY"; - - -// @Value("${spring.profiles.active}") -// private String env; - - @PostMapping("getSecret") - @ApiOperation("oss秘钥") - public ResponseVO getSecret() { - GetSecretVO getSecretVO = new GetSecretVO(); - getSecretVO.setKey(keyId); - getSecretVO.setSecret(secret); - return ResponseData.generateCreatedResponse(0, getSecretVO); - } - -// @PostMapping("uploadFile") -// @ApiOperation("上传文件 file") -// public ResponseVO uploadFile(@RequestParam("file") MultipartFile file) { -// // 创建OSSClient实例。 -// OSS ossClient = new OSSClientBuilder().build("http://oss-cn-shanghai.aliyuncs.com", keyId, secret); -// UploadFileVO uploadFileVO = new UploadFileVO(); -// try { -//// -//// if (env.equals("test")) { -//// env = "ykhl-bigger-test"; -//// } -//// if (env.equals("prod")) { -//// env = "ykhl-bigger"; -//// } -// -// -// // 创建PutObjectRequest对象。 -// PutObjectRequest putObjectRequest = new PutObjectRequest("zhongzhi-cms", System.currentTimeMillis() + "_" + file.getOriginalFilename(), file.getInputStream()); -// // 设置该属性可以返回response。如果不设置,则返回的response为空。 -// putObjectRequest.setProcess("true"); -// // 创建PutObject请求。 -// PutObjectResult result = ossClient.putObject(putObjectRequest); -// // 如果上传成功,则返回200。 -//// System.out.println(result.getResponse().getUri()); -// uploadFileVO.setUrl(result.getResponse().getUri()); -// } catch (Exception oe) { -// oe.printStackTrace(); -// } finally { -// if (ossClient != null) { -// ossClient.shutdown(); -// } -// } -// return ResponseData.generateCreatedResponse(0, uploadFileVO); -// } - - @PostMapping("uploadFile") - @ApiOperation("分片上传") - public ResponseVO fenpian(@RequestParam("file") MultipartFile file) { - - UploadFileVO uploadFileVO = new UploadFileVO(); - - // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 - String endpoint = "http://oss-cn-beijing.aliyuncs.com"; - // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 - String accessKeyId = keyId; - String accessKeySecret = secret; - // 填写Bucket名称,例如examplebucket。 - String bucketName = "mass-entrepreneurship"; - // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。 - String objectName = System.currentTimeMillis() + "_" + file.getOriginalFilename(); - - // 创建OSSClient实例。 - OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); - try { - // 创建InitiateMultipartUploadRequest对象。 - InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName); - - // 如果需要在初始化分片时设置请求头,请参考以下示例代码。 - ObjectMetadata metadata = new ObjectMetadata(); -// - metadata.setContentType(file.getContentType()); - if ("pdf".equals(file.getContentType())){ - metadata.setContentType("application/x-pcx"); - } - - metadata.setContentDisposition("inline"); -// metadata.setHeader("x-oss-force-download", false); - request.setObjectMetadata(metadata); - // 返回uploadId,它是分片上传事件的唯一标识。您可以根据该uploadId发起相关的操作,例如取消分片上传、查询分片上传等。 - // 初始化分片。 - InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request); - String uploadId = upresult.getUploadId(); - - // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。 - List partETags = new ArrayList(); - // 每个分片的大小,用于计算文件有多少个分片。单位为字节。 - final long partSize = 1 * 1024 * 1024L; //1 MB。 - - // 根据上传的数据大小计算分片数。以本地文件为例,说明如何通过File.length()获取上传数据的大小。 -// final File sampleFile = new File("D:\\localpath\\examplefile.txt"); -// long fileLength = sampleFile.length(); -// int partCount = (int) (fileLength / partSize); -// if (fileLength % partSize != 0) { -// partCount++; -// } - - long fileLength = file.getSize(); - int partCount = (int) (fileLength / partSize); - if (fileLength % partSize != 0) { - partCount++; - } - - // 遍历分片上传。 - for (int i = 0; i < partCount; i++) { - long startPos = i * partSize; - long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize; - UploadPartRequest uploadPartRequest = new UploadPartRequest(); - uploadPartRequest.setBucketName(bucketName); - uploadPartRequest.setKey(objectName); - uploadPartRequest.setUploadId(uploadId); - // 设置上传的分片流。 - // 以本地文件为例说明如何创建FIleInputstream,并通过InputStream.skip()方法跳过指定数据。 - InputStream instream = file.getInputStream(); - instream.skip(startPos); - uploadPartRequest.setInputStream(instream); - // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100 KB。 - uploadPartRequest.setPartSize(curPartSize); - // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出此范围,OSS将返回InvalidArgument错误码。 - uploadPartRequest.setPartNumber(i + 1); - // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 - UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); - // 每次上传分片之后,OSS的返回结果包含PartETag。PartETag将被保存在partETags中。 - partETags.add(uploadPartResult.getPartETag()); - } - - - // 创建CompleteMultipartUploadRequest对象。 - // 在执行完成分片上传操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 - CompleteMultipartUploadRequest completeMultipartUploadRequest = - new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags); - - // 如果需要在完成分片上传的同时设置文件访问权限,请参考以下示例代码。 - // completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.Private); - // 指定是否列举当前UploadId已上传的所有Part。仅在Java SDK为3.14.0及以上版本时,支持通过服务端List分片数据来合并完整文件时,将CompleteMultipartUploadRequest中的partETags设置为null。 - // Map headers = new HashMap(); - // 如果指定了x-oss-complete-all:yes,则OSS会列举当前UploadId已上传的所有Part,然后按照PartNumber的序号排序并执行CompleteMultipartUpload操作。 - // 如果指定了x-oss-complete-all:yes,则不允许继续指定body,否则报错。 - // headers.put("x-oss-complete-all","yes"); - // completeMultipartUploadRequest.setHeaders(headers); - - // 完成分片上传。 - CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest); - uploadFileVO.setUrl(completeMultipartUploadResult.getLocation().replace("http","https")); - uploadFileVO.setRequestId(completeMultipartUploadResult.getRequestId()); - System.out.println(completeMultipartUploadResult.getLocation()); - } catch (OSSException oe) { - System.out.println("Caught an OSSException, which means your request made it to OSS, " - + "but was rejected with an error response for some reason."); - System.out.println("Error Message:" + oe.getErrorMessage()); - System.out.println("Error Code:" + oe.getErrorCode()); - System.out.println("Request ID:" + oe.getRequestId()); - System.out.println("Host ID:" + oe.getHostId()); - oe.printStackTrace(); - } catch (ClientException ce) { - System.out.println("Caught an ClientException, which means the client encountered " - + "a serious internal problem while trying to communicate with OSS, " - + "such as not being able to access the network."); - System.out.println("Error Message:" + ce.getMessage()); - ce.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (ossClient != null) { - ossClient.shutdown(); - } - } - - return ResponseData.generateCreatedResponse(0, uploadFileVO); - } - - -} diff --git a/src/main/java/com/zhongzhi/model/base/BaseModel.java b/src/main/java/com/zhongzhi/model/base/BaseModel.java deleted file mode 100644 index 405a4d7..0000000 --- a/src/main/java/com/zhongzhi/model/base/BaseModel.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.zhongzhi.model.base; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.FieldStrategy; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.fasterxml.jackson.annotation.JsonIgnore; -import lombok.Data; - -import java.time.LocalDateTime; - -@Data -public class BaseModel { - - /** - * 创建时间 - */ - @JsonIgnore - @TableField(insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER, value = "create_date", fill = FieldFill.INSERT) - private LocalDateTime createDate; - - /** - * 更新时间 - */ - @JsonIgnore - @TableField(insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER, value = "update_date", fill = FieldFill.UPDATE) - private LocalDateTime updateDate; - - /** - * 删除时间 - */ - @JsonIgnore - @TableLogic - private LocalDateTime deleteTime; -} diff --git a/src/main/java/com/zhongzhi/utils/AliyunSmsUtil.java b/src/main/java/com/zhongzhi/utils/AliyunSmsUtil.java deleted file mode 100644 index e5e5544..0000000 --- a/src/main/java/com/zhongzhi/utils/AliyunSmsUtil.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.zhongzhi.utils; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.aliyuncs.DefaultAcsClient; -import com.aliyuncs.IAcsClient; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; -import com.zhongzhi.common.configure.AliyunSmsProperties; -import com.aliyuncs.profile.DefaultProfile; -import com.aliyuncs.profile.IClientProfile; -import com.zhongzhi.common.exception.HttpException; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; -import org.springframework.web.client.RestTemplate; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.util.HashMap; -import java.util.Map; - -/** - *

- * 阿里云短信 - *

- * - * @author DengMin - * @since 2021/1/27 - */ - -@Slf4j -@Component -public class AliyunSmsUtil { - - @Autowired - private AliyunSmsProperties aliyunSmsProperties; - - /** - * 阿里云短信 -- 验证码 - * @param phone - * @param code - * @return - */ - public SendSmsResponse send(String phone, int code) { - try { - System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); - System.setProperty("sun.net.client.defaultReadTimeout", "10000"); - - //初始化acsClient,暂不支持region化 - IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", aliyunSmsProperties.getAccessKeyId(), aliyunSmsProperties.getAccessKeySecret()); - DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain()); - IAcsClient acsClient = new DefaultAcsClient(profile); - - //组装请求对象-具体描述见控制台-文档部分内容 - SendSmsRequest request = new SendSmsRequest(); - //必填:待发送手机号 - request.setPhoneNumbers(phone); - //必填:短信签名-可在短信控制台中找到 - request.setSignName("双创平台"); - //必填:短信模板-可在短信控制台中找到 - request.setTemplateCode("SMS_229640297"); - //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 - request.setTemplateParam("{\"code\":\"" + code + "\"}"); - - //hint 此处可能会抛出异常,注意catch - SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); - if (sendSmsResponse != null && sendSmsResponse.getCode().equals("OK")) { - return sendSmsResponse; - } - - throw new Exception(sendSmsResponse.getMessage()); - } catch (Exception e) { - log.error("---短信发送失败:" + e); - throw new HttpException(10011); - } - } - - public static void main(String[] args) { -// AliyunSmsUtil.sendNew("15201936167",000123); - } - - - /** - * 三网平台短信 - * @param msg - * @param phone - * @param templateId - */ - public void sendTemplateMsg(String msg, String phone, String templateId) { - Map map = new HashMap<>(); - try { - map.put("cpcode", aliyunSmsProperties.getCpcode()); - map.put("msg", msg); - map.put("mobiles", phone); - map.put("excode", aliyunSmsProperties.getExcode()); - map.put("templetid", templateId); - String md5source = aliyunSmsProperties.getCpcode() + msg + phone + aliyunSmsProperties.getExcode() + templateId + aliyunSmsProperties.getKey(); - map.put("sign", makeMD5(new String(md5source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)).toLowerCase()); - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity responseEntity = restTemplate.postForEntity(aliyunSmsProperties.getRcsapi(), map, String.class); - String body = responseEntity.getBody(); - JSONObject object = JSON.parseObject(body); - if (Integer.valueOf(object.get("resultcode").toString()) != 0) { - log.error(object.get("resultmsg").toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - -// /** -// * 三网平台短信 新版本 https://flaginfo-cloud.yuque.com/staff-rozzgq/ofcpak -// * @param msg -// * @param phone -// * @param templateId -// */ -// public static void sendTemplateMsgNew(String msg, String phone, String templateId) { -// String info = null; -// try{ -// HttpClient httpclient = new HttpClient(); -// PostMethod post = new PostMethod("https://opassapi.infocloud.cc/sms/Api/SendGBK.do");// -// post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"gb2312"); -// post.addParameter("SpCode", templateId); -// post.addParameter("LoginName", "7db124d0baf189d1e485350xxx"); -// post.addParameter("Password", "3df50b24fb8288b9da99d16bf527e9dbf13659748534dca6e0820xxx"); -// post.addParameter("MessageContent", msg); -// post.addParameter("UserNumber", phone); -// post.addParameter("SerialNumber", ""); -// post.addParameter("f", "1"); -// httpclient.executeMethod(post); -// info = new String(post.getResponseBody(),"gbk"); -// System.out.println(info); -// }catch (Exception e) { -// e.printStackTrace(); -// } -// } - - - public void sendTemplateMsgP(String msg, String phone, String templateId) { - Map map = new HashMap<>(); - try { - map.put("cpcode", aliyunSmsProperties.getCpcode()); - map.put("msg", msg); - map.put("mobiles", phone); - map.put("excode", aliyunSmsProperties.getExcode()); - map.put("templetid", templateId); - String md5source = aliyunSmsProperties.getCpcode() + msg + phone + aliyunSmsProperties.getExcode() + templateId + aliyunSmsProperties.getKey(); - map.put("sign", makeMD5(new String(md5source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8)).toLowerCase()); - RestTemplate restTemplate = new RestTemplate(); - ResponseEntity responseEntity = restTemplate.postForEntity(aliyunSmsProperties.getRcsapi(), map, String.class); - String body = responseEntity.getBody(); - JSONObject object = JSON.parseObject(body); - if (Integer.valueOf(object.get("resultcode").toString()) != 0) { - log.error(object.get("resultmsg").toString()); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public String makeMD5(String plainText) { - String re_md5 = ""; - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(plainText.getBytes(StandardCharsets.UTF_8)); - byte[] b = md.digest(); - int i; - StringBuffer buf = new StringBuffer(); - for (int offset = 0; offset < b.length; offset++) { - i = b[offset]; - if (i < 0) { - i += 256; - } - - if (i < 16) { - buf.append("0"); - } - buf.append(Integer.toHexString(i)); - } - re_md5 = buf.toString().toLowerCase(); - } catch (Exception e) { - e.printStackTrace(); - } - return re_md5; - } - - -// public static String getByteString( byte[] buff_out ) -// { -// StringBuffer strBuf = new StringBuffer(buff_out.length * 3); -// strBuf.append("Length["); -// strBuf.append(buff_out.length); -// strBuf.append("];Content["); -// for ( int i = 0 ; i < buff_out.length ; ++i ) { -// int l = buff_out[i] & 0x0F; -// int h = (buff_out[i] & 0xF0) >> 4; -// -// char ll = (char) (l > 9 ? 'a' + l - 10 : '0' + l); -// char hh = (char) (h > 9 ? 'a' + h - 10 : '0' + h); -// -// strBuf.append(hh); -// strBuf.append(ll); -// strBuf.append(" "); -// } -// strBuf.append("]"); -// return strBuf.toString().toUpperCase(); -// } - -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/utils/ApplicationContextUtil.java b/src/main/java/com/zhongzhi/utils/ApplicationContextUtil.java deleted file mode 100644 index ab79dfe..0000000 --- a/src/main/java/com/zhongzhi/utils/ApplicationContextUtil.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.zhongzhi.utils; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -@Component -public class ApplicationContextUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - ApplicationContextUtil.applicationContext = applicationContext; - } - - public static T getBean(Class clazz) { - return applicationContext.getBean(clazz); - } - - public static T getBean(String name) { - return (T) applicationContext.getBean(name); - } -} diff --git a/src/main/java/com/zhongzhi/utils/DateFormatUtil.java b/src/main/java/com/zhongzhi/utils/DateFormatUtil.java deleted file mode 100644 index cadc6c8..0000000 --- a/src/main/java/com/zhongzhi/utils/DateFormatUtil.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.zhongzhi.utils; - -import com.baomidou.mybatisplus.core.toolkit.StringUtils; - -import java.text.SimpleDateFormat; -import java.time.*; -import java.util.Date; - -/** - * Date格式工具 - * - * @author DengMin - * @date 2020/08/03 - **/ -public class DateFormatUtil { - - public final static String FMT_sdf14_L = "yyyy/MM/dd HH:mm:ss"; - public final static String FMT_sdf_yMd = "yyyy/MM/dd"; - public final static String FMT_sdf_Hm = "H:mm"; - public final static String cron = "s m H d M ? yyyy"; - - /** - * Date转String,自定义格式 - * - * @param date - * @param pattern - * @return - */ - public static String format(Date date, String pattern) { - try { - if (date == null) { - return null; - } - - SimpleDateFormat sdf = new SimpleDateFormat(pattern); - return sdf.format(date); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * String转Date,自定义格式 - * - * @param date - * @param pattern - * @return - */ - public static Date parse(String date, String pattern) { - try { - if (StringUtils.isBlank(date)) { - return null; - } - - SimpleDateFormat sdf = new SimpleDateFormat(pattern); - return sdf.parse(date); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /** - * LocalDate转Date - * - * @param localDate - * @return - */ - public static Date localDateToDate(LocalDate localDate) { - if (localDate == null) { - return null; - } - - ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); - return Date.from(zonedDateTime.toInstant()); - } - - /** - * LocalDate转String - * - * @param localDate - * @return - */ - public static String localDateToString(LocalDate localDate) { - if (localDate == null) { - return null; - } - - ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault()); - return format(Date.from(zonedDateTime.toInstant()), FMT_sdf_yMd); - } - - public static Date localDateTimeToDate(LocalDateTime localDateTime) { - if (localDateTime == null) { - return null; - } - - return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); - } - - /** - * date转localDate - * - * @param date - * @return - */ - public static LocalDate dateTOLocalDate(Date date) { - if (date == null) { - return null; - } - return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); - } - - /** - * String转LocalDate - * - * @param date - * @return - */ - public static LocalDate localDateParse(String date) { - if (StringUtils.isBlank(date)) { - return null; - } - return LocalDate.parse(date); - } - - /** - * 时间戳转LocalDate - * - * @param timestamp - * @return - */ - public static LocalDate timestampTOLocalDate(Long timestamp) { - return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(0)).toLocalDate(); - } - - /** - * 时间字符串转Cron - * - * @param date - * @return - */ - public static String getCron(String date) { - try { - Date d = parse(date, FMT_sdf14_L); - SimpleDateFormat sdf = new SimpleDateFormat(cron); - return sdf.format(d); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * 时间戳转日期字符串 - * - * @param timestamp 时间戳 - * @return 日期字符串 - * @author ALiang - */ - public static String timestampToDateString(Long timestamp) { - Date date = new Date(timestamp); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FMT_sdf14_L); - return simpleDateFormat.format(date); - } - - /** - * Date转LocalTime - * - * @param date - * @return - */ - public static LocalTime dateToLocalTime(Date date) { - Instant instant = date.toInstant(); - ZoneId zoneId = ZoneId.systemDefault(); - LocalTime localTime = instant.atZone(zoneId).toLocalTime(); - return localTime; - } - - public static LocalDateTime dateToLocalDateTime(Date date) { - Instant instant = date.toInstant(); - ZoneId zoneId = ZoneId.systemDefault(); - LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime(); - return localDateTime; - } -} diff --git a/src/main/java/com/zhongzhi/utils/EncryptionUtil.java b/src/main/java/com/zhongzhi/utils/EncryptionUtil.java deleted file mode 100644 index 09c9924..0000000 --- a/src/main/java/com/zhongzhi/utils/EncryptionUtil.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.zhongzhi.utils; - -import javax.crypto.Cipher; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; -import java.security.MessageDigest; -import java.util.Base64; -import java.util.Random; - -/** - * 敏感数据加密解密 - */ -public class EncryptionUtil { - - // AES加密 - public static String encrypt(String data, String key, String salt) throws Exception { - // 生成密钥 - byte[] keyBytes = generateKey(key, salt); - SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES"); - - // 初始化向量 - byte[] ivBytes = new byte[16]; - System.arraycopy(keyBytes, 0, ivBytes, 0, Math.min(keyBytes.length, ivBytes.length)); - IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes); - - // 加密 - Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); - byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8")); - - // 返回Base64编码的密文 - return Base64.getEncoder().encodeToString(encryptedBytes); - } - - // AES解密 - public static String decrypt(String encryptedData, String key, String salt) throws Exception { - // 生成密钥 - byte[] keyBytes = generateKey(key, salt); - SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES"); - - // 初始化向量 - byte[] ivBytes = new byte[16]; - System.arraycopy(keyBytes, 0, ivBytes, 0, Math.min(keyBytes.length, ivBytes.length)); - IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes); - - // 解密 - Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); - byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData)); - - // 返回解密后的字符串 - return new String(decryptedBytes, "UTF-8"); - } - - // 生成密钥(加盐) - private static byte[] generateKey(String key, String salt) throws Exception { - MessageDigest sha = MessageDigest.getInstance("SHA-256"); - byte[] keyBytes = (key + salt).getBytes("UTF-8"); - keyBytes = sha.digest(keyBytes); - return keyBytes; - } - - // 方法:生成指定长度的随机字符串 - public static String generateRandomString(int length) { - // 定义字符集(可以根据需要修改字符集) - String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - - // 创建一个随机数生成器 - Random random = new Random(); - StringBuilder sb = new StringBuilder(length); - - // 随机选择字符并拼接 - for (int i = 0; i < length; i++) { - int index = random.nextInt(characters.length()); - sb.append(characters.charAt(index)); - } - - return sb.toString(); - } - - public static void main(String[] args) { - try { - String data = "Hello, World!"; - String key = "youhehulian"; // 密钥 - String salt = generateRandomString(8); // 盐值 - System.out.println("salt:"+salt); - - // 加密 - String encryptedData = encrypt(data, key, salt); - System.out.println("Encrypted Data: " + encryptedData); - - // 解密 - String decryptedData = decrypt(encryptedData, key, salt); - System.out.println("Decrypted Data: " + decryptedData); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/zhongzhi/utils/ExcelUtil.java b/src/main/java/com/zhongzhi/utils/ExcelUtil.java deleted file mode 100644 index 2d10a46..0000000 --- a/src/main/java/com/zhongzhi/utils/ExcelUtil.java +++ /dev/null @@ -1,335 +0,0 @@ -package com.zhongzhi.utils; - -import com.zhongzhi.common.annotate.ExcelColumn; -import com.zhongzhi.common.exception.HttpException; -import com.zhongzhi.vo.ExcelFieldVO; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.multipart.MultipartFile; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.net.URLEncoder; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -@Component -public class ExcelUtil { - - private final static String EXCEL2003 = "xls"; - - private final static String EXCEL2007 = "xlsx"; - - public static List readExcel(Class cls, MultipartFile file) { - String fileName = file.getOriginalFilename(); - if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) { - throw new HttpException(10800); - } - - Workbook workbook = null; - List list = new ArrayList<>(); - try { - InputStream stream = file.getInputStream(); - if (fileName.endsWith(EXCEL2003)) { - workbook = new HSSFWorkbook(stream); - } else if (fileName.endsWith(EXCEL2007)) { - workbook = new XSSFWorkbook(stream); - } - - if (workbook != null) { - Map> classMap = new HashMap<>(); - List fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList()); - fields.forEach(field -> { - ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); - if (annotation != null) { - String value = annotation.value(); - if (StringUtils.isBlank(value)) { - return; - } - - if (!classMap.containsKey(value)) { - classMap.put(value, new ArrayList<>()); - } - field.setAccessible(true); - classMap.get(value).add(field); - } - }); - - boolean title = true; - Map> reflectionMap = new HashMap<>(); - Sheet sheet = workbook.getSheetAt(0); - for (int i = 0; i <= sheet.getLastRowNum(); i++) { - Row row = sheet.getRow(i); - if (title) { - for (int j = 0; j <= row.getLastCellNum(); j++) { - Cell cell = row.getCell(j); - if (cell != null) { - String cellValue = cell.getStringCellValue(); - if (StringUtils.isNotBlank(cellValue)) { - if (classMap.containsKey(cellValue)) { - reflectionMap.put(j, classMap.get(cellValue)); - } else { - throw new HttpException(10802); - } - } - } - } - title = false; - } else { - if (row == null) { - continue; - } - - boolean isBlank = true; - T t = cls.newInstance(); - for (int j = 0; j <= row.getLastCellNum(); j++) { - if (reflectionMap.containsKey(j)) { - List fieldList = reflectionMap.get(j); - for (Field field : fieldList) { - Cell cell = row.getCell(j); - Class type = field.getType(); - Object cellValue = getCellValue(cell, type); - if (cellValue != null) { - isBlank = false; - } - handleField(t, cellValue, field); - } - } - } - if (!isBlank) { - list.add(t); - } - } - } - } - } catch (InstantiationException | IOException | IllegalAccessException e) { - e.printStackTrace(); - } - return list; - } - - public static void writeExcel(String title, List fields, List list) { - ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletResponse response = servletRequestAttributes.getResponse(); - - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - AtomicInteger ai = new AtomicInteger(); - { - sheet.addMergedRegion(new CellRangeAddress(0,0, 0, 6)); - Row t = sheet.createRow(ai.getAndIncrement()); - AtomicInteger tat = new AtomicInteger(); - Cell tcl = t.createCell(tat.getAndIncrement()); - CellStyle style = wb.createCellStyle(); - style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); - style.setAlignment(HSSFCellStyle.ALIGN_CENTER); - style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); - Font f = wb.createFont(); - f.setFontHeightInPoints((short) 13); - f.setBoldweight(Font.BOLDWEIGHT_NORMAL); - style.setFont(f); - tcl.setCellStyle(style); - tcl.setCellValue(title); - - Row row = sheet.createRow(ai.getAndIncrement()); - AtomicInteger at = new AtomicInteger(); - fields.forEach(field -> { - Cell cell = row.createCell(at.getAndIncrement()); - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); - Font font = wb.createFont(); - font.setBoldweight(Font.BOLDWEIGHT_NORMAL); - cellStyle.setFont(font); - cell.setCellStyle(cellStyle); - cell.setCellValue(field.getName()); - }); - - if (list != null) { - for (Map map : list) { - Row r = sheet.createRow(ai.getAndIncrement()); - AtomicInteger a = new AtomicInteger(); - fields.forEach(field -> { - Object value = map.get(field.getField()); - Cell cell = r.createCell(a.getAndIncrement()); - if (value != null) { - cell.setCellValue(value.toString()); - } - }); - } - } - sheet.autoSizeColumn(1); - String fileName = String.valueOf(new Date().getTime()); - buildExcelDocument(fileName + "." + EXCEL2007, wb, response); - } - } - - public static void writeExcel(List fields, List list) { - ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletResponse response = servletRequestAttributes.getResponse(); - - Workbook wb = new XSSFWorkbook(); - Sheet sheet = wb.createSheet(); - AtomicInteger ai = new AtomicInteger(); - { - Row row = sheet.createRow(ai.getAndIncrement()); - AtomicInteger at = new AtomicInteger(); - fields.forEach(field -> { - Cell cell = row.createCell(at.getAndIncrement()); - CellStyle cellStyle = wb.createCellStyle(); - cellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); - Font font = wb.createFont(); - font.setBoldweight(Font.BOLDWEIGHT_BOLD); - cellStyle.setFont(font); - cell.setCellStyle(cellStyle); - cell.setCellValue(field.getName()); - }); - - if (list != null) { - list.forEach(map -> { - Row r = sheet.createRow(ai.getAndIncrement()); - AtomicInteger a = new AtomicInteger(); - fields.forEach(field -> { - Object value = map.get(field.getField()); - Cell cell = r.createCell(a.getAndIncrement()); - if (value != null) { - cell.setCellValue(value.toString()); - } - }); - }); - for (int i = 0; i < list.size(); i++) { - sheet.autoSizeColumn(i); - } - } - String fileName = String.valueOf(new Date().getTime()); - buildExcelDocument(fileName + "." + EXCEL2007, wb, response); - } - } - - public static List getField(Class cls) { - List fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList()); - List list = new ArrayList<>(); - fields.forEach(field -> { - ExcelFieldVO excelFieldVO = new ExcelFieldVO(); - ExcelColumn annotation = field.getAnnotation(ExcelColumn.class); - if (annotation != null) { - - String value = annotation.value(); - if (StringUtils.isBlank(value)) { - return; - } - - excelFieldVO.setField(field.getName()); - excelFieldVO.setName(value); - field.setAccessible(true); - list.add(excelFieldVO); - } - }); - return list; - } - - private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) { - try { - response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); - response.flushBuffer(); - wb.write(response.getOutputStream()); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static Object getCellValue(Cell cell, Class type) { - if (cell == null) { - return null; - } - - if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { - if (DateUtil.isCellDateFormatted(cell)) { - if ("h:mm".equals(cell.getCellStyle().getDataFormatString()) || "hh:mm".equals(cell.getCellStyle().getDataFormatString())) { - return DateFormatUtil.format(cell.getDateCellValue(), DateFormatUtil.FMT_sdf_Hm); - } - return cell.getDateCellValue(); - } else { - if (type != null) { - if (type == String.class) { - cell.setCellType(Cell.CELL_TYPE_STRING); - return cell.getStringCellValue(); - } else { - return cell.getNumericCellValue(); - } - } else { - cell.setCellType(Cell.CELL_TYPE_STRING); - return cell.getStringCellValue(); - } - - } - } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { - return cell.getStringCellValue(); - } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { - return cell.getCellFormula(); - } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) { - return ""; - } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) { - return String.valueOf(cell.getBooleanCellValue()); - } else { - return cell; - } - } - - private static void handleField(T t, Object value, Field field) { - try { - Class type = field.getType(); - if (type == null || type == void.class || value == null) { - return; - } - - if (type == Object.class) { - field.set(t, value); - } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) { - if (type == BigDecimal.class) { - field.set(t, new BigDecimal(value.toString())); - } else { - field.set(t, value); - } - } else if (type == Boolean.class) { - field.set(t, BooleanUtils.toBoolean(value.toString())); - } else if (type == Date.class || type == LocalTime.class || type == LocalDateTime.class) { - if (type == Date.class) { - field.set(t, value); - } else if (type == LocalTime.class) { - if (value != null && value != "") { - field.set(t, DateFormatUtil.dateToLocalTime(DateFormatUtil.parse(value.toString(), DateFormatUtil.FMT_sdf_yMd))); - } - } else if (type == LocalDateTime.class) { - if (value != null && value != "") { - field.set(t, DateFormatUtil.dateToLocalDateTime(DateFormatUtil.parse(value.toString(), DateFormatUtil.FMT_sdf_yMd))); - } - } - } else if (type == String.class) { - field.set(t, value.toString()); - } else { - Constructor constructor = type.getConstructor(String.class); - field.set(t, constructor.newInstance(value)); - } - } catch (Exception e) { - e.printStackTrace(); - throw new HttpException(10801); - } - } -} diff --git a/src/main/java/com/zhongzhi/utils/IpAddressUtil.java b/src/main/java/com/zhongzhi/utils/IpAddressUtil.java deleted file mode 100644 index a3157e6..0000000 --- a/src/main/java/com/zhongzhi/utils/IpAddressUtil.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.zhongzhi.utils; - -import javax.servlet.http.HttpServletRequest; -import java.net.InetAddress; -import java.net.UnknownHostException; - -public class IpAddressUtil { - - public static String getIpAddress(HttpServletRequest request) { - String ipAddress = request.getHeader("x-forwarded-for"); - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getHeader("WL-Proxy-Client-IP"); - } - if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { - ipAddress = request.getRemoteAddr(); - if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) { - InetAddress inet = null; - try { - inet = InetAddress.getLocalHost(); - } catch (UnknownHostException e) { - e.printStackTrace(); - } - ipAddress = inet.getHostAddress(); - } - } - if (ipAddress != null && ipAddress.length() > 15) { - if (ipAddress.indexOf(",") > 0) { - ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); - } - } - return ipAddress; - } -} diff --git a/src/main/java/com/zhongzhi/utils/LocalstorageUtil.java b/src/main/java/com/zhongzhi/utils/LocalstorageUtil.java deleted file mode 100644 index 6b85360..0000000 --- a/src/main/java/com/zhongzhi/utils/LocalstorageUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.zhongzhi.utils; - -import org.springframework.web.bind.annotation.RestController; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -@RestController -public class LocalstorageUtil { - - private static final ThreadLocal local = ThreadLocal.withInitial(() -> null); - private static ConcurrentHashMap map = new ConcurrentHashMap<>(); - public static void setUser(Object obj, String type) { - Map map = new HashMap<>(); - map.put("user", obj); - map.put("type", type); - LocalstorageUtil.local.set(map); - } - - public static Map getMap() { - return (Map) LocalstorageUtil.local.get(); - } - - public static Object getUser() { - Map map = (Map) LocalstorageUtil.local.get(); - return map.get("user"); - } - - public static void remove() { - LocalstorageUtil.local.remove(); - } -} diff --git a/src/main/java/com/zhongzhi/utils/PDFUtil.java b/src/main/java/com/zhongzhi/utils/PDFUtil.java deleted file mode 100644 index 64a602c..0000000 --- a/src/main/java/com/zhongzhi/utils/PDFUtil.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.zhongzhi.utils; - -import com.itextpdf.text.*; -import com.itextpdf.text.pdf.BaseFont; -import com.itextpdf.text.pdf.PdfPTable; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; - -@Slf4j -@Component -public class PDFUtil { - - static BaseFont baseFont; - - { - try { - baseFont = BaseFont.createFont("https://zhongzhi-cms.oss-cn-shanghai.aliyuncs.com/STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void tableStyle(PdfPTable table, int[] cellsWidth) throws DocumentException { - table.setWidths(cellsWidth); - table.setWidthPercentage(100); - table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); - table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); - table.getDefaultCell().setFixedHeight(30); - table.getDefaultCell().setBackgroundColor(BaseColor.BLUE); - table.getDefaultCell().setPadding(0); - table.getDefaultCell().setBorderWidth(0); - } - - /** - * 流化下载 - * - * @param bytes - * @param filename - */ - public static void renderPdf(final byte[] bytes, final String filename, String type) { - ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); - HttpServletResponse response = servletRequestAttributes.getResponse(); - initResponseHeader(response, "application/" + type); - setFileDownloadHeader(response, filename, "." + type); - if (null != bytes) { - try { - response.getOutputStream().write(bytes); - response.getOutputStream().flush(); - } catch (IOException e) { - throw new IllegalArgumentException(e); - } - } - } - - /** - * 分析并设置contentType与headers. - */ - private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) { - // 分析headers参数 - String encoding = "utf-8"; - boolean noCache = true; - for (String header : headers) { - String headerName = StringUtils.substringBefore(header, ":"); - String headerValue = StringUtils.substringAfter(header, ":"); - if (StringUtils.equalsIgnoreCase(headerName, "utf-8")) { - encoding = headerValue; - } else if (StringUtils.equalsIgnoreCase(headerName, "no-cache")) { - noCache = Boolean.parseBoolean(headerValue); - } else { - throw new IllegalArgumentException(headerName + "不是一个合法的header类型"); - } - } - // 设置headers参数 - String fullContentType = contentType + ";charset=" + encoding; - response.setContentType(fullContentType); - if (noCache) { - // Http 1.0 header - response.setDateHeader("Expires", 0); - response.addHeader("Pragma", "no-cache"); - // Http 1.1 header - response.setHeader("Cache-Control", "no-cache"); - } - return response; - } - - /** - * 设置让浏览器弹出下载对话框的Header. - * - * @param - */ - public static void setFileDownloadHeader(HttpServletResponse response, String fileName, String fileType) { - try { - // 中文文件名支持 - String encodedfileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"); - response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + fileType + "\""); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/zhongzhi/utils/RandomUtil.java b/src/main/java/com/zhongzhi/utils/RandomUtil.java deleted file mode 100644 index 6e66556..0000000 --- a/src/main/java/com/zhongzhi/utils/RandomUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.zhongzhi.utils; - -import java.util.Date; -import java.util.Random; - -public class RandomUtil { - - public static int getCode() { - return (int) ((Math.random() * 9 + 1) * 100000); - } - - public static String randomPass(Integer count) { - StringBuffer stringBuffer = new StringBuffer(); - Random random = new Random(new Date().getTime()); - String flag = type[random.nextInt(type.length)]; - int length = count; - for (int i = 0; i < length; i++) { - switch (flag) { - case "word": - stringBuffer.append(word[random.nextInt(word.length)]); - break; - case "num": - stringBuffer.append(num[random.nextInt(num.length)]); - break; - case "symbol": - stringBuffer.append(symbol[random.nextInt(symbol.length)]); - break; - default: - break; - } - flag = type[random.nextInt(type.length)]; - } - return stringBuffer.toString(); - } - - public final static String[] type = { - "word", "num", "symbol" - }; - - public final static String[] word = { - "a", "b", "c", "d", "e", "f", "g", - "h", "j", "k", "m", "n", - "p", "q", "r", "s", "t", - "u", "v", "w", "x", "y", "z", - "A", "B", "C", "D", "E", "F", "G", - "H", "J", "K", "M", "N", - "P", "Q", "R", "S", "T", - "U", "V", "W", "X", "Y", "Z" - }; - - public final static String[] num = { - "1", "2", "3", "4", "5", "6", "7", "8", "9" - }; - - public final static String[] symbol = { - "!", "@", "#", "$", "%", "&" - }; -} diff --git a/src/main/java/com/zhongzhi/utils/VodUtil.java b/src/main/java/com/zhongzhi/utils/VodUtil.java deleted file mode 100644 index d20532a..0000000 --- a/src/main/java/com/zhongzhi/utils/VodUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.zhongzhi.utils; - -import com.tencentcloudapi.common.Credential; -import com.tencentcloudapi.common.exception.TencentCloudSDKException; -import com.tencentcloudapi.common.profile.ClientProfile; -import com.tencentcloudapi.common.profile.HttpProfile; -import com.tencentcloudapi.vod.v20180717.VodClient; -import com.tencentcloudapi.vod.v20180717.models.*; -import com.zhongzhi.common.configure.VODConfig; -import com.zhongzhi.common.exception.HttpException; -import org.springframework.stereotype.Component; - -/** - *

- * 腾讯云 - 云点播API - *

- * - * @author DengMin - * @since 2022/8/1 - */ -@Component -public class VodUtil { - - private static String endpoint = "vod.tencentcloudapi.com"; - - /** - * 根据视频模版进行转码 - * @param vodCode - * @return - */ - public static ProcessMediaResponse processMedia(VODConfig vodConfig, String vodCode) { - try { - //上传后直接转码 - Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey()); - HttpProfile httpProfile = new HttpProfile(); - httpProfile.setEndpoint(endpoint); - - ClientProfile clientProfile = new ClientProfile(); - clientProfile.setHttpProfile(httpProfile); - - VodClient client = new VodClient(cred, "", clientProfile); - - ProcessMediaRequest processMediaRequest = new ProcessMediaRequest(); - MediaProcessTaskInput mediaProcessTaskInput1 = new MediaProcessTaskInput(); - TranscodeTaskInput[] transcodeTaskInputs1 = new TranscodeTaskInput[1]; - TranscodeTaskInput transcodeTaskInput1 = new TranscodeTaskInput(); - transcodeTaskInput1.setDefinition(100030L); - transcodeTaskInputs1[0] = transcodeTaskInput1; - mediaProcessTaskInput1.setTranscodeTaskSet(transcodeTaskInputs1); - processMediaRequest.setMediaProcessTask(mediaProcessTaskInput1); - processMediaRequest.setFileId(vodCode); - return client.ProcessMedia(processMediaRequest); - } catch (Exception ex) { - throw new HttpException(50001); - } - } - - /** - * 删除腾讯云上原视频 - * @param vodCode - */ - public static void deleteMedia(VODConfig vodConfig, String vodCode) { - try { - //删除原视频 - Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey()); - HttpProfile httpProfile = new HttpProfile(); - httpProfile.setEndpoint(endpoint); - - ClientProfile clientProfile = new ClientProfile(); - clientProfile.setHttpProfile(httpProfile); - - VodClient client = new VodClient(cred, "", clientProfile); - // 实例化一个请求对象,每个接口都会对应一个request对象 - DeleteMediaRequest req = new DeleteMediaRequest(); - req.setFileId(vodCode); - // 返回的resp是一个DeleteMediaResponse的实例,与请求对象对应 - client.DeleteMedia(req); - } catch (TencentCloudSDKException e) { - throw new HttpException(99999, e.getMessage()); - } - } - - /** - * 云点播域名的CDN统计数据 - * @param vodConfig - * @param DataType - * @param startTime - * @param endTime - * @return - */ - public static StatDataItem[] DescribeCDNStatDetails(VODConfig vodConfig, String DataType, String startTime, String endTime) { - try { - Credential cred = new Credential(vodConfig.getSecretId(), vodConfig.getSecretKey()); - // 实例化一个http选项,可选的,没有特殊需求可以跳过 - HttpProfile httpProfile = new HttpProfile(); - httpProfile.setEndpoint(endpoint); - // 实例化一个client选项,可选的,没有特殊需求可以跳过 - ClientProfile clientProfile = new ClientProfile(); - clientProfile.setHttpProfile(httpProfile); - // 实例化要请求产品的client对象,clientProfile是可选的 - VodClient client = new VodClient(cred, "", clientProfile); - // 实例化一个请求对象,每个接口都会对应一个request对象 - DescribeCDNUsageDataRequest req = new DescribeCDNUsageDataRequest(); - req.setStartTime(startTime); - req.setEndTime(endTime); - req.setDataType(DataType); - // 返回的resp是一个DescribeCDNUsageDataResponse的实例,与请求对象对应 - DescribeCDNUsageDataResponse resp = client.DescribeCDNUsageData(req); - // 返回的resp是一个DescribeCDNStatDetailsResponse的实例,与请求对象对应 - return resp.getData(); - } catch (TencentCloudSDKException e) { - e.printStackTrace(); - throw new HttpException(99999, e.getMessage()); - } - } -} diff --git a/src/main/java/com/zhongzhi/vo/ExcelFieldVO.java b/src/main/java/com/zhongzhi/vo/ExcelFieldVO.java deleted file mode 100644 index bea28df..0000000 --- a/src/main/java/com/zhongzhi/vo/ExcelFieldVO.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.zhongzhi.vo; - -import lombok.Data; - -@Data -public class ExcelFieldVO { - - private String field; - - private String name; -} diff --git a/src/main/java/com/zhongzhi/vo/ResponseData.java b/src/main/java/com/zhongzhi/vo/ResponseData.java deleted file mode 100644 index d67f865..0000000 --- a/src/main/java/com/zhongzhi/vo/ResponseData.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.zhongzhi.vo; - -import com.zhongzhi.common.configure.RemoteProperties; -import com.zhongzhi.vo.ResponseVO; -import lombok.Data; -import org.springframework.boot.context.properties.EnableConfigurationProperties; - -/** - * 返回数据 - * - * @author DengMin - * @date 2019/08/27 13:57 - **/ -@Data -@EnableConfigurationProperties(RemoteProperties.class) -public class ResponseData { - - public static ResponseVO generateCreatedResponse(int code) { - return (ResponseVO) ResponseVO.builder() - .code(code) - .message(RemoteProperties.getMessage(code)) - .build(); - } - - public static ResponseVO generateCreatedResponse(int code, String message) { - return (ResponseVO) ResponseVO.builder() - .code(code) - .message(message) - .build(); - } - - public static ResponseVO generateCreatedResponse(int code, T data) { - return (ResponseVO) ResponseVO.builder() - .code(code) - .message(RemoteProperties.getMessage(code)) - .data(data) - .build(); - } - - public static ResponseVO generateCreatedResponse(int code, String message, T data) { - return (ResponseVO) ResponseVO.builder() - .code(code) - .message(message) - .data(data) - .build(); - } - - public static ResponseVO generateCreatedResponse(int code, String message, String path) { - return (ResponseVO) ResponseVO.builder() - .code(code) - .message(message) - .path(path) - .build(); - } -} \ No newline at end of file diff --git a/src/main/java/com/zhongzhi/vo/ResponseVO.java b/src/main/java/com/zhongzhi/vo/ResponseVO.java deleted file mode 100644 index 6cbadd0..0000000 --- a/src/main/java/com/zhongzhi/vo/ResponseVO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.zhongzhi.vo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@Builder -@AllArgsConstructor -@NoArgsConstructor -public class ResponseVO { - - private Integer code; - - private String message; - - private T data; - - private String path; -} diff --git a/src/main/java/com/zhongzhi/vo/oss/GetSecretVO.java b/src/main/java/com/zhongzhi/vo/oss/GetSecretVO.java deleted file mode 100644 index 686f8f3..0000000 --- a/src/main/java/com/zhongzhi/vo/oss/GetSecretVO.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.zhongzhi.vo.oss; - -import lombok.Data; - -@Data -public class GetSecretVO { - - private String key; - - private String secret; - - -} diff --git a/src/main/java/com/zhongzhi/vo/oss/UploadFileVO.java b/src/main/java/com/zhongzhi/vo/oss/UploadFileVO.java deleted file mode 100644 index 92715f1..0000000 --- a/src/main/java/com/zhongzhi/vo/oss/UploadFileVO.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.zhongzhi.vo.oss; - -import lombok.Data; - -@Data -public class UploadFileVO { - - private String url; - - private String requestId; - -} diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index 7bf4c9e..d023418 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -47,7 +47,7 @@ - + @@ -56,7 +56,7 @@ - + @@ -65,7 +65,7 @@ - + -- libgit2 0.25.0