框架搭建

bugfix/ai-assessment-evidence-rescore
whb 2 years ago
parent 8e531df3de
commit c575868e6c

@ -1,21 +0,0 @@
package com.sztzjy.trade;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@Configuration
@MapperScan(basePackages = "com.sztzjy.trade.mapper")
@EnableScheduling
@Slf4j
public class LinkCommerceApplication {
public static void main(String[] args) {
SpringApplication.run(LinkCommerceApplication.class, args);
}
}

@ -1,16 +0,0 @@
package com.sztzjy.trade.annotation;
import java.lang.annotation.*;
/**
* 用于匿名访问配置, 使用时只需在Controller方法上使用此注解即能实现匿名访问
*
* @author 陈沅
*/
@Inherited
@Documented
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnonymousAccess {
}

@ -1,16 +0,0 @@
package com.sztzjy.trade.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 导入Excel数据进行校验的注解
* @author 17803
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelValid {
String message() default "导入有未填入的字段";
}

@ -1,27 +0,0 @@
package com.sztzjy.trade.annotation;
import java.lang.annotation.*;
/**
* 系统日志
*
*
* 2023年6月21日
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperateLog {
/**
* 记录参数
*
* @return 是否记录参数
*/
boolean recordParameters() default true;
/**
* 接口描述
* @return 操作描述
*/
String description() default "";
}

@ -1,29 +0,0 @@
package com.sztzjy.trade.annotation;
import com.sztzjy.trade.annotation.aspect.PermissionType;
import java.lang.annotation.*;
/**
* 权限切面控制
* 标识符
* @author 陈沅
*
* 2023年6月30日
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Permission {
/**
* 默认授权限制类型:MANAGER
* 设置多值列如:{o1,02}
* 多值表示或者的关系,既只需满足其中一个角色,即可授权
* @return string
*/
String[] codes() default {PermissionType.TERMINAL_MANAGEMENT};
}

@ -1,26 +0,0 @@
package com.sztzjy.trade.annotation.aspect;
/**
* 系统权限静态资源配置
* author:陈沅
*/
public class PermissionType {
public final static String DATA_STATISTICS = "DATA_STATISTICS";
public final static String QUOTATION_TRADING = "QUOTATION_TRADING";
public final static String TERMINAL_MANAGEMENT = "TERMINAL_MANAGEMENT";
public final static String TRADING = "TRADING";
public final static String TRAINING_MANAGEMENT = "TRAINING_MANAGEMENT";
public final static String TRAINING_MANAGEMENT_ADD = "TRAINING_MANAGEMENT_ADD";
public final static String TRAINING_MANAGEMENT_DEL = "TRAINING_MANAGEMENT_DEL";
public final static String TRAINING_MANAGEMENT_EDIT = "TRAINING_MANAGEMENT_EDIT";
public final static String TRAINING_MANAGEMENT_SEARCH = "TRAINING_MANAGEMENT_SEARCH";
public final static String TRAINING_PLAN_MANAGEMENT = "TRAINING_PLAN_MANAGEMENT";
public final static String TRAINING_PLAN_MANAGEMENT_ADD = "TRAINING_PLAN_MANAGEMENT_ADD";
public final static String TRAINING_PLAN_MANAGEMENT_DEL = "TRAINING_PLAN_MANAGEMENT_DEL";
public final static String TRAINING_PLAN_MANAGEMENT_EDIT = "TRAINING_PLAN_MANAGEMENT_EDIT";
public final static String TRAINING_PLAN_MANAGEMENT_SEARCH = "TRAINING_PLAN_MANAGEMENT_SEARCH";
}

@ -1,61 +0,0 @@
package com.sztzjy.trade.config;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* 常量定义
*/
@Component
public class Constant {
/**
* 请求头
*/
public static final String AUTHORIZATION = "Authorization";
/**
* Basic 请求头
*/
public static final String BASIC = "Basic";
public static final String[] MODULES={"数字贸易概论","数字贸易标准和规则","数字贸易法律法规","数字贸易知识产权保护","数字贸易技术","数字产品物流","数字贸易金融",
"数字产品贸易","数字技术贸易","数字服务贸易","数据贸易","数字贸易营销","aigc数字运营"};
public static final String[] PROJECTS={"项目一","项目二","项目三","项目四","项目五","项目六","项目七",
"项目八","项目九","项目十","项目十","项目十二","项目十三"};
public static final String PRO_XXSC="学习时长";
public static final String PRO_ZYXX="资源学习";
public static final String PRO_XXCP="学习测评";
public static final String PRO_SYSX="实验实训";
public static final String PRO_SXBG="实训报告";
public static final String DANDUGOUMAI = "单独购买";
public static final String PINDUANGOUMAI = "我要开团";
public static final String COMMENT_NUMBER="评论数";
public static final String BROWSE_NUMBER="被浏览数";
public static final String ZSGY_TCHMODULE = "学习时长";
public static final String ZYXX_TCHMODULE = "资源学习";
public static final String XXCP_TCHMODULE = "学习测评";
public static final String SYSX_TCHMODULE = "实验实训";
public static final String SYBG_TCHMODULE = "实验报告";
public static final String PRO_XXMB="学习目标";
public static final String PRO_LLZS="理论知识";
public static final String PRO_RWZJ="任务总结";
public static final String PRO_KHTS="课后提升";
public static final String CODE = "code";
public static final String IP = "ip";
public static final String END = "END";
public static final String READY = "READY";
public static final String MANUAL = "manual";
}

@ -1,19 +0,0 @@
package com.sztzjy.trade.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.Date;
/**
* 自定义日期序列化工具 Date -> Long
* 使用方法:通过在实体字段或get方法上使用注解 @JsonSerialize(using = DateToLongSerialized.class) 进行转换输出
*/
public class DateToLongSerialized extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(date.getTime());
}
}

@ -1,14 +0,0 @@
package com.sztzjy.trade.config;
import org.springframework.context.ApplicationEvent;
/**
* 系统日志事件捕获
*
*/
public class LogRecordEvent extends ApplicationEvent {
private static final long serialVersionUID = -7520983571492156143L;
public LogRecordEvent(Object source) {
super(source);
}
}

@ -1,79 +0,0 @@
package com.sztzjy.trade.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext属性未注入, 请在applicationContext" +
".xml中定义SpringContextHolder或在SpringBoot启动类中注册SpringContextHolder.");
}
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
private static void clearHolder() {
log.debug("清除SpringContextHolder中的ApplicationContext:"
+ applicationContext);
applicationContext = null;
}
@Override
public void destroy(){
SpringContextHolder.clearHolder();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextHolder.applicationContext != null) {
log.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
}
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 发布事件
*
* @param event
*/
public static void publishEvent(ApplicationEvent event) {
if (applicationContext == null) {
return;
}
applicationContext.publishEvent(event);
}
}

@ -1,41 +0,0 @@
package com.sztzjy.trade.config.exception;
/**
* 当用户访问受保护资源但不提供任何凭据时将抛出此异常
*
* @author 陈沅
* @version 1.0.0
*/
public class UnAuthorizedException extends RuntimeException {
/**
* Constructs a new runtime exception with the specified detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public UnAuthorizedException(String message) {
super(message);
}
/**
* Constructs a new runtime exception with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this runtime exception's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public UnAuthorizedException(String message, Throwable cause) {
super(message, cause);
}
}

@ -1,32 +0,0 @@
package com.sztzjy.trade.config.exception.handler;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* 权限不足异常拦截
* 当用户在没有授权的情况下访问受保护的REST资源时,将调用此方法发送403 Forbidden响应
*
* @author 陈沅
*/
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpStatus.FORBIDDEN.value());
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Content-Type", "application/json");
PrintWriter printWriter = response.getWriter();
printWriter.write("{\"code\":" + HttpStatus.FORBIDDEN.value() + ", \"msg\": \"权限不足\"}");
printWriter.flush();
}
}

@ -1,39 +0,0 @@
package com.sztzjy.trade.config.exception.handler;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* token异常拦截
* 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
*
* @author 陈沅
*/
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
// 当用户尝试访问安全的REST资源而不提供任何凭据时,将调用此方法发送401 响应
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
// response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Content-Type", "application/json");
Throwable cause = authException.getCause();
PrintWriter printWriter = response.getWriter();
if (cause instanceof InvalidTokenException) {
printWriter.write("{\"code\":" + HttpStatus.UNAUTHORIZED.value() + ",\"msg\":\"身份认证失败,无效或过期token\"}");
} else {
printWriter.write("{\"code\":" + HttpStatus.UNAUTHORIZED.value() + ",\"msg\":\"身份认证失败\"}");
}
printWriter.flush();
}
}

@ -1,37 +0,0 @@
package com.sztzjy.trade.config.exception.handler;
import org.springframework.http.HttpStatus;
public class DigitalEconomyxception extends RuntimeException {
private HttpStatus code;
private String msg;
public DigitalEconomyxception() {
}
public DigitalEconomyxception(HttpStatus code) {
this.code = code;
}
public DigitalEconomyxception(HttpStatus code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public HttpStatus getCode() {
return code;
}
public void setCode(HttpStatus code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -1,79 +0,0 @@
package com.sztzjy.trade.config.exception.handler;
import com.sztzjy.trade.config.exception.UnAuthorizedException;
import com.sztzjy.trade.util.ResultEntity;
import com.sztzjy.trade.util.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResultEntity<String> illegalArgumentException(IllegalArgumentException e) {
log.error(ThrowableUtil.getStackTrace(e));
return new ResultEntity<>(HttpStatus.BAD_REQUEST, e.getMessage());
}
@ExceptionHandler(AccessDeniedException.class)
public ResultEntity<String> accessDeniedException(AccessDeniedException e) {
log.error(ThrowableUtil.getStackTrace(e));
return new ResultEntity<>(HttpStatus.FORBIDDEN, e.getMessage());
}
@ExceptionHandler(UnAuthorizedException.class)
public ResultEntity<String> UnAuthorizedException(UnAuthorizedException e) {
log.error(ThrowableUtil.getStackTrace(e));
return new ResultEntity<>(HttpStatus.UNAUTHORIZED, e.getMessage());
}
/**
* 处理所有接口数据验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultEntity<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error(ThrowableUtil.getStackTrace(e));
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
String message = objectError.getDefaultMessage();
if (objectError instanceof FieldError) {
message = ((FieldError) objectError).getField() + ": " + message;
}
return new ResultEntity<>(HttpStatus.BAD_REQUEST, message);
}
/**
* 处理所有不可知的异常
*
* @param e 未知异常
* @return /
*/
@ExceptionHandler(Throwable.class)
public ResultEntity<String> nullPointerException(Throwable e) {
log.error(ThrowableUtil.getStackTrace(e));
return new ResultEntity<>(HttpStatus.BAD_REQUEST, e.getMessage());
}
/**
* BadCredentialsException
*/
@ExceptionHandler(BadCredentialsException.class)
public ResultEntity<String> badCredentialsException(BadCredentialsException e) {
// 打印堆栈信息
String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage();
log.error(message);
return new ResultEntity<>(HttpStatus.BAD_REQUEST, message);
}
}

@ -1,37 +0,0 @@
package com.sztzjy.trade.config.exception.handler;
import org.springframework.http.HttpStatus;
public class InvoceTException extends RuntimeException {
private HttpStatus code;
private String msg;
public InvoceTException() {
}
public InvoceTException(HttpStatus code) {
this.code = code;
}
public InvoceTException(HttpStatus code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public HttpStatus getCode() {
return code;
}
public void setCode(HttpStatus code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -1,37 +0,0 @@
package com.sztzjy.trade.config.exception.handler;
import org.springframework.http.HttpStatus;
public class ServiceException extends RuntimeException {
private HttpStatus code;
private String msg;
public ServiceException() {
}
public ServiceException(HttpStatus code) {
this.code = code;
}
public ServiceException(HttpStatus code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public HttpStatus getCode() {
return code;
}
public void setCode(HttpStatus code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -1,41 +0,0 @@
package com.sztzjy.trade.config.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> template(RedisConnectionFactory factory) {
// 创建RedisTemplate<String, Object>对象
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
// 定义Jackson2JsonRedisSerializer序列化对象
Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会报异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
StringRedisSerializer stringSerial = new StringRedisSerializer();
// redis key 序列化方式使用stringSerial
template.setKeySerializer(stringSerial);
// redis value 序列化方式使用jackson
template.setValueSerializer(jacksonSeial);
// redis hash key 序列化方式使用stringSerial
template.setHashKeySerializer(stringSerial);
// redis hash value 序列化方式使用jackson
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
}

@ -1,142 +0,0 @@
package com.sztzjy.trade.config.security;
import cn.hutool.extra.servlet.ServletUtil;
import com.sztzjy.trade.config.Constant;
import com.sztzjy.trade.config.exception.UnAuthorizedException;
import com.sztzjy.trade.config.redis.RedisConfig;
import com.sztzjy.trade.util.RedisUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SignatureException;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
/**
* 系统登陆认证拦截
*
* @author 陈沅
*/
@Configuration
public class AuthenticationFilter extends OncePerRequestFilter {
private final PathMatcher matcher = new AntPathMatcher();
// private final RedisUtil redisUtil;
//
//
// @Autowired
// public AuthenticationFilter(RedisUtil redisUtil) {
// this.redisUtil = redisUtil;
//
// }
private final TokenProvider tokenProvider;
public AuthenticationFilter(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String requestRri = request.getRequestURI();
if (requestRri.equals("/")) {
response.sendRedirect("/doc.html");
return;
}
if (!isExclude(request)) {
System.out.println("--------------------------------->>> " + LocalDateTime.now() + " ---ip:" + ServletUtil.getClientIP(request) + " requestUri:" + requestRri);
}
String token = request.getHeader(Constant.AUTHORIZATION);
if (token == null || token.equals("undefined") || token.equals("") || token.equals("null")) {
filterChain.doFilter(request, response);
response.setHeader("Access-Control-Allow-Origin","*");
return;
}
if (!StringUtils.startsWithIgnoreCase(token, "Bearer ")) {
throw new UnAuthorizedException("令牌错误: 缺失Bearer..");
}
JwtUser currentUser;
try {
currentUser = tokenProvider.getJWTUser(token);
response.setCharacterEncoding("UTF-8");
} catch (ExpiredJwtException e1) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().print("Token已过期");
return;
} catch (UnsupportedJwtException e2) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().print("不支持的Token");
return;
} catch (MalformedJwtException e3) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().print("无效的Token格式");
return;
} catch (SignatureException e4) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().print("无效的Token签名");
return;
} catch (Exception e5) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().print("无效的Token");
return;
}
Authentication authentication = new UsernamePasswordAuthenticationToken(currentUser, token == null ? "****" : token, currentUser.getAuthorities());
// request.getUserPrincipal();
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}
/**
* 排除的请求路径匹配
*/
private final static List<String> patterns = Arrays.asList(
"/swagger-resources/**",
"/doc.html",
"/webjars/**",
"/v2/**",
"/favicon.ico",
"/login",
"/druid/**"
);
/**
* 判断请求路径是否是在排除之外
*
* @param request /
* @return true-是排除的
*/
private boolean isExclude(HttpServletRequest request) {
String requestURI = request.getRequestURI();
for (String pattern : patterns) {
if (matcher.match(pattern, requestURI)) {
return true;
}
}
return false;
}
}

@ -1,59 +0,0 @@
package com.sztzjy.trade.config.security;
import cn.hutool.system.UserInfo;
import com.sztzjy.trade.entity.StuUser;
import com.sztzjy.trade.entity.StuUserExample;
import com.sztzjy.trade.mapper.StuUserMapper;
import io.jsonwebtoken.lang.Assert;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class AuthenticationService implements UserDetailsService {
@Resource
private StuUserMapper stuUserMapper;
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// StuUserExample stuUserExample = new StuUserExample();
// stuUserExample.createCriteria().andStudentIdEqualTo(username);
// List<StuUser> list = stuUserMapper.selectByExample(stuUserExample);
// Assert.notNull(list, "用户不存在");
// StuUser user = list.get(0);
// JwtUser jwtUser = new JwtUser();
// jwtUser.setUsername(user.getStudentId());
// jwtUser.setPassword(new BCryptPasswordEncoder().encode(user.getPassword())); //不加密会报错Encoded password does not look like BCrypt
// jwtUser.setUserId(user.getUserId());
// jwtUser.setName(user.getName());
// jwtUser.setRoleId(user.getRoleId());
// jwtUser.setStudentId(user.getStudentId());
// return jwtUser;
// }
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
StuUserExample stuUserExample = new StuUserExample();
stuUserExample.createCriteria().andStudentIdEqualTo(username);
List<StuUser> list = stuUserMapper.selectByExample(stuUserExample);
Assert.notNull(list, "用户不存在");
StuUser user = list.get(0);
JwtUser jwtUser = new JwtUser();
jwtUser.setUsername(user.getStudentId());
jwtUser.setPassword(new BCryptPasswordEncoder().encode(user.getPassword())); //不加密会报错Encoded password does not look like BCrypt
jwtUser.setUserId(user.getUserId());
jwtUser.setName(user.getName());
jwtUser.setRoleId(user.getRoleId());
jwtUser.setStudentId(user.getStudentId());
return jwtUser;
}
}

@ -1,151 +0,0 @@
package com.sztzjy.trade.config.security;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.session.*;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* 自定义session管理
* 该方法创建是为解决同一个用户在同一台电脑调同一个接口SessionRegistryImpl的registerNewSession会生成不同的会话id(相当于一个用户在缓存中有好几个会话id)
* 故重构该方法便于后台管理sessionId
*
* @author 陈沅
* @date 2023/07/06 22:27:47
*/
@Component
public class CustomSessionRegistry implements SessionRegistry {
protected final Log logger = LogFactory.getLog(CustomSessionRegistry.class);
private final ConcurrentMap<Object, Set<String>> principals;
private final Map<String, SessionInformation> sessionIds;
public CustomSessionRegistry() {
this.principals = new ConcurrentHashMap();
this.sessionIds = new ConcurrentHashMap();
}
public CustomSessionRegistry(ConcurrentMap<Object, Set<String>> principals, Map<String, SessionInformation> sessionIds) {
this.principals = principals;
this.sessionIds = sessionIds;
}
public List<Object> getAllPrincipals() {
return new ArrayList(this.principals.keySet());
}
public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) {
Set<String> sessionsUsedByPrincipal = (Set)this.principals.get(principal);
if (sessionsUsedByPrincipal == null) {
return Collections.emptyList();
} else {
List<SessionInformation> list = new ArrayList(sessionsUsedByPrincipal.size());
Iterator var5 = sessionsUsedByPrincipal.iterator();
while(true) {
SessionInformation sessionInformation;
do {
do {
if (!var5.hasNext()) {
return list;
}
String sessionId = (String)var5.next();
sessionInformation = this.getSessionInformation(sessionId);
} while(sessionInformation == null);
} while(!includeExpiredSessions && sessionInformation.isExpired());
list.add(sessionInformation);
}
}
}
public SessionInformation getSessionInformation(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
return (SessionInformation)this.sessionIds.get(sessionId);
}
public void onApplicationEvent(AbstractSessionEvent event) {
String oldSessionId;
if (event instanceof SessionDestroyedEvent) {
SessionDestroyedEvent sessionDestroyedEvent = (SessionDestroyedEvent)event;
oldSessionId = sessionDestroyedEvent.getId();
this.removeSessionInformation(oldSessionId);
} else if (event instanceof SessionIdChangedEvent) {
SessionIdChangedEvent sessionIdChangedEvent = (SessionIdChangedEvent)event;
oldSessionId = sessionIdChangedEvent.getOldSessionId();
if (this.sessionIds.containsKey(oldSessionId)) {
Object principal = ((SessionInformation)this.sessionIds.get(oldSessionId)).getPrincipal();
this.removeSessionInformation(oldSessionId);
this.registerNewSession(sessionIdChangedEvent.getNewSessionId(), principal);
}
}
}
public void refreshLastRequest(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
SessionInformation info = this.getSessionInformation(sessionId);
if (info != null) {
info.refreshLastRequest();
}
}
public void registerNewSession(String sessionId, Object principal) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
Assert.notNull(principal, "Principal required as per interface contract");
if(principal instanceof JwtUser){
sessionId = ((JwtUser) principal).getUsername();
}
if (this.getSessionInformation(sessionId) != null) {
this.removeSessionInformation(sessionId);
}
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format("Registering session %s, for principal %s", sessionId, principal));
}
this.sessionIds.put(sessionId, new SessionInformation(principal, sessionId, new Date()));
String finalSessionId = sessionId;
this.principals.compute(principal, (key, sessionsUsedByPrincipal) -> {
if (sessionsUsedByPrincipal == null) {
sessionsUsedByPrincipal = new CopyOnWriteArraySet();
}
((Set)sessionsUsedByPrincipal).add(finalSessionId);
this.logger.trace(LogMessage.format("Sessions used by '%s' : %s", principal, sessionsUsedByPrincipal));
return (Set)sessionsUsedByPrincipal;
});
}
public void removeSessionInformation(String sessionId) {
Assert.hasText(sessionId, "SessionId required as per interface contract");
SessionInformation info = this.getSessionInformation(sessionId);
if (info != null) {
if (this.logger.isTraceEnabled()) {
this.logger.debug("Removing session " + sessionId + " from set of registered sessions");
}
this.sessionIds.remove(sessionId);
this.principals.computeIfPresent(info.getPrincipal(), (key, sessionsUsedByPrincipal) -> {
this.logger.debug(LogMessage.format("Removing session %s from principal's set of registered sessions", sessionId));
sessionsUsedByPrincipal.remove(sessionId);
if (sessionsUsedByPrincipal.isEmpty()) {
this.logger.debug(LogMessage.format("Removing principal %s from registry", info.getPrincipal()));
sessionsUsedByPrincipal = null;
}
this.logger.trace(LogMessage.format("Sessions used by '%s' : %s", info.getPrincipal(), sessionsUsedByPrincipal));
return sessionsUsedByPrincipal;
});
}
}
}

@ -1,72 +0,0 @@
package com.sztzjy.trade.config.security;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* jwt用户对象
*/
@Getter
@Setter
public class JwtUser implements UserDetails {
private String username;
private String studentId;
private String password;
private String name;
private String userId;
private int roleId;
private Integer schoolId;
private int classId;
private String schoolName;
private String className;
private int majorId;
private String majorName;
private int collegeId;
private String collegeName;
private List<String> authorityCodes;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof JwtUser)) return false;
JwtUser user = (JwtUser) o;
return username.equals(user.username);
}
@Override
public int hashCode() {
return Objects.hash(username);
}
}

@ -1,108 +0,0 @@
package com.sztzjy.trade.config.security;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* 用户登录结果集
*
* @author 陈沅
*/
@ApiModel("用户登录结果集")
@Setter
@Getter
public class LoginResult {
@ApiModelProperty("用户ID")
private String userId;
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("访问令牌")
private String accessToken;
@ApiModelProperty("角色Id")
private int roleId;
@ApiModelProperty("用户所在班级id")
private int classId;
@ApiModelProperty("用户所在学校id")
private int schoolId;
@ApiModelProperty("用户所在学校名称")
private String schoolName;
@ApiModelProperty("用户权限")
private List<String> authorityCodes;
@ApiModelProperty("用户所在院系")
private int collegeId;
@ApiModelProperty("用户所在专业")
private int majorId;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("studentId")
private String studentId;
// user.setUserId(dataObject.getStr("userId"));
// user.setName(dataObject.getStr("name"));
// user.setRoleId(dataObject.getInt("roleId"));
// user.setSchoolId(dataObject.getInt("schoolId"));
// user.setClassId(dataObject.getInt("classId"));
// user.setMajorId(dataObject.getInt("majorId"));
// user.setClassName(dataObject.getStr("className"));
// user.setMajorName(dataObject.getStr("majorName"));
// user.setSchoolName(dataObject.getStr("schoolName"));
// user.setCollegeId(dataObject.getInt("collegeId"));
// user.setCollegeName(dataObject.getStr("collegeName"));
/**
* 创建登录成功实体
*
* @param jwtUser 授权用户实体
* @param accessToken 令牌
* @return LoginResult
*/
public static LoginResult create(JwtUser jwtUser, String accessToken) {
LoginResult result = new LoginResult();
result.setUserId(jwtUser.getUserId());
result.setRoleId(jwtUser.getRoleId());
result.setName(jwtUser.getName());
result.setAccessToken(accessToken);
result.setClassId(jwtUser.getClassId());
result.setSchoolId(jwtUser.getSchoolId());
result.setAuthorityCodes(jwtUser.getAuthorityCodes());
result.setMajorId(jwtUser.getMajorId());
result.setCollegeId(jwtUser.getCollegeId());
result.setUsername(jwtUser.getUsername());
result.setSchoolName(jwtUser.getSchoolName());
result.setStudentId(jwtUser.getUsername());
return result;
}
// /**
// * 创建登录成功实体
// *
// * @param jwtUser 授权用户实体
// * @param accessToken 令牌
// * @return LoginResult
// */
// public static LoginResult create(JwtUser jwtUser, String accessToken) {
// LoginResult result = new LoginResult();
// result.setUserId(jwtUser.getUserId());
// result.setRoleId(jwtUser.getRoleId());
// result.setName(jwtUser.getName());
// result.setAccessToken(accessToken);
// result.setClassId(jwtUser.getClassId());
// result.setSchoolId(jwtUser.getSchoolId());
// result.setAuthorityCodes(jwtUser.getAuthorityCodes());
// result.setMajorId(jwtUser.getMajorId());
// result.setCollegeId(jwtUser.getCollegeId());
// result.setUsername(jwtUser.getUsername());
// result.setSchoolName(jwtUser.getSchoolName());
// return result;
// }
}

@ -1,290 +0,0 @@
package com.sztzjy.trade.config.security;
import com.sztzjy.trade.config.Constant;
import com.sztzjy.trade.config.exception.UnAuthorizedException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Date;
import java.util.List;
@Component
public class TokenProvider {
private final static String SECRET = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAghgsx+OLLThi7c+/HgCaRla8n+/QLHt++uscoK22dMeaVa3WJvRb5C5qtHGzj9V74pI96JpxdWWCN3Zr1QtanQIDAQABAkB2fWRUD1jVMBVS+rPctLnPNPMKTRdzXGv0SC5D3tRfGZqdcfsmZg8hzBVndHxngmwZS73d+hPjofcdefDDnXq1AiEAz/r1AMF7fweN70mbKgBJuTja37puJMsH2Szwrvb5jlcCIQCgIaLZ5d9J7OomL0NwH8ghba/xgBEpKzErfGbFnTfeKwIgc8ptczFFV1DWZb2eJIEqinOr79l0jwl2YiQSD+cyw1sCIHqxCvv1Wx5jPgy/zeYNE+Q5DMP3Ii7u/x+Yk436JiI9AiEAio84hFm44YTUuV7YCYsbyvnCn/vtcAaqZlczbeHlP1I=";
private final static long EXP_TIME = 1000 * 60 * 60 * 12;
private final static String SECRET_ZHIYUN = "zy_szmy_mnjy_fp76ckwuczzmb67w0a8x0";
private final static String CURRENT_TO_ZHIYUN = "jVzvfoZU_eFN0CJcFARg0K6DlzTLa7oMWB7lV_y2s7bkv2Bem0281wEwlJp5afhsmM-Ynwvh3mAUTpwblGEz1A";
/**
* 解析jwtToken
*
* @param jwtToken jwtToken
* @return jwt解析对象
*/
public static JwtUser getJWTUser(String jwtToken) {
jwtToken = jwtToken.replace("Bearer ", "");
try {
Claims claims = Jwts.parser()
.setSigningKey(
new SecretKeySpec(
SECRET.getBytes("UTF-8"),
SignatureAlgorithm.HS512.getJcaName()
)
)
.parseClaimsJws(jwtToken)
.getBody();
JwtUser jwtUser = new JwtUser();
jwtUser.setName(claims.get("name")==null?"":claims.get("name").toString());
jwtUser.setUserId(claims.get("userId")==null?"":claims.get("userId").toString());
if (claims.get("roleId")!=null){
jwtUser.setRoleId(Integer.valueOf(claims.get("roleId")==null?"0":claims.get("roleId").toString()));
}
if (claims.get("classId")!=null){
jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?"0":claims.get("classId").toString()));
}
if (claims.get("schoolId")!=null){
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
}
jwtUser.setUsername(claims.get("username")==null?"":claims.get("username").toString());
jwtUser.setAuthorityCodes((List<String>) claims.get("authorityCodes"));
return jwtUser;
} catch (ExpiredJwtException e1) {
throw new ExpiredJwtException(null, null, "token过期");
} catch (UnsupportedJwtException e2) {
throw new UnsupportedJwtException("不支持的token");
} catch (MalformedJwtException e3) {
throw new MalformedJwtException("token格式错误");
} catch (SignatureException e4) {
throw new SignatureException("签名失败");
} catch (Exception e) {
throw new UnAuthorizedException("无效token");
}
}
public static JwtUser getJWTUserOne(String jwtToken) {
jwtToken = jwtToken.replace("Bearer ", "");
try {
Claims claims = Jwts.parser()
.setSigningKey(
new SecretKeySpec(
SECRET.getBytes("UTF-8"),
SignatureAlgorithm.HS512.getJcaName()
)
)
.parseClaimsJws(jwtToken)
.getBody();
// JwtUser jwtUser = new JwtUser();
// jwtUser.setName(claims.get("name")==null?"":claims.get("name").toString());
// jwtUser.setUserId(claims.get("userId")==null?"":claims.get("userId").toString());
// jwtUser.setRoleId(Integer.valueOf(claims.get("roleId")==null?"0":claims.get("roleId").toString()));
// jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?"0":claims.get("classId").toString()));
// jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
// jwtUser.setUsername(claims.get("username")==null?"":claims.get("username").toString());
// jwtUser.setAuthorityCodes((List<String>) claims.get("authorityCodes"));
JwtUser jwtUser = new JwtUser();
jwtUser.setName(claims.get("name")==null?null:claims.get("name").toString());
jwtUser.setUserId(claims.get("userId")==null?null:claims.get("userId").toString());
if(claims.get("roleid")!=null){
jwtUser.setRoleId(Integer.valueOf(claims.get("roleid")==null?"4":claims.get("roleid").toString()));
}
if(claims.get("classId")!=null){
jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
}
//jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
if(claims.get("schoolId")!=null){
// jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
}
jwtUser.setUsername(claims.get("username")==null?null:claims.get("username").toString());
jwtUser.setClassName(claims.get("class")==null?null:claims.get("class").toString());
jwtUser.setStudentId(claims.get("studentNo")==null?null:claims.get("studentNo").toString());
jwtUser.setSchoolName(claims.get("school")==null?null:claims.get("school").toString());
jwtUser.setMajorName(claims.get("major")==null?null:claims.get("major").toString());
jwtUser.setPassword(claims.get("password")==null?"123qwe":claims.get("password").toString());
return jwtUser;
} catch (ExpiredJwtException e1) {
throw new ExpiredJwtException(null, null, "token过期");
} catch (UnsupportedJwtException e2) {
throw new UnsupportedJwtException("不支持的token");
} catch (MalformedJwtException e3) {
throw new MalformedJwtException("token格式错误");
} catch (SignatureException e4) {
throw new SignatureException("签名失败");
} catch (Exception e) {
throw new UnAuthorizedException("无效token");
}
}
public static String createToken(JwtUser jwtUser) {
Key key = Keys.hmacShaKeyFor(SECRET.getBytes());
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
return Jwts.builder()
.claim("userId", jwtUser.getUserId())
.claim("roleId", jwtUser.getRoleId())
.claim("name", jwtUser.getName())
.claim("classId", jwtUser.getClassId())
.claim("schoolId", jwtUser.getSchoolId())
.claim("username", jwtUser.getUsername())
.claim("authorityCodes", jwtUser.getAuthorityCodes())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expiration)
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
public static String createZHIYUNToken(JwtUser jwtUser) {
Key key = Keys.hmacShaKeyFor(CURRENT_TO_ZHIYUN.getBytes());
Date expiration = new Date(System.currentTimeMillis() + EXP_TIME);
return Jwts.builder()
.claim("userId", jwtUser.getUserId())
.claim("roleId", jwtUser.getRoleId())
.claim("name", jwtUser.getName())
.claim("classId", jwtUser.getClassId())
.claim("schoolId", jwtUser.getSchoolId())
.claim("username", jwtUser.getUsername())
.claim("majorId", jwtUser.getMajorId())
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(expiration)
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
/**
* 解析智云平台的token
*/
public static JwtUser getJWTUserByZhiYun(String token) {
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InR6czAwMSIsInVzZXJJZCI6" +
// "NDg3LCJuYW1lIjoi5Zev5ZO8IiwicGFzc3dvcmQiOiIxMjNxd2UiLCJyb2xlSWQiOjQsInNjaG9" +
// "vbElkIjoxLCJzY2hvb2xOYW1lIjoi5aSp5oup5aSn5a2mIi" +
// "wiY2xhc3NJZCI6MjAsImNsYXNzTmFtZSI6IuWkqeaLqea8lOekujHnj60iLCJsZXZlbElkIjo1fQ" +
// ".5fVdEtC7eDC2HuUX8jnodomdTUw_nPOzkOJUXCw5Fqc";
try {
Claims claims = Jwts.parser()
.setSigningKey(Keys.hmacShaKeyFor(SECRET_ZHIYUN.getBytes()))
.parseClaimsJws(token)
.getBody();
JwtUser jwtUser = new JwtUser();
jwtUser.setName(claims.get("name")==null?null:claims.get("name").toString());
jwtUser.setUserId(claims.get("userId")==null?null:claims.get("userId").toString());
if(claims.get("roleid")!=null){
jwtUser.setRoleId(Integer.valueOf(claims.get("roleid")==null?"4":claims.get("roleid").toString()));
}
if(claims.get("classId")!=null){
jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
}
//jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
if(claims.get("schoolId")!=null){
// jwtUser.setClassId(Integer.valueOf(claims.get("classId")==null?null:claims.get("classId").toString()));
jwtUser.setSchoolId(Integer.valueOf(claims.get("schoolId")==null?"0":claims.get("schoolId").toString()));
}
jwtUser.setUsername(claims.get("username")==null?null:claims.get("username").toString());
jwtUser.setClassName(claims.get("class")==null?null:claims.get("class").toString());
jwtUser.setStudentId(claims.get("studentNo")==null?null:claims.get("studentNo").toString());
jwtUser.setSchoolName(claims.get("school")==null?null:claims.get("school").toString());
jwtUser.setMajorName(claims.get("major")==null?null:claims.get("major").toString());
jwtUser.setPassword(claims.get("password")==null?"123qwe":claims.get("password").toString());
return jwtUser;
} catch (Exception e) {
throw new UnAuthorizedException("token解析失败");
}
}
//生成智云平台32字节密钥
public static void main(String[] args) {
// String prefix = "zy_wh_mnjy_";
// String generatedKey = generateKey(prefix);
// System.out.println("Generated Key: " + generatedKey);
// getJWTUserByZhiYun(null);
//生成一个新的长度为512字节的随机密钥供智云平台解析token
// int keyLength = 512; // 根据您的要求进行调整
// KeyGenerator keyGenerator;
// try {
// keyGenerator = KeyGenerator.getInstance("HmacSHA512");
// keyGenerator.init(keyLength);
// SecretKey secretKey = keyGenerator.generateKey();
// byte[] secretBytes = secretKey.getEncoded();
// String secret = Base64.getUrlEncoder().withoutPadding().encodeToString(secretBytes);
//
// System.out.println("Generated Secret: " + secret);
// } catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
// }
JwtUser user = new JwtUser();
user.setUserId("486");
user.setRoleId(3);
user.setUsername("tzt006");
user.setSchoolId(1);
user.setSchoolName("天择大学");
user.setCollegeId(1);
user.setCollegeName("演示学院");
user.setMajorId(1);
user.setMajorName("产品演示专业");
String token = createZHIYUNToken(user);
System.out.println(token);
}
public static String generateKey(String prefix) {
String characters = "0123456789abcdefghijklmnopqrstuvwxyz";
SecureRandom random = new SecureRandom();
StringBuilder keyBuilder = new StringBuilder(prefix);
while (keyBuilder.length() < 32) {
int randomIndex = random.nextInt(characters.length());
char randomChar = characters.charAt(randomIndex);
keyBuilder.append(randomChar);
}
return keyBuilder.toString();
}
/**
* 获取当前用户信息
*
* @param request request
* @return JwtUser
*/
public static JwtUser getJWTUser(HttpServletRequest request) {
if (!(request.getUserPrincipal() instanceof UsernamePasswordAuthenticationToken)) {
throw new UnAuthorizedException("身份认证失败");
}
String jwtToken = request.getHeader(Constant.AUTHORIZATION);
if (StringUtils.hasText(jwtToken)) {
return getJWTUser(jwtToken);
}
throw new UnAuthorizedException("身份认证失败");
}
}

@ -1,103 +0,0 @@
package com.sztzjy.trade.config.security;
import com.sztzjy.trade.util.file.IFileUtil;
import com.sztzjy.trade.util.file.LocalFileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
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.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* 系统配置
*/
@Configuration
@EnableWebMvc
public class WebConfigurerAdapter implements WebMvcConfigurer {
@Resource
private StringHttpMessageConverter stringHttpMessageConverter;
@Value("${file.type}")
private String fileType;
@Value("${file.path}")
private String filePath;
@Bean
@Primary
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10); // 设置核心线程数
executor.setMaxPoolSize(50); // 设置最大线程数
executor.setQueueCapacity(100); // 设置队列容量
executor.setThreadNamePrefix("async-executor-");
executor.initialize();
return executor;
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setTaskExecutor(asyncTaskExecutor());
configurer.setDefaultTimeout(30000); // 设置默认超时时间
}
@Bean
public IFileUtil getFileUtil() {
if (fileType.equals("local")) {
return new LocalFileUtil(filePath);
} else {
throw new IllegalArgumentException("未知文件工具类注入类型");
}
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// config.addAllowedOrigin("*");
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource reloadableResourceBundleMessageSource = new ReloadableResourceBundleMessageSource();
reloadableResourceBundleMessageSource.setBasename("classpath:messages");
return reloadableResourceBundleMessageSource;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (int i = 0; i < converters.size(); i++) {
if (converters.get(i) instanceof StringHttpMessageConverter) {
stringHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);
converters.set(i, stringHttpMessageConverter);
}
}
}
}

@ -1,133 +0,0 @@
package com.sztzjy.trade.config.security;
import com.sztzjy.trade.annotation.AnonymousAccess;
import com.sztzjy.trade.config.SpringContextHolder;
import com.sztzjy.trade.config.exception.handler.CustomAccessDeniedHandler;
import com.sztzjy.trade.config.exception.handler.CustomAuthenticationEntryPoint;
import com.sztzjy.trade.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* secret配置
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
private RedisUtil redisUtil;
@Value("${item.name}")
private String itemName;
@Resource
private TokenProvider tokenProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
RequestMappingHandlerMapping handlerMapping = SpringContextHolder.getBean("requestMappingHandlerMapping");
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
Set<String> anonymousUrls = discoveryAnonymousUrls(handlerMethods);
http
.sessionManagement(sessionManagement ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)// 不保存任何session 每次请求都需要携带token
.maximumSessions(1) //防止同一用户在多个地方同时登录
.sessionRegistry(sessionRegistry()) //可以控制会话的生命周期等。
)
// .addFilterBefore(new AuthenticationFilter(redisUtil), UsernamePasswordAuthenticationFilter.class) //自定义过滤链,认证流程中执行
.addFilterBefore(new AuthenticationFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class) //自定义过滤链,认证流程中执行
.cors().and() //启用跨域资源共享(CORS)支持
//在响应头中添加 Access-Control-Allow-Headers,允许浏览器的跨域请求中携带 Authorization 头部信息,这通常用于传递认证信息(如 JWT token)
.headers().addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers", "Authorization"))
.and()
// 禁用 CSRF
.csrf().disable()
.exceptionHandling()
//配置认证和授权失败的处理
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
.accessDeniedHandler(new CustomAccessDeniedHandler())
// 防止iframe 造成跨域
.and().headers().frameOptions().disable().and()
// 所有请求都需要认证
.authorizeRequests()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/doc.html").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/v2/**").permitAll()
.antMatchers("/test/**").permitAll()
.antMatchers("/druid/**").permitAll()
.antMatchers("/webSocket/**").permitAll()
.antMatchers(anonymousUrls.toArray(new String[]{})).permitAll()
.anyRequest().authenticated();
}
/**
* 认证相关的核心接口
*
* @return {@link AuthenticationManager}
* @throws Exception /
*/
@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
/**
* 根据注解发现需要匿名访问的请求路径
*
* @param handlerMethodMap ?
* @return 匿名Mapping patterns
*/
private Set<String> discoveryAnonymousUrls(Map<RequestMappingInfo, HandlerMethod> handlerMethodMap) {
Set<String> patterns = new HashSet<>();
for (Map.Entry<RequestMappingInfo, HandlerMethod> infoEntry : handlerMethodMap.entrySet()) {
HandlerMethod handlerMethod = infoEntry.getValue();
AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation(AnonymousAccess.class);
if (Objects.nonNull(anonymousAccess)) {
assert infoEntry.getKey().getPatternsCondition() != null;
patterns.addAll(infoEntry.getKey().getPatternsCondition().getPatterns());
}
}
return patterns;
}
@Bean
public SessionRegistry sessionRegistry() {
return new CustomSessionRegistry();
}
}

@ -1,104 +0,0 @@
package com.sztzjy.trade.config.swagger;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* swagger 3.0接口文档配置类
*
* @author 陈沅
*/
@EnableSwagger2
@Configuration
@Profile({"dev", "pro", "test"})
public class Swagger2Config implements ApplicationListener<WebServerInitializedEvent> {
@Resource
private SwaggerProperties swaggerProperties;
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerProperties.getEnable())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
// .globalRequestParameters(requestParameters())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title(swaggerProperties.getTitle())
.description(swaggerProperties.getDescription())
.contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactAddress(), swaggerProperties.getContactEmail()))
.version(swaggerProperties.getVersion())
.build();
}
/**
* 设置全局安全策略
*
* @return /
*/
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> schemes = new ArrayList<>();
SecurityScheme scheme = new ApiKey(swaggerProperties.getTokenHeader(), swaggerProperties.getTokenHeader(), In.HEADER.toValue());
schemes.add(scheme);
return schemes;
}
/**
* 授权信息全局应用
*/
private List<SecurityContext> securityContexts() {
SecurityContext securityContext = SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference(swaggerProperties.getTokenHeader(), new AuthorizationScope[]{new AuthorizationScope("global", "")})))
.build();
return Collections.singletonList(securityContext);
}
@Override
public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
try {
Logger logger = LoggerFactory.getLogger(Swagger2Config.class);
//获取IP
String hostAddress = Inet4Address.getLocalHost().getHostAddress();
//获取端口号
int port = webServerInitializedEvent.getWebServer().getPort();
//获取应用名
String applicationName = webServerInitializedEvent.getApplicationContext().getApplicationName();
logger.info("项目启动成功!接口文档地址: http://" + hostAddress + ":" + webServerInitializedEvent.getWebServer().getPort() + applicationName + "/doc.html#");
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

@ -1,115 +0,0 @@
package com.sztzjy.trade.config.swagger;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author 陈沅
*/
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {
/**
* 是否开启swagger,生产环境一般关闭
*/
private Boolean enable;
/**
* 授权KEY
*/
private String tokenHeader;
/**
* 标题
*/
private String title;
/**
* 描述
*/
private String description;
/**
* 联系人姓名
*/
private String contactName;
/**
* 联系人地址
*/
private String contactAddress;
/**
* 联系人邮箱
*/
private String contactEmail;
/**
* 版本
*/
private String version;
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactAddress() {
return contactAddress;
}
public void setContactAddress(String contactAddress) {
this.contactAddress = contactAddress;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getTokenHeader() {
return tokenHeader;
}
public void setTokenHeader(String tokenHeader) {
this.tokenHeader = tokenHeader;
}
}

@ -1,338 +0,0 @@
package com.sztzjy.trade.controller.stu;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.sztzjy.trade.annotation.AnonymousAccess;
import com.sztzjy.trade.annotation.OperateLog;
import com.sztzjy.trade.config.exception.UnAuthorizedException;
import com.sztzjy.trade.config.security.JwtUser;
import com.sztzjy.trade.config.security.LoginResult;
import com.sztzjy.trade.config.security.TokenProvider;
import com.sztzjy.trade.entity.StuUser;
import com.sztzjy.trade.entity.StuUserExample;
import com.sztzjy.trade.entity.ZYUserInfo;
import com.sztzjy.trade.mapper.StuUserMapper;
import com.sztzjy.trade.service.StuUserService;
import com.sztzjy.trade.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@Api(tags = "用户管理")
@RequestMapping("api/user")
@RestController
public class UserController {
@Resource
private StuUserService stuUserService;
@Resource
private HttpServletRequest request;
@Autowired
private StuUserMapper userMapper;
@Resource
private AuthenticationManagerBuilder authenticationManagerBuilder;
@Autowired
private RedisUtil redisUtil;
@Value("${item.name}")
String itemName;
@Autowired
private StuUserMapper stuUserMapper;
@AnonymousAccess
@ApiOperation("用户登录")
@PostMapping("login")
@OperateLog(description = "登录授权")
public ResultDataEntity<LoginResult> login(@ApiParam("用户名") String username,
@ApiParam("加密后的密码") String passwordEncode,
@ApiParam("智云携带的token")@RequestParam(required = false) String TOKEN,
@RequestParam(required = false) Integer type,
HttpServletResponse response) throws IOException {
JwtUser jwtUser;
String password;
if(org.apache.commons.lang3.StringUtils.isBlank(TOKEN)){ //子系统登录
try {
password = RsaUtil.decryptByPrivateKey(passwordEncode);
} catch (Exception e) {
return new ResultDataEntity(HttpStatus.BAD_REQUEST, "密码错误");
}
try {
StuUserExample example = new StuUserExample();
StuUserExample.Criteria criteria = example.createCriteria();
criteria.andStudentIdEqualTo(username);
List<StuUser> stuUsers = userMapper.selectByExample(example);
if(stuUsers.isEmpty()){
throw new UnAuthorizedException("账号不存在");
}else {
StuUser stuUser = stuUsers.get(0);
LoginResult loginResult = new LoginResult();
if(org.apache.commons.lang3.StringUtils.isBlank(stuUser.getPassword()) && "123qwe".equals(password)){
stuUser.setPassword("123qwe");
if(org.apache.commons.lang3.StringUtils.isBlank(stuUser.getClassId())){
stuUser.setRoleId(3);
}else {
stuUser.setRoleId(4);
}
userMapper.updateByPrimaryKeySelective(stuUser);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
jwtUser = (JwtUser) authentication.getPrincipal();
String token = TokenProvider.createToken(jwtUser);
loginResult.setClassId(Convert.toInt(stuUser.getClassId()));
loginResult.setUserId(stuUser.getUserId());
loginResult.setUsername(stuUser.getStudentId());
loginResult.setName(stuUser.getName());
loginResult.setRoleId(stuUser.getRoleId());
loginResult.setSchoolName(stuUser.getSchoolName());
loginResult.setSchoolId(Integer.valueOf(stuUser.getSchoolId()));
loginResult.setAccessToken(token);
loginResult.setStudentId(stuUser.getStudentId());
// redisUtil.set(itemName+"-token:"+jwtUser.getUserId(),token,43200);
//
// //redisUtil.set(itemName+"-userId:"+jwtUser.getUserId(),System.currentTimeMillis(),36000);
// // 设置 loginTime
// Long newLoginTime = System.currentTimeMillis();
// Long newLastActiveTime = System.currentTimeMillis();
// redisUtil.hset(itemName+"-userId:"+jwtUser.getUserId(), "loginTime", newLoginTime,43200);
//
//
// // 设置 lastActiveTime
// redisUtil.hset(itemName+"-userId:"+jwtUser.getUserId(), "lastActiveTime", newLastActiveTime,43200);
return new ResultDataEntity<>(HttpStatus.OK,loginResult);
}else {
if(password.equals(stuUser.getPassword())){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
jwtUser = (JwtUser) authentication.getPrincipal();
String token = TokenProvider.createToken(jwtUser);
loginResult.setClassId(Convert.toInt(stuUser.getClassId()));
loginResult.setUserId(stuUser.getUserId());
loginResult.setName(stuUser.getName());
loginResult.setUsername(stuUser.getStudentId());
loginResult.setRoleId(stuUser.getRoleId());
loginResult.setSchoolId(Integer.valueOf(stuUser.getSchoolId()));
loginResult.setStudentId(stuUser.getStudentId());
loginResult.setAccessToken(token);
loginResult.setSchoolName(stuUser.getSchoolName());
// redisUtil.set(itemName+"-token:"+jwtUser.getUserId(),token,43200);
// // redisUtil.set(itemName+"-userId:"+jwtUser.getUserId(),System.currentTimeMillis(),3600);
//
// Long newLoginTime = System.currentTimeMillis();
// Long newLastActiveTime = System.currentTimeMillis();
//
// // 设置 loginTime
// redisUtil.hset(itemName+"-userId:"+jwtUser.getUserId(), "loginTime", newLoginTime,43200);
//
//
// // 设置 lastActiveTime
// redisUtil.hset(itemName+"-userId:"+jwtUser.getUserId(), "lastActiveTime", newLastActiveTime,43200);
return new ResultDataEntity<>(HttpStatus.OK,loginResult);
}else {
throw new UnAuthorizedException("密码错误");
}
}
}
} catch (Exception e) {
throw new UnAuthorizedException("密码错误");
}
}else { //单点登录
if (!StringUtils.hasText(username) && !StringUtils.hasText(passwordEncode) && !StringUtils.hasText(TOKEN)) {
throw new IllegalArgumentException("请提供登录凭据");
}
if (StringUtils.hasText(TOKEN)) {
if (type==null)
{
type = 0;
}
if (type ==1 )
{
jwtUser = TokenProvider.getJWTUserOne(TOKEN);
}else {
jwtUser = TokenProvider.getJWTUserByZhiYun(TOKEN);
}
// jwtUser = TokenProvider.getJWTUserByZhiYun(TOKEN);
if (jwtUser == null) {
throw new UnAuthorizedException("token无效");
}
} else {
try {
password = RsaUtil.decryptByPrivateKey(passwordEncode);
} catch (Exception e) {
throw new UnAuthorizedException("密码错误");
}
jwtUser = TzApi.foreignExchangeTradingLogin(username, password);
if (jwtUser == null) {
throw new UnAuthorizedException("用户名或密码错误");
}
}
String studentId = jwtUser.getStudentId();
if (!StringUtils.hasText(studentId)) {
studentId= jwtUser.getUsername();
if (!StringUtils.hasText(studentId)) {
studentId= jwtUser.getName();
}
}
//根据StudentId查询用户数据 并且赋予userId
StuUserExample stuUserExample = new StuUserExample();
stuUserExample.createCriteria().andStudentIdEqualTo(studentId);
List<StuUser> stuUserList = stuUserMapper.selectByExample(stuUserExample);
String userId = null;
if (CollectionUtils.isEmpty(stuUserList)) {
StuUser student = new StuUser();
userId = IdUtil.randomUUID();
student.setUserId(userId);
student.setStudentId(studentId);
if (StringUtils.hasText(jwtUser.getName())){
student.setName(jwtUser.getName());
}else {
student.setName(studentId);
}
student.setPassword(jwtUser.getPassword());
student.setRoleId(jwtUser.getRoleId());
student.setClassId(String.valueOf(jwtUser.getClassId()));
student.setClassName(jwtUser.getClassName());
student.setMajor(jwtUser.getMajorName());
student.setSchoolId(String.valueOf(jwtUser.getSchoolId()));
student.setSchoolName(jwtUser.getSchoolName());
stuUserMapper.insertSelective(student);
}
if (StringUtils.hasText(userId)){
jwtUser.setUserId(userId);
}else {
jwtUser.setUserId(stuUserList.get(0).getUserId());
}
Authentication authentication = new UsernamePasswordAuthenticationToken(jwtUser, null, jwtUser.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = TokenProvider.createToken(jwtUser);
//
// redisUtil.set(itemName+"-token:"+jwtUser.getUserId(),token,43200);
//
// // redisUtil.set(itemName+"-userId:"+jwtUser.getUserId(),System.currentTimeMillis(),3600);
//
// Long newLoginTime = System.currentTimeMillis();
// Long newLastActiveTime = System.currentTimeMillis();
//
// // 设置 loginTime
// redisUtil.hset(itemName+"-userId:"+jwtUser.getUserId(), "loginTime", newLoginTime,43200);
//
// // 设置 lastActiveTime
// redisUtil.hset(itemName+"-userId:"+jwtUser.getUserId(), "lastActiveTime", newLastActiveTime,43200);
return new ResultDataEntity<LoginResult>(HttpStatus.OK,LoginResult.create(jwtUser, token));
}
}
@ApiOperation("明文密码公钥加密方法(该方法仅在开发阶段开放用于测试接口)")
@AnonymousAccess
@GetMapping("encrypt")
public ResultDataEntity<String> encrypt(@ApiParam("明文密码") String pwd) throws Exception {
return new ResultDataEntity<>(HttpStatus.OK,"加密成功",RsaUtil.encryptByPublicKey(pwd));
}
@ApiOperation("同步学生信息")
@PostMapping("synchronizationStudentInfo")
public ResultDataEntity synchronizationStudentInfo() {
JwtUser user = TokenProvider.getJWTUser(request);
stuUserService.insertAll(user);
return new ResultDataEntity(HttpStatus.OK);
}
@ApiOperation("开放接口,自动同步学生信息")
@PostMapping("synchronizationStudentInfoByAuto")
@AnonymousAccess
public String synchronizationStudentInfoByAuto(@RequestBody List<ZYUserInfo> zyUserInfoList) {
// JwtUser user = TokenProvider.getJWTUser(request);
// stuUserService.insertAllByAuto(studentList);
List<StuUser> users = new ArrayList<>();
for (int i = 0; i < zyUserInfoList.size(); i++) {
ZYUserInfo zyUserInfo = zyUserInfoList.get(i);
String username = zyUserInfo.getUsername(); // studentid
String name = zyUserInfo.getName();
String password = zyUserInfo.getPassword();
Integer roleId = zyUserInfo.getRoleId(); //3教师 4学生
StuUserExample userInfoExample = new StuUserExample();
userInfoExample.createCriteria().andStudentIdEqualTo(username);
List<StuUser> userInfos = stuUserMapper.selectByExample(userInfoExample);
if(userInfos.isEmpty() || userInfos==null){
StuUser stuUser = new StuUser();
stuUser.setUserId(IdUtil.randomUUID());
stuUser.setStudentId(zyUserInfo.getUsername());
if (!StringUtils.hasText(name)){
stuUser.setName(username);
}else {
stuUser.setName(name);
}
// stuUser.setUsername(username);
stuUser.setPassword(password);
stuUser.setRoleId(roleId);
stuUser.setClassId(zyUserInfo.getClassId().toString());
// stuUser.setPhone(zyUserInfo.getPhone());
stuUser.setClassName(zyUserInfo.getClassName());
stuUser.setMajor(zyUserInfo.getMajorName());
stuUser.setSchoolId(zyUserInfo.getSchoolId().toString());
stuUser.setSchoolName(zyUserInfo.getSchoolName());
stuUser.setCreateTime(new Date());
users.add(stuUser);
}
}
if (users.isEmpty()) {
return "账号已全部存在";
}
users.forEach(stuUser -> {
stuUserMapper.insertSelective(stuUser);
});
return "自动同步学生信息成功!"+"同步"+users.size()+"条用户数据";
}
}

@ -1,358 +0,0 @@
package com.sztzjy.trade.entity;
import java.math.BigDecimal;
import java.util.Date;
import io.swagger.annotations.ApiModelProperty;
/**
* 学生列表
*
* @author whb
* stu_user
*/
public class StuUser {
@ApiModelProperty(notes = "用户ID")
private String userId;
@ApiModelProperty(notes = "学号")
private String studentId;
@ApiModelProperty(notes = "姓名")
private String name;
@ApiModelProperty(notes = "密码")
private String password;
@ApiModelProperty(notes = "3老师 4学生")
private Integer roleId;
@ApiModelProperty(notes = "班级ID")
private String classId;
@ApiModelProperty(notes = "班级名称")
private String className;
@ApiModelProperty(notes = "专业")
private String major;
@ApiModelProperty(notes = "学校ID")
private String schoolId;
@ApiModelProperty(notes = "学校名称")
private String schoolName;
@ApiModelProperty(notes = "总排名(学校)")
private Integer totalRank;
@ApiModelProperty(notes = "综合得分(学校)(乘完权重后)")
private BigDecimal totalScore;
@ApiModelProperty(notes = "创建时间")
private Date createTime;
@ApiModelProperty(notes = "0:未删除 1:已删除")
private Integer delState;
@ApiModelProperty(notes = "更新时间")
private Date updateTime;
@ApiModelProperty(notes = "(总)考勤成绩")
private BigDecimal attendanceScore;
@ApiModelProperty(notes = "(总)作业考试成绩")
private BigDecimal examResultsForHomeworkAssignments;
@ApiModelProperty(notes = "(总)理实案例成绩")
private BigDecimal resultsOfPracticalCaseStudies;
@ApiModelProperty(notes = "数字贸易概论成绩")
private BigDecimal introductionDigitalTrade;
@ApiModelProperty(notes = "数字贸易标准和规则成绩")
private BigDecimal digitalTradeStandardsRules;
@ApiModelProperty(notes = "数字贸易法律法规成绩")
private BigDecimal digitalTradeLawsRegulations;
@ApiModelProperty(notes = "数字知识产权保护成绩")
private BigDecimal protectionDigitalIntellectualProperty;
@ApiModelProperty(notes = "数字贸易技术成绩")
private BigDecimal digitalTradeTechnology;
@ApiModelProperty(notes = "数字贸易物流成绩")
private BigDecimal digitalTradeLogistics;
@ApiModelProperty(notes = "数字贸易金融成绩")
private BigDecimal digitalTradeFinance;
@ApiModelProperty(notes = "数字产品贸易成绩")
private BigDecimal digitalProductTrade;
@ApiModelProperty(notes = "数字技术贸易成绩")
private BigDecimal digitalTechnologyTrade;
@ApiModelProperty(notes = "数字服务贸易成绩")
private BigDecimal digitalServiceTrade;
@ApiModelProperty(notes = "数据贸易成绩")
private BigDecimal dataTrade;
@ApiModelProperty(notes = "数字贸易营销成绩")
private BigDecimal digitalTradeMarketing;
@ApiModelProperty(notes = "aigc数字运营")
private BigDecimal aigcDigitalOperations;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId == null ? null : studentId.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getClassId() {
return classId;
}
public void setClassId(String classId) {
this.classId = classId == null ? null : classId.trim();
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className == null ? null : className.trim();
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major == null ? null : major.trim();
}
public String getSchoolId() {
return schoolId;
}
public void setSchoolId(String schoolId) {
this.schoolId = schoolId == null ? null : schoolId.trim();
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName == null ? null : schoolName.trim();
}
public Integer getTotalRank() {
return totalRank;
}
public void setTotalRank(Integer totalRank) {
this.totalRank = totalRank;
}
public BigDecimal getTotalScore() {
return totalScore;
}
public void setTotalScore(BigDecimal totalScore) {
this.totalScore = totalScore;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getDelState() {
return delState;
}
public void setDelState(Integer delState) {
this.delState = delState;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public BigDecimal getAttendanceScore() {
return attendanceScore;
}
public void setAttendanceScore(BigDecimal attendanceScore) {
this.attendanceScore = attendanceScore;
}
public BigDecimal getExamResultsForHomeworkAssignments() {
return examResultsForHomeworkAssignments;
}
public void setExamResultsForHomeworkAssignments(BigDecimal examResultsForHomeworkAssignments) {
this.examResultsForHomeworkAssignments = examResultsForHomeworkAssignments;
}
public BigDecimal getResultsOfPracticalCaseStudies() {
return resultsOfPracticalCaseStudies;
}
public void setResultsOfPracticalCaseStudies(BigDecimal resultsOfPracticalCaseStudies) {
this.resultsOfPracticalCaseStudies = resultsOfPracticalCaseStudies;
}
public BigDecimal getIntroductionDigitalTrade() {
return introductionDigitalTrade;
}
public void setIntroductionDigitalTrade(BigDecimal introductionDigitalTrade) {
this.introductionDigitalTrade = introductionDigitalTrade;
}
public BigDecimal getDigitalTradeStandardsRules() {
return digitalTradeStandardsRules;
}
public void setDigitalTradeStandardsRules(BigDecimal digitalTradeStandardsRules) {
this.digitalTradeStandardsRules = digitalTradeStandardsRules;
}
public BigDecimal getDigitalTradeLawsRegulations() {
return digitalTradeLawsRegulations;
}
public void setDigitalTradeLawsRegulations(BigDecimal digitalTradeLawsRegulations) {
this.digitalTradeLawsRegulations = digitalTradeLawsRegulations;
}
public BigDecimal getProtectionDigitalIntellectualProperty() {
return protectionDigitalIntellectualProperty;
}
public void setProtectionDigitalIntellectualProperty(BigDecimal protectionDigitalIntellectualProperty) {
this.protectionDigitalIntellectualProperty = protectionDigitalIntellectualProperty;
}
public BigDecimal getDigitalTradeTechnology() {
return digitalTradeTechnology;
}
public void setDigitalTradeTechnology(BigDecimal digitalTradeTechnology) {
this.digitalTradeTechnology = digitalTradeTechnology;
}
public BigDecimal getDigitalTradeLogistics() {
return digitalTradeLogistics;
}
public void setDigitalTradeLogistics(BigDecimal digitalTradeLogistics) {
this.digitalTradeLogistics = digitalTradeLogistics;
}
public BigDecimal getDigitalTradeFinance() {
return digitalTradeFinance;
}
public void setDigitalTradeFinance(BigDecimal digitalTradeFinance) {
this.digitalTradeFinance = digitalTradeFinance;
}
public BigDecimal getDigitalProductTrade() {
return digitalProductTrade;
}
public void setDigitalProductTrade(BigDecimal digitalProductTrade) {
this.digitalProductTrade = digitalProductTrade;
}
public BigDecimal getDigitalTechnologyTrade() {
return digitalTechnologyTrade;
}
public void setDigitalTechnologyTrade(BigDecimal digitalTechnologyTrade) {
this.digitalTechnologyTrade = digitalTechnologyTrade;
}
public BigDecimal getDigitalServiceTrade() {
return digitalServiceTrade;
}
public void setDigitalServiceTrade(BigDecimal digitalServiceTrade) {
this.digitalServiceTrade = digitalServiceTrade;
}
public BigDecimal getDataTrade() {
return dataTrade;
}
public void setDataTrade(BigDecimal dataTrade) {
this.dataTrade = dataTrade;
}
public BigDecimal getDigitalTradeMarketing() {
return digitalTradeMarketing;
}
public void setDigitalTradeMarketing(BigDecimal digitalTradeMarketing) {
this.digitalTradeMarketing = digitalTradeMarketing;
}
public BigDecimal getAigcDigitalOperations() {
return aigcDigitalOperations;
}
public void setAigcDigitalOperations(BigDecimal aigcDigitalOperations) {
this.aigcDigitalOperations = aigcDigitalOperations;
}
public StuUser() {
}
}

File diff suppressed because it is too large Load Diff

@ -1,130 +0,0 @@
package com.sztzjy.trade.entity;
public class ZYUserInfo {
private String username;
private String password;
private String name;
private Integer userId;
private Integer roleId;
private Integer schoolId;
private String schoolName;
private Integer classId;
private String className;
private String phone ;
private Long collegeId;
private String collegeName;
private Long majorId;
private String majorName;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getSchoolId() {
return schoolId;
}
public void setSchoolId(Integer schoolId) {
this.schoolId = schoolId;
}
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getCollegeId() {
return collegeId;
}
public void setCollegeId(Long collegeId) {
this.collegeId = collegeId;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
public Long getMajorId() {
return majorId;
}
public void setMajorId(Long majorId) {
this.majorId = majorId;
}
public String getMajorName() {
return majorName;
}
public void setMajorName(String majorName) {
this.majorName = majorName;
}
}

@ -1,38 +0,0 @@
package com.sztzjy.trade.enums;
import com.sztzjy.trade.util.EnumUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 进行中 ING
* 已结束 END
* 未开始 READY
*/
@Getter
@AllArgsConstructor
public enum StartStatusEnum {
// 未开始
READY(-1, "未开始"),
// 进行中
ING(0, "进行中"),
// 已结束
END(1, "已结束")
;
private Integer code;
// 可以转换成中文
// @JsonValue
private String text;
public static StartStatusEnum getByCode(Integer code) {
return EnumUtil.getByFieldWithValue(StartStatusEnum.class, "code", code);
}
}

@ -1,76 +0,0 @@
package com.sztzjy.trade.mapper;
import com.sztzjy.trade.entity.StuUser;
import com.sztzjy.trade.entity.StuUserExample;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface StuUserMapper {
long countByExample(StuUserExample example);
int deleteByExample(StuUserExample example);
int deleteByPrimaryKey(String userId);
int insert(StuUser record);
int insertSelective(StuUser record);
List<StuUser> selectByExample(StuUserExample example);
StuUser selectByPrimaryKey(String userId);
int updateByExampleSelective(@Param("record") StuUser record, @Param("example") StuUserExample example);
int updateByExample(@Param("record") StuUser record, @Param("example") StuUserExample example);
int updateByPrimaryKeySelective(StuUser record);
int updateByPrimaryKey(StuUser record);
List<StuUser> getStartCourseNameList(@Param("classNames")List<String> classNames);
List<StuUser> selectByCourseName(String startCourseName);
/**
* 查询学校所有班级名称
* @param schoolId 学校ID学校ID
* @return 班级名称集合
*/
List<String> selectByClassName(String schoolId);
@Select("select school_id from stu_user group by school_id")
List<String> selectSchool();
/**
* 根据班级名称查询所有不在班级集合中的学生信息
* @param strings 班级名称集合
* @param schoolId 学校ID
* @return 学生信息
*/
List<String> selectByNoClassName(@Param("strings") List<String> strings,String schoolId);
/**
* 根据班级名称查询学生信息
* @param lists 班级名称集合
* @param schoolId 学校ID
* @return 学生信息
*/
List<StuUser> selectStuList(@Param("lists") List<String> lists, String schoolId);
@Select("SELECT class_name, class_id\n" +
"FROM stu_user\n" +
"WHERE school_id = #{schoolId}\n" +
" AND class_name IS NOT NULL\n" +
"GROUP BY class_name, class_id")
List<Map<String, Object>> getClassList(String schoolId);
@Select("SELECT school_name \n" +
"FROM stu_user\n" +
"WHERE school_id = #{schoolId} LIMIT 1")
String selectBySchoolName(String schoolId);
}

@ -1,21 +0,0 @@
package com.sztzjy.trade.service;
import com.sztzjy.trade.config.security.JwtUser;
import com.sztzjy.trade.entity.ZYUserInfo;
import java.util.List;
/**
* @author 17803
* @date 2024-05-07 9:57
*/
public interface StuUserService {
void insertAll(JwtUser user);
void insertAllByAuto(List<ZYUserInfo> studentList);
}

@ -1,157 +0,0 @@
package com.sztzjy.trade.service.impl;/**
* @author 17803
* @date 2024-05-07 9:58
*/
import com.sztzjy.trade.config.security.JwtUser;
import com.sztzjy.trade.entity.*;
import com.sztzjy.trade.mapper.StuUserMapper;
import com.sztzjy.trade.service.StuUserService;
import com.sztzjy.trade.util.TzApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
@Service
public class StuUserServiceImpl implements StuUserService {
@Autowired
private StuUserMapper userMapper;
@Autowired
private StuUserMapper stuUserMapper;
@Override
public void insertAll(JwtUser user) {
List<Map<String, Object>> classList = TzApi.GetClassBySchoolIdForForeignExchangeTrading(user);
if (classList == null || classList.size() == 0) {
return;
}
List<StuUser> users = new ArrayList<>();
Set<String> userIds = new HashSet<>();
String schoolId = String.valueOf(user.getSchoolId());
for (Map<String, Object> classes : classList) {
String classId = classes.get("id").toString();
List<Map<String, Object>> studentList = TzApi.GetStudentInfoByClassIdForForeignExchangeTrading(classId, user);
if (studentList == null || studentList.size() == 0) {
continue;
}
for (Map<String, Object> student : studentList) {
StuUser stuUser = new StuUser();
stuUser.setUserId(student.get("userId").toString());
if (student.get("userId").toString().equals("null") || student.get("userId").toString().equals("8184") || student.get("userId").toString().equals("8238") || student.get("userId").toString().equals("8258") || student.get("userId").toString().equals("8259") || student.get("userId").toString().equals("8260") || student.get("userId").toString().equals("8270")) {
continue;
}
if (!userIds.add(stuUser.getUserId())) {
continue;
}
stuUser.setStudentId(student.get("studentNo").toString());
stuUser.setSchoolName(student.get("schoolName").toString());
stuUser.setName(student.get("name").toString());
stuUser.setClassId(classId);
stuUser.setRoleId(3);
stuUser.setClassName(classes.get("name").toString());
stuUser.setSchoolId(schoolId);
stuUser.setPassword("123qwe");
// stuUser.setLoanCasesScore(BigDecimal.valueOf(0));
// stuUser.setPerSituationScore(BigDecimal.valueOf(0));
// stuUser.setRepaymentBehaviorScore(BigDecimal.valueOf(0));
// stuUser.setPerInfluenceFactorScore(BigDecimal.valueOf(0));
// stuUser.setPerCreditOptimizationSocre(BigDecimal.valueOf(0));
// stuUser.setPerCreditRatingSocre(BigDecimal.valueOf(0));
// stuUser.setEntInfluenceFactorSocre(BigDecimal.valueOf(0));
// stuUser.setEntCreditOptimizationSocre(BigDecimal.valueOf(0));
// stuUser.setEntCreditRatingSocre(BigDecimal.valueOf(0));
// stuUser.setCaseUserProfileSocre(BigDecimal.valueOf(0));
// stuUser.setCasePersonalCreditScore(BigDecimal.valueOf(0));
// stuUser.setCaseCorporateCreditScore(BigDecimal.valueOf(0));
// stuUser.setCaseCorporateCreditSubScore(BigDecimal.valueOf(0));
// stuUser.setCaseCorporateCreditObjScore(BigDecimal.valueOf(0));
// stuUser.setCasePersonalCreditSubScore(BigDecimal.valueOf(0));
// stuUser.setCasePersonalCreditObjScore(BigDecimal.valueOf(0));
//
// stuUser.setCreditPortraitScore(BigDecimal.valueOf(0));
// stuUser.setPersonalCreditScore(BigDecimal.valueOf(0));
// stuUser.setCorporateCreditScore(BigDecimal.valueOf(0));
// stuUser.setComprehensiveCaseScore(BigDecimal.valueOf(0));
stuUser.setTotalScore(BigDecimal.valueOf(0));
users.add(stuUser);
}
}
for (StuUser userinfo : users) {
userMapper.insertSelective(userinfo);
}
//根据学校id 查询成绩总览权重表中是否有数据 有则不进行操作 没有则新增权重
// TchModuleWeithExample resultsExample = new TchModuleWeithExample();
// resultsExample.createCriteria().andSchoolIdEqualTo(schoolId);
// List<TchModuleWeith> resultsWeights = tchModuleWeithMapper.selectByExample(resultsExample);
// if (resultsWeights.isEmpty()) {
// TchModuleWeith tchModuleWeith = new TchModuleWeith(schoolId);
//
// tchModuleWeithMapper.insertSelective(tchModuleWeith);
// }
}
/**
* 开放接口,自动同步学生信息
*
* @param studentList
* @return
*/
@Override
public void insertAllByAuto(List<ZYUserInfo> studentList) {
if (studentList.isEmpty()) {
return;
}
for (ZYUserInfo student : studentList) {
StuUser stuUser = new StuUser();
//基本信息
if (student.getUserId().equals("null") || student.getUserId().equals("8184")
|| student.getUserId().equals("8238")
|| student.getUserId().equals("8258") || student.getUserId().equals("8259")
|| student.getUserId().equals("8260") || student.getUserId().equals("8270")) {
continue;
}
stuUser.setUserId(student.getUserId().toString());
stuUser.setStudentId(student.getUsername());
stuUser.setName(student.getUsername());
stuUser.setPassword(student.getPassword());
stuUser.setRoleId(student.getRoleId());
stuUser.setClassId(student.getClassId().toString());
stuUser.setClassName(student.getClassName());
stuUser.setMajor(student.getMajorName());
stuUser.setSchoolId(student.getSchoolId().toString());
stuUser.setSchoolName(student.getSchoolName());
stuUser.setTotalScore(BigDecimal.valueOf(0));
stuUserMapper.insertSelective(stuUser);
}
}
}

@ -1,293 +0,0 @@
package com.sztzjy.trade.util;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class BigDecimalUtils {
//默认除法运算精度
private static final int DEF_DIV_SCALE = 5;
public double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
public double add(double v1, double v2,int scale) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的加法运算
*
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public BigDecimal add(String v1, String v2) {
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.add(b2);
}
/**
* 提供精确的加法运算
*
* @param v1 被加数
* @param v2 加数
* @param scale 保留scale 位小数
* @return 两个参数的和
* @throws IllegalAccessException
*/
public String add(String v1, String v2, int scale) throws IllegalAccessException {
if (scale < 0) {
throw new IllegalAccessException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 提供精确的减法运算
*
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public Double sub(Double v1, Double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的减法运算
*
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public BigDecimal sub(String v1, String v2) {
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.subtract(b2);
}
/**
* 提供精确的减法运算
*
* @param v1 被减数
* @param v2 减数
* @param scale 保留scale 位小数
* @return 两个参数的差
* @throws IllegalAccessException
*/
public String sub(String v1, String v2, int scale) throws IllegalAccessException {
if (scale < 0) {
throw new IllegalAccessException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.subtract(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 提供精确的乘法运算
*
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public Double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供精确的乘法运算
*
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public BigDecimal mul(String v1, String v2) {
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.multiply(b2);
}
/**
* 提供精确的乘法运算
*
* @param v1 被乘数
* @param v2 乘数
* @param scale 保留scale 位小数
* @return 两个参数的积
*/
public double mul(double v1, double v2, int scale) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return round(b1.multiply(b2).doubleValue(), scale);
}
/**
* 提供精确的乘法运算
*
* @param v1 被乘数
* @param v2 乘数
* @param scale 保留scale 位小数
* @return 两个参数的积
*/
public String mul(String v1, String v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.multiply(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入
*
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public Double div(double v1, double v2) {
return div(v1, v2, DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入
*
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入
*
* @param v1 被除数
* @param v2 除数
* @param scale 表示需要精确到小数点以后几位
* @return 两个参数的商
*/
public String div(String v1, String v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v1);
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 提供精确的小数位四舍五入处理
*
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理
*
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public String round(String v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(v);
return b.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 取余数
*
* @param v1 被除数
* @param v2 除数
* @param scale 小数点后保留几位
* @return 余数
*/
public String remainder(String v1, String v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
return b1.remainder(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 取余数 BigDecimal
*
* @param v1 被除数
* @param v2 除数
* @param scale 小数点后保留几位
* @return 余数
*/
public BigDecimal remainder(BigDecimal v1, BigDecimal v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
return v1.remainder(v2).setScale(scale, BigDecimal.ROUND_HALF_UP);
}
/**
* 比较大小
*
* @param v1 被比较数
* @param v2 比较数
* @return 如果v1 大于v2 则 返回true 否则false
*/
public boolean compare(String v1, String v2) {
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
int bj = b1.compareTo(b2);
boolean res;
if (bj > 0)
res = true;
else
res = false;
return res;
}
}

@ -1,50 +0,0 @@
package com.sztzjy.trade.util;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* 咖啡因提供的缓存工具类
*
*/
public class CacheProvider {
private Cache<String, Object> cache = null;
public CacheProvider(Integer expire, Integer maxSize) {
/**
* 基于时间的移除:expireAfterAccess(long, TimeUnit) 根据某个键值对最后一次访问之后多少时间后移除
*         expireAfterWrite(long, TimeUnit) 根据某个键值对被创建或值被替换后多少时间移除
*/
if(cache==null){
cache = Caffeine.newBuilder()
.expireAfterWrite(expire, TimeUnit.SECONDS)
.maximumSize(maxSize)
.build();
}
}
public long getSize(){
return cache.estimatedSize();
}
public void put(String key,String value){
cache.put(key, value);
}
public void put(String key,Object value){
cache.put(key, value);
}
public Object get(String key){
return cache.getIfPresent(key);
}
public Object get(String key,Function<? super String, ? extends Object> fc){
return cache.get(key,fc);
}
public void remove(String key){
cache.invalidate(key);
}
}

@ -1,117 +0,0 @@
package com.sztzjy.trade.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @Author tanzheng
* @Description 类型转换: Entity - DTO互转
* @Date 2023/8/9
* @Param [params]
**/
@Component
public class ConvertUtil {
public static final Logger logger = LoggerFactory.getLogger(ConvertUtil.class);
/**
* Entity转DTO
* @param source
* @param target
* @return
* @param <T>
*/
public <T> T entityToDTO(Object source, Class<T> target) {
if (source == null) {
return null;
}
T targetObject = null;
try {
targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
} catch (Exception e) {
e.printStackTrace();
}
return targetObject;
}
/**
* DTO转Entity
* @param source
* @param target
* @return
* @param <T>
*/
public <T> T DTOToEntity(Object source, Class<T> target) {
if (source == null) {
return null;
}
T targetObject = null;
try {
targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
} catch (Exception e) {
e.printStackTrace();
}
return targetObject;
}
/**
* 列表实体转DTO
* @param sourceList
* @param target
* @return
* @param <T>
*/
public <T> List<T> entityToDTOList(Collection<?> sourceList, Class<T> target) {
if (sourceList == null) {
return null;
}
List<T> targetList = new ArrayList<>(sourceList.size());
try {
for (Object source : sourceList) {
T targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
targetList.add(targetObject);
}
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetList;
}
/**
* DTO转列表实体
* @param sourceList
* @param target
* @return
* @param <T>
*/
public <T> List<T> DTOListToEntity(Collection<?> sourceList, Class<T> target) {
if (sourceList == null) {
return null;
}
List<T> targetList = new ArrayList<>(sourceList.size());
try {
for (Object source : sourceList) {
T targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
targetList.add(targetObject);
}
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetList;
}
}

@ -1,97 +0,0 @@
package com.sztzjy.trade.util;
import cn.hutool.core.date.DateUtil;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 日期转成中文大写形式
*
*/
public class DateToUpperChinese {
private static final String[] NUMBERS = { "零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖" };
/** 通过 yyyy-MM-dd 得到中文大写格式 yyyy MM dd 日期 */
public static synchronized String toChinese(Date newDate) {
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
String str = outputFormat.format(newDate);
StringBuffer sb = new StringBuffer();
sb.append(getSplitDateStr(str, 0)).append("年").append(
getSplitDateStr(str, 1)).append("月").append(
getSplitDateStr(str, 2)).append("日");
return sb.toString();
}
/** 分别得到年月日的大写 默认分割符 "-" */
public static String getSplitDateStr(String str, int unit) {
// unit是单位 0=年 1=月 2日
String[] DateStr = str.split("-");
if (unit > DateStr.length)
unit = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < DateStr[unit].length(); i++) {
if ((unit == 1 || unit == 2) && Integer.valueOf(DateStr[unit]) > 9) {
sb.append(convertNum(DateStr[unit].substring(0, 1)))
.append("拾").append(
convertNum(DateStr[unit].substring(1, 2)));
break;
} else {
sb.append(convertNum(DateStr[unit].substring(i, i + 1)));
}
}
if (unit == 1 || unit == 2) {
return sb.toString().replaceAll("^壹", "").replace("零", "");
}
return sb.toString();
}
/** 转换数字为大写 */
private static String convertNum(String str) {
return NUMBERS[Integer.valueOf(str)];
}
/** 判断是否是零或正整数 */
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
public static void main(String args[]) {
System.out.println(toChinese(DateUtil.parse("2008-10-24")));
// 获取当前日期
Date currentDate = new Date();
// 将日期转换为Calendar对象
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
// 将月份增加1
calendar.add(Calendar.MONTH, 1);
// 获取加一个月后的日期
Date newDate = calendar.getTime();
// // 将 Date 对象格式化为 "yyyy-MM-dd" 的字符串
// SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
// String outputDateString = outputFormat.format(newDate);
// System.out.println(outputDateString);
System.out.println(toChinese(newDate));
}
}

@ -1,40 +0,0 @@
package com.sztzjy.trade.util;
import cn.hutool.core.util.ReflectUtil;
import java.util.Arrays;
/**
* <p>
*
* </p>
*
* @author mlx
* @date 2022/9/24
* @modified
*/
public class EnumUtil extends cn.hutool.core.util.EnumUtil {
/**
* 通过属性名,匹配值
* @param enumClass
* @param fieldNme
* @param value
* @return
* @param <E>
*/
public static <E extends Enum<E>> E getByFieldWithValue(Class<E> enumClass, String fieldNme, Object value) {
final E[] enumConstants = enumClass.getEnumConstants();
for (E enumConstant : enumConstants) {
Object fieldValue = ReflectUtil.getFieldValue(enumConstant, fieldNme);
if (fieldValue.equals(value)) {
return enumConstant;
}
}
return null;
}
public static <E extends Enum<E>> boolean contains(E em, E... eNums) {
return Arrays.stream(eNums).anyMatch(e -> e.compareTo(em) == 0);
}
}

@ -1,38 +0,0 @@
package com.sztzjy.trade.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileHashUtil {
public static String calculateSHA256(MultipartFile file) throws Exception {
// 创建 SHA-256 的 MessageDigest 实例
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// 获取输入流并读取文件内容
try (InputStream inputStream = file.getInputStream()) {
byte[] buffer = new byte[4096]; // 4KB 缓冲区
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 更新哈希值
digest.update(buffer, 0, bytesRead);
}
}
// 计算哈希值
byte[] hashBytes = digest.digest();
// 将字节数组转换为十六进制字符串
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0'); // 确保每个字节都是两位
hexString.append(hex);
}
return hexString.toString(); // 返回结果
}
}

@ -1,39 +0,0 @@
package com.sztzjy.trade.util;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class GeneratorUtil {
public static void generate() {
try {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
// 获取 generatorConfig.xml 文件路径
URL resourceUrl = GeneratorUtil.class.getResource("/generatorConfig.xml");
String configFilePath = resourceUrl.getFile();
File configFileObj = new File(configFilePath);
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFileObj);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
generate();
}
}

@ -1,131 +0,0 @@
package com.sztzjy.trade.util;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class HttpUtils {
public static String CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
// 发送GET请求
public static String sendGet(String url) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
// 发送POST请求
public static JSONObject sendPost(String url, String paramStr, String contentType, String token) throws IOException {
try {
JSONObject ret = new JSONObject();
HttpPost method = new HttpPost(url);
StringEntity entity = new StringEntity(paramStr, "utf-8");
entity.setContentEncoding("UTF-8");
if (StringUtils.isEmpty(contentType))
entity.setContentType("application/json");
else
entity.setContentType(contentType);
if (StringUtils.isNotEmpty(token)) {
method.setHeader("Authorization", "Bearer " + token);
}
method.setEntity(entity);
int timeout = 60000;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(timeout)
.setConnectTimeout(timeout)
.build();
method.setConfig(requestConfig);
HttpClient client = HttpClients.createDefault();
HttpResponse resp = client.execute(method);
int statusCode = resp.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
log.info("接口请求失败,返回码:" + statusCode + ",失败原因:" + resp.getStatusLine().getReasonPhrase());
return null;
}
String respString = EntityUtils.toString(resp.getEntity(), "UTF-8");
ret.set("statusCode",statusCode);
if(StringUtils.isNotEmpty(respString)){
ret.set("respString",respString);
}
return ret;
}catch (Exception e) {
e.printStackTrace();
log.info("接口请求失败,失败原因:"+e.getMessage());
}
return null;
}
// 发送GET请求 携带Token
public static String sendGet(String url, String token) throws IOException {
HttpURLConnection connection = null;
BufferedReader reader = null;
StringBuilder response = new StringBuilder();
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setRequestMethod("GET");
// 添加token到请求头部
connection.setRequestProperty("Authorization", "Bearer " + token);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
if (connection != null) {
connection.disconnect();
}
}
return response.toString();
}
}

@ -1,159 +0,0 @@
package com.sztzjy.trade.util;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReUtil;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static cn.hutool.core.net.NetUtil.ipv4ToLong;
public class IpUtils {
// 分隔符1
public static final String SEPARATOR = "\\,";
// 分隔符2
public static final String IP_SPLIT_MARK = "\\-";
// 分隔符3
public static final String IP_SPLIT_SEPARATOR = "\\.";
private IpUtils() {
}
/**
* 获取当前网络ip
*
* @param request
* @return
*/
public static String getIpAddr(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")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
/**
* 获得MAC地址
*
* @param ip
* @return
*/
public static String getMACAddress(String ip) {
String str = "";
String macAddress = "";
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
InputStreamReader ir = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (int i = 1; i < 100; i++) {
str = input.readLine();
if (str != null) {
if (str.indexOf("MAC Address") > 1) {
macAddress = str.substring(str.indexOf("MAC Address") + 14);
break;
}
}
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
return macAddress;
}
/**
* 验证IP区间是否符合要求
*
*
* @param ipRangeAddressList 支持格式:x.x.x.x-x.x.x.x,x.x.x.x-x.x.x.x。多个IP段逗号隔开
*/
public static void verifyIpRange(String ipRangeAddressList) {
Assert.notBlank(ipRangeAddressList, "待验证的IP区间,不能为空!");
for (String ipRange : ipRangeAddressList.split(SEPARATOR)) {
// IP区间的正则
String reg = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}" +
"-((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$";
Assert.isTrue(ReUtil.isMatch(reg, ipRange),
() -> new RuntimeException("ipRangeAddressList 参数格式化错误!支持格式如:192.168.1.1-192.168.1.100"));
}
}
/**
* 验证IP是否符合要求
*
*
* @param ipAddressList 支持格式:x.x.x.x 多个IP段逗号隔开
*/
public static void verifyIp(String ipAddressList) {
Assert.notBlank(ipAddressList, "待验证的IP,不能为空!");
for (String ip : ipAddressList.split(SEPARATOR)) {
// 单IP的正则
String reg = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$";
Assert.isTrue(ReUtil.isMatch(reg, ip),
() -> new RuntimeException("ipAddressList 参数格式化错误!支持格式:192.168.1.1-192.168.1.100"));
}
}
/**
* ID是否在IP区间内
*
* @param myIpAddress
* @param ipAddressList 支持格式:x.x.x.x-x.x.x.x,x.x.x.x-x.x.x.x。多个IP段逗号隔开
* @return
*/
public static Boolean isRangeInner(String myIpAddress, String ipAddressList) throws RuntimeException {
verifyIpRange(ipAddressList);
// 我的IPv4转long类型
long myIpLong = ipv4ToLong(myIpAddress);
// 是否在IP段区间
Boolean isRangeInner = false;
// 处理IP段,判断IP是否在这个区间内 192.168.1.1-192.168.1.100,192.168.2.1-192.168.2.100
for (String range : ipAddressList.split(SEPARATOR)) {
// 两个IP段。开始IP-结束IP
String[] ips = range.split(IP_SPLIT_MARK);
long startIpLong = ipv4ToLong(ips[0]);
long endIpLong = ipv4ToLong(ips[1]);
// 在区间内,则打标记
if((myIpLong >= startIpLong) && (myIpLong <= endIpLong)) {
isRangeInner = true;
}
}
return isRangeInner;
}
}

@ -1,251 +0,0 @@
package com.sztzjy.trade.util;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import org.mybatis.generator.internal.util.StringUtility;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import static org.mybatis.generator.internal.util.StringUtility.isTrue;
/*
* @author tz
* @Date 2023/11/14
*/
public class MyCommentGenerator implements CommentGenerator {
public static void main(String[] args) {
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
// 给出generatorConfig.xml文件的位置,绝对地址或者类路径下
//File configFile = new File("E:\\xxxxxxxxx\\generatorConfig.xml");
File configFile = new File(MyCommentGenerator.class.getClassLoader().getResource("generatorConfig.xml").getFile());
ConfigurationParser cp = new ConfigurationParser(warnings);
try {
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
private Properties properties;
private boolean suppressDate;
private boolean suppressAllComments;
/**
* If suppressAllComments is true, this option is ignored.
*/
private boolean addRemarkComments;
private SimpleDateFormat dateFormat;
public MyCommentGenerator() {
super();
properties = new Properties();
suppressDate = false;
suppressAllComments = false;
addRemarkComments = false;
}
/**
* 默认配置
*
* @param properties
*/
@Override
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
suppressDate = isTrue(properties
.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
suppressAllComments = isTrue(properties
.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
addRemarkComments = isTrue(properties
.getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));
String dateFormatString = properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT);
if (StringUtility.stringHasValue(dateFormatString)) {
dateFormat = new SimpleDateFormat(dateFormatString);
}
}
/**
* 实体类添加的注释
*
* @param topLevelClass
* @param introspectedTable
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
if (suppressAllComments || !addRemarkComments) {
return;
}
topLevelClass.addJavaDocLine("import io.swagger.annotations.ApiModelProperty;");
topLevelClass.addJavaDocLine("/**"); //$NON-NLS-1$
String remarks = introspectedTable.getRemarks();
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
String[] remarkLines = remarks.split(System.getProperty("line.separator")); //$NON-NLS-1$
for (String remarkLine : remarkLines) {
topLevelClass.addJavaDocLine(" * " + remarkLine); //$NON-NLS-1$
}
}
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * @author whb");
topLevelClass.addJavaDocLine(" * " + introspectedTable.getFullyQualifiedTable().toString());
topLevelClass.addJavaDocLine(" */");
// topLevelClass.addJavaDocLine("@Data");
}
// /**
// * 实体类的属性注释,数据库中自定义注释
// *
// * @param field
// * @param introspectedTable
// * @param introspectedColumn
// */
// @Override
// public void addFieldComment(Field field,
// IntrospectedTable introspectedTable,
// IntrospectedColumn introspectedColumn) {
// if (suppressAllComments) {
// return;
// }
// field.addJavaDocLine("/**"); //$NON-NLS-1$
// String remarks = introspectedColumn.getRemarks();
// if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
// String[] remarkLines = remarks.split(System.getProperty("line.separator")); //$NON-NLS-1$
// for (String remarkLine : remarkLines) {
// field.addJavaDocLine(" * " + remarkLine); //$NON-NLS-1$
// }
// }
// field.addJavaDocLine(" */"); //$NON-NLS-1$
// }
/**
* 实体类的属性注释,数据库中自定义注释
*
* @param field
* @param introspectedTable
* @param introspectedColumn
*/
@Override
public void addFieldComment(Field field,
IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
// field.addJavaDocLine("/**"); //$NON-NLS-1$
String remarks = introspectedColumn.getRemarks();
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
String[] remarkLines = remarks.split(System.getProperty("line.separator")); //$NON-NLS-1$
for (String remarkLine : remarkLines) {
// field.addJavaDocLine("@ApiModelProperty(\"" + remarkLine + "\")");
field.addJavaDocLine("@ApiModelProperty(notes = \"" + remarkLine + "\")");
}
}
// field.addJavaDocLine(" */"); //$NON-NLS-1$
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
// field.addJavaDocLine("/**"); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
// field.addJavaDocLine(" */"); //$NON-NLS-1$
}
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
}
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
}
// 不需要get方法的注释
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
// 不需要set方法的注释
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
@Override
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable, Set<FullyQualifiedJavaType> imports) {
}
@Override
public void addComment(XmlElement xmlElement) {
}
@Override
public void addRootComment(XmlElement rootElement) {
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
}
}

@ -1,100 +0,0 @@
package com.sztzjy.trade.util;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 分页工具类
*/
public class PageUtil {
private final Integer index;
private final Integer size;
private Sort sort;
/*
* @author xcj
* @Date 2023/9/9
*/
//直接给list分页
public static PageInfo pageHelper(List list, Integer pageNum, Integer pageSize){
Page page = new Page(pageNum, pageSize);
int total = list.size();
page.setTotal(total);
int startIndex = (pageNum - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize,total);
if(startIndex>endIndex){
page.addAll(new ArrayList());
PageInfo pageInfo = new PageInfo<>(page);
return pageInfo;
}else{
page.addAll(list.subList(startIndex,endIndex));
PageInfo pageInfo = new PageInfo<>(page);
return pageInfo;
}
}
//给map分页
public static <K, V> PageInfo<Map.Entry<K, V>> pageMapHelper(Map<K, V> map, Integer pageNum, Integer pageSize) {
Page page = new Page(pageNum, pageSize);
List<Map.Entry<K, V>> entryList = new ArrayList<>(map.entrySet()); // 将 Map 转换为 Entry 列表
int total = entryList.size();
page.setTotal(total);
int startIndex = (pageNum - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, total);
if (startIndex > endIndex) {
page.addAll(new ArrayList<>()); // 当没有内容时,也要确保页面的一致性
} else {
page.addAll(entryList.subList(startIndex, endIndex)); // 获取子列表
}
return new PageInfo<>(page);
}
public PageUtil(Integer index, Integer size) {
if (index == null || index < 0) index = 0;
if (size == null || size < 0) size = 10;
if (size > 200) size = 1000;
this.index = index;
this.size = size;
}
//该方法用于数据量大的情况下分页导出
public PageUtil(Integer index, Integer size, boolean type) {
if (index == null || index < 0) index = 0;
if (size == null || size < 0) size = 10;
this.index = index;
this.size = size;
}
public void addSort(String columnName, Boolean asc) {
Sort.Direction direction = Sort.Direction.ASC;
if (!asc) direction = Sort.Direction.DESC;
if (sort == null) {
sort = Sort.by(direction, columnName);
} else {
sort = sort.and(Sort.by(direction, columnName));
}
}
public Pageable getPageable() {
if (sort == null)
return PageRequest.of(index, size);
else
return PageRequest.of(index, size, sort);
}
}

@ -1,619 +0,0 @@
package com.sztzjy.trade.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
@Value("${item.name}")
String itemName;
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
public String item() {
return itemName;
}
/**
* scan 实现
* @param pattern 表达式
* @param consumer 对迭代到的key进行操作
*/
public void scan(String pattern, Consumer<byte[]> consumer) {
this.redisTemplate.execute((RedisConnection connection) -> {
try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(Long.MAX_VALUE).match(pattern).build())) {
cursor.forEachRemaining(consumer);
return null;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
});
}
/**
* 获取符合条件的key
* @param pattern 表达式
* @return
*/
public List<String> keysByScan(String pattern) {
List<String> keys = new ArrayList<>();
this.scan(pattern, item -> {
//符合条件的key
String key = new String(item, StandardCharsets.UTF_8);
keys.add(key);
});
return keys;
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public <T> T get(String key) {
if (key == null) return null;
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}

@ -1,64 +0,0 @@
package com.sztzjy.trade.util;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Flux;
/**
* 出参对象统一封装
*/
@Getter
public class ResultDataEntity<T> {
/**
* 状态码
*/
private final Integer code;
/**
* 异常提示
*/
// @JsonInclude(JsonInclude.Include.NON_NULL)
private String msg = null;
/**
* 返回体对象
*/
// @JsonInclude(JsonInclude.Include.NON_NULL)
private T data = null;
private Flux<String> flow;
public ResultDataEntity(T data) {
this.code = HttpStatus.OK.value();
this.data = data;
}
public ResultDataEntity(HttpStatus status, T data) {
this.code = status.value();
this.data = data;
}
public ResultDataEntity(HttpStatus status, Flux<String> data) {
this.code = status.value();
this.flow = data;
}
public ResultDataEntity(HttpStatus status, String msg, T data) {
this.code = status.value();
this.msg = msg;
this.data = data;
}
public ResultDataEntity(String msg) {
this.code = HttpStatus.OK.value();
this.msg = msg;
}
public ResultDataEntity(HttpStatus status, String msg) {
this.code = status.value();
this.msg = msg;
}
public ResultDataEntity(HttpStatus status) {
this.code = status.value();
}
}

@ -1,43 +0,0 @@
package com.sztzjy.trade.util;
import io.swagger.annotations.ApiModel;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import reactor.core.publisher.Flux;
/**
* 对ResponseEntity做了简单包装
*
*/
@ApiModel("API返回对象")
@Getter
public class ResultEntity<T> extends ResponseEntity<ResultDataEntity<T>> {
public ResultEntity(T data) {
super(new ResultDataEntity<>(HttpStatus.OK, data), HttpStatus.OK);
}
public ResultEntity(HttpStatus status, T data) {
super(new ResultDataEntity<>(status, data), status);
}
public ResultEntity(HttpStatus status, String msg, T data) {
super(new ResultDataEntity<>(status, msg, data), status);
}
public ResultEntity(String msg) {
super(new ResultDataEntity<>(HttpStatus.OK, msg), HttpStatus.OK);
}
public ResultEntity(HttpStatus status, String msg) {
super(new ResultDataEntity<>(status, msg), status);
}
public ResultEntity(HttpStatus status) {
super(new ResultDataEntity<>(status), status);
}
public ResultEntity(HttpStatus status, Flux<String> flow) {
super(new ResultDataEntity<>(status, flow), status);
}
}

@ -1,187 +0,0 @@
package com.sztzjy.trade.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* RSA密码工具
*/
public class RsaUtil {
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRehqqa1eLnTL3BSRq3zmB+Yw7nLAMAZ0G+FpoGP0eFLc0JVC2P2sfkCJJjH2cOmoLcUFjHfDcHzMNyl4wmNTMeXhpvK3v2ha1ufZnGmoMd9d4+1R/t/pZdxXXzkQMN2012X/KIojluEJmrIXLUM0zjOTABSMlTY6TPfSrmuXyGwIDAQAB";
private static final String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJF6GqprV4udMvcFJGrfOYH5jDucsAwBnQb4WmgY/R4UtzQlULY/ax+QIkmMfZw6agtxQWMd8NwfMw3KXjCY1Mx5eGm8re/aFrW59mcaagx313j7VH+3+ll3FdfORAw3bTXZf8oiiOW4QmashctQzTOM5MAFIyVNjpM99Kua5fIbAgMBAAECgYBtr3fNiHOQg6z6jLkBj18nvYTbKW+fDdRcfgKEPFsURCBBw+TQFI7rVFxVwgSvN2ffSrw3RErnXOq8ehl8YK8IfPWleMTXkuGB4QDptou3S7aJ4OlK+p5YOsjVEgnzJ3J7gPUYJRGAX59G+EbEnHKvoTQQjlQ4EaFqp77ba+SN+QJBAM1rre1TSSIuZd7biS4d0znVDRA3Zv/AnpmSaLZODU6p70DnPn3WCf5LNJGsS+Bt1xkq/EHzhpspjy/IfJrZOO8CQQC1S/vrpm8+WsXp8FAlvuQ+UOR1UlMs4WMokVMSOcPcgG2Iab8f1UcD9GptjBjORKiloQBpjG/+FXp2VJPd7yGVAkBvmRRAXoLYwwQs8m+wUhuyy3/xU2ftgaOoItYoVHb+SWvlgrt8eY+sSwcgLM57+rBkx+mLmtWB7i4P84deSKyZAkBYJ5FgnXY8MLFJtoOSRwb+0iC0d4pgKVwo7rkhBJubTYt1KE458V/tqVxS1it9qN8EYowrxpDyUIlSnn+kC9IdAkAH6TkJw2tb4N7rIvcZWjd74EBNQdP0FzvZWU2rE6SGqj87yWDKOKGKWu/hz84DCSkyltII4uB+YasJhsgsJnjb";
public static void main(String[] args) throws Exception {
// System.out.println("\n");
// RsaKeyPair keyPair = generateKeyPair();
// System.out.println("公钥:" + keyPair.getPublicKey());
// System.out.println("私钥:" + keyPair.getPrivateKey());
//System.out.println("\n");
String text1 = encryptByPublicKey("123qwe");
// String text1 = encryptByPrivateKey("123");
System.out.println(text1);
//String text1 = "Bs+MJo8yrGxvwD/G5QGTihU6lh/PjaDKQNxBDs66GQrNXoX0ttzX0grYFxWh8MibHkHikkw8rLsoxXk6bQOzs0eHst/yzj823sTZRDBYdx0oYoEKeda7s7xjYheq4nBnHJn8HVkQbYtchddRRfKVcwyBrUQquhlnzmnfZQ98QiU=";
// String text1 = "CP7GpqY3Tw3DSazqwMHvlRys0/RARfjNL0fgw5IEXEHdZB2K+7G8Ro+wVAm9fiViMba3KcQidG5g244RrpD0HJc/g6PVW4kn81xx1WHjW0SgVUUrsjj4RgHUnUyY/lN0506Ng945svGrGd6pXb+XdtETv4ZKau5EHdR6L/TOR8I=";
// String text1 = "dWRzqk2DC/rm55B+m1Is4mwTnPoc3qoDIZ41Plie6s4vsJwDdHzoWhnIx1pfdFAwEZ3eQ6FV7tcfHJwHDFzNal15e1c2+EFThmWdqdgGNCXttH/c/fsmzaXda5kQRzQxqbhvF96KmJKtshzq23766iLV1Vm3KUsvB6c7bP5yKYc=";
//String text2 = decryptByPrivateKey(text1);
// String text2 = decryptByPrivateKey("R/t6KFVPbCgYSVlYJ4ULuFFwn29/RlLo/IBeXqdtwm0ulIcG0iTDqbCNcQZChE8iN/AL7S4MoGL/HWZArEqAz4BdDmYgLggykX/hhu1fue7tpefyVEnW5TF27rFBCxo1cH0kB1VP0FbwlWHDqG1GCnHOBZbS6j4yUTqu41WBmq4=");
// System.out.println(text2);
}
public static String encryptByPublicKey(String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeBase64String(result);
}
/**
* 私钥加密
*
* @param text 待加密的信息
* @return /
* @throws Exception /
*/
public static String encryptByPrivateKey(String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(result);
}
public static String encryptByPrivateKey(String text,String privateKey) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey1 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey1);
byte[] result = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(result);
}
public static String decryptByPrivateKey(String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
public static String decryptByPublicKey(String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
public static String decryptByPublicKey(String text,String publicKey) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey1 = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey1);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
* 构建RSA密钥对512
*
* @return /
* @throws NoSuchAlgorithmException /
*/
public static RsaKeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RsaKeyPair(publicKeyString, privateKeyString);
}
// 从公钥生成钱包地址
public static String generateBlockchainAddress(String publicKey) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(publicKey.getBytes(StandardCharsets.UTF_8));
// Base58编码是一种常用于区块链地址的编码方式
String blockchainAddress = java.util.Base64.getEncoder().encodeToString(hash);
return blockchainAddress;
}
public static String calculateMD5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashBytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public static String formatHash(String hash) {
StringBuilder formattedHash = new StringBuilder();
for (int i = 0; i < hash.length(); i += 2) {
formattedHash.append(hash.substring(i, i + 2));
if (i < hash.length() - 2) {
formattedHash.append("-");
}
}
return formattedHash.toString();
}
/**
* RSA密钥对对象
*/
public static class RsaKeyPair {
private final String publicKey;
private final String privateKey;
public RsaKeyPair(String publicKey, String privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
}
}

@ -1,23 +0,0 @@
package com.sztzjy.trade.util;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 异常工具
*
* 陈沅
*/
public class ThrowableUtil {
/**
* 获取堆栈信息
*/
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
throwable.printStackTrace(pw);
return sw.toString();
}
}
}

@ -1,254 +0,0 @@
package com.sztzjy.trade.util;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.sztzjy.trade.config.security.JwtUser;
import com.sztzjy.trade.config.security.TokenProvider;
import org.checkerframework.checker.units.qual.A;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TzApi {
private final static String API_URL = "http://Cloud.sztzjy.com";
private final static String NEW_API_URL = "http://zycloud.sztzjy.com:9090";
// private final static String NEW_API_URL = "http://localhost:9090";
private final static String LOGIN_URL = NEW_API_URL + "/server/account/findByUsernameAndPwd.json";
private final static String GET_CLASS = NEW_API_URL + "/server/account/findClassesBySchoolId.json";
private final static String GET_MAJOR = NEW_API_URL + "/server/account/findMajorsBySchoolId.json";
private final static String GET_CLASS_BY_MAJOR = NEW_API_URL + "/server/account/getClassListByMajorId.json";
private final static String GET_STUDENT_BY_ClALL = NEW_API_URL + "/server/account/getStudentsByClassId.json";
private final static String GET_STUDENT_BY_KEYWORD = NEW_API_URL + "/server/account/getStudentByKeyword.json";
private final static String PAGE_STUDENT_BY_KEYWORD = NEW_API_URL + "/server/account/pagedListStudentByClassId.json";
// 智云接口调用token加入缓存,默认1小时过期
private static CacheProvider cacheProvider = new CacheProvider(3600*12, 6000);
public static JwtUser foreignExchangeTradingLogin(String userName, String password) {
try {
String requestBody = "username=" + URLEncoder.encode(userName, "UTF8") +
"&password=" + URLEncoder.encode(password, "UTF8");
JSONObject object = HttpUtils.sendPost(
LOGIN_URL,
requestBody,
HttpUtils.CONTENT_TYPE_APPLICATION_X_WWW_FORM_URLENCODED,
null);
if (object == null) {
throw new IllegalArgumentException("登录失败");
}
int code = object.getInt("statusCode");
if (code != HttpStatus.HTTP_OK) {
throw new IllegalArgumentException("登录失败");
}
JSONObject jsonObject = object.getJSONObject("respString");
JSONObject dataObject = jsonObject.getJSONObject("data");
JwtUser user = new JwtUser();
user.setUserId(dataObject.getStr("userid"));
user.setName(dataObject.getStr("name"));
String roleName = dataObject.getStr("rolename");
Integer roleId = roleName.equals("学生") ? 4 : 3;
user.setRoleId(roleId);
user.setSchoolId(dataObject.getInt("schoolid"));
if(roleId==4){
user.setClassId(dataObject.getInt("classid"));
user.setClassName(dataObject.getStr("classname"));
}
// user.setMajorId(dataObject.getStr("majorid"));
user.setMajorName(dataObject.getStr("majorname"));
user.setSchoolName(dataObject.getStr("schoolname"));
user.setCollegeId(dataObject.getInt("collegeid"));
user.setCollegeName(dataObject.getStr("collegename"));
user.setUsername(userName);
user.setPassword(password);
return user;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Map<String, Object>> GetClassBySchoolIdForForeignExchangeTrading(JwtUser user) {
String token = getToken(user);
String url = GET_CLASS+"?schoolId=" + user.getSchoolId();
return getDataFromApi(url, token);
}
public static List<Map<String, Object>> GetMajorIdForForeignExchangeTrading(JwtUser user) {
String token = getToken(user);
String url = GET_MAJOR+"?schoolId=" + user.getSchoolId();
return getDataFromApi(url, token);
}
public static List<Map<String, Object>> GetClassByMajorIdForForeignExchangeTrading(JwtUser user, String majorId) {
String token = getToken(user);
String url = GET_CLASS_BY_MAJOR + "?majorId=" + majorId;
return getDataFromApi(url, token);
}
public static List<Map<String, Object>> GetStudentInfoByClassIdForForeignExchangeTrading(String classIds, JwtUser user) {
String token = getToken(user);
String url = GET_STUDENT_BY_ClALL + "?classList=" + classIds;
return getStudentsFromApi(url, token);
}
public static List<Map<String, Object>> GetStudentInfoByKeywordForForeignExchangeTrading(JwtUser user, String keyword) throws UnsupportedEncodingException {
String token = getToken(user);
String url = GET_STUDENT_BY_KEYWORD + "?keyword=" + URLEncoder.encode(keyword,"UTF-8") +"&schoolId="+user.getSchoolId();
return getStudentsFromApi(url, token);
}
public static PageInfo<Map<String, Object>> PagedListStudentInfoByClassIdForForeignExchangeTrading(JwtUser user, String classIds, int page, int size) {
String token = getToken(user);
String url = PAGE_STUDENT_BY_KEYWORD + "?classList=" + classIds + "&page=" + page + "&size=" + size;
return getPageDataFromApi(url, token);
}
public static List<Map<String, Object>> getDataFromApi(String url, String token) {
List<Map<String, Object>> dataList = new ArrayList<>();
try {
String responseBody = HttpUtils.sendGet(url, token);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
JsonNode dataNode = jsonNode.get("data");
if (dataNode.isArray()) {
for (JsonNode node : dataNode) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", node.get("classid").asText());
dataMap.put("name", node.get("classname").asText());
dataList.add(dataMap);
}
}
} catch (Exception e) {
throw new IllegalArgumentException("获取数据异常");
}
return dataList;
}
public static List<Map<String, Object>> getStudentsFromApi(String url, String token) {
List<Map<String, Object>> dataList = new ArrayList<>();
try {
String responseBody = HttpUtils.sendGet(url, token);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
JsonNode dataNode = jsonNode.get("data");
if (dataNode.isArray()) {
for (JsonNode node : dataNode) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("userId", node.get("userid").asText());
dataMap.put("studentId", node.get("studentid").asText());
dataMap.put("name", node.get("name").asText());
dataMap.put("className", node.get("classname").asText());
dataMap.put("classId", node.get("classid").asText());
dataMap.put("studentNo", node.get("studentno").asText());
dataMap.put("schoolName", node.get("schoolname").asText());
dataList.add(dataMap);
}
}
} catch (Exception e) {
throw new IllegalArgumentException("获取数据异常");
}
return dataList;
}
public static PageInfo<Map<String, Object>> getPageDataFromApi(String url, String token) {
PageInfo pageInfo = new PageInfo();
try {
String responseBody = HttpUtils.sendGet(url, token);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(responseBody);
JsonNode resultNode = jsonNode.get("content");
if (resultNode != null) {
pageInfo.setPages(resultNode.get("totalPage").asInt());
pageInfo.setTotal(resultNode.get("totalRow").asInt());
pageInfo.setPageNum(resultNode.get("pageNumber").asInt());
pageInfo.setPageSize(resultNode.get("pageSize").asInt());
JsonNode retNode = resultNode.get("list");
List<Map<String,Object>> dataList = new ArrayList<>();
if(retNode.isArray()){
for(JsonNode node: retNode){
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("id", node.get("userid").asText());
dataMap.put("name", node.get("name").asText());
dataMap.put("studentNo", node.get("studentno").asText());
dataMap.put("className", node.get("classname").asText());
dataMap.put("majorName", node.get("majorname").asText());
dataMap.put("classId", node.get("classid").asText());
dataList.add(dataMap);
}
}
pageInfo.setList(dataList);
}
} catch (Exception e) {
throw new IllegalArgumentException("获取数据异常");
}
return pageInfo;
}
private static String getToken(JwtUser user) {
try {
String access_token;
access_token = (String) cacheProvider.get(user.getUserId() + user.getUsername());
if (StringUtils.hasText(access_token)) {
System.out.println("-------->>> 从缓存中获取 access_token【成功】");
} else {
access_token = TokenProvider.createZHIYUNToken(user);
cacheProvider.put(user.getUserId() + user.getUsername(), access_token);
System.out.println("-------->>> 从远程获取 access_token【成功】");
}
return access_token;
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public static void main(String[] args) {
JwtUser user = new JwtUser();
user.setUserId("486");
user.setRoleId(3);
user.setUsername("tzt006");
user.setSchoolId(1);
user.setSchoolName("天择大学");
user.setCollegeId(1);
user.setCollegeName("演示学院");
user.setMajorId(1);
user.setMajorName("产品演示专业");
PagedListStudentInfoByClassIdForForeignExchangeTrading(user, "7", 1, 10);
}
}

@ -1,99 +0,0 @@
package com.sztzjy.trade.util.encryption;
import cn.hutool.crypto.digest.DigestUtil;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Base64;
@Component
public class ShaUtil {
private final String SHA_1 = "SHA-1";
private final String SHA_224 = "SHA-224";
private final String SHA_256 = "SHA-256";
private final String SHA_384 = "SHA-384";
private final String SHA_512 = "SHA-512";
private final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public String getSHA1(String painText, boolean uppercase) {
return getSha(painText, SHA_1, uppercase);
}
public String getSHA224(String painText, boolean uppercase) {
return getSha(painText, SHA_224, uppercase);
}
public String getSHA256(String painText, boolean uppercase) {
return getSha(painText, SHA_256, uppercase);
}
public String getSHA384(String painText, boolean uppercase) {
return getSha(painText, SHA_384, uppercase);
}
public String getSHA512(String painText, boolean uppercase) {
return getSha(painText, SHA_512, uppercase);
}
/**
* 利用Java原生摘要实现SHA加密(支持大小写,默认小写)
*
* @param plainText 要加密的数据
* @param algorithm 要使用的算法(SHA-1,SHA-2224,SHA-256,SHA-384,SHA-512)
* @param uppercase 是否转为大写
* @return
*/
private String getSha(String plainText, String algorithm, boolean uppercase) {
//输入的字符串转换成字节数组
byte[] bytes = plainText.getBytes(StandardCharsets.UTF_8);
MessageDigest messageDigest;
try {
//获得SHA转换器
messageDigest = MessageDigest.getInstance(algorithm);
//bytes是输入字符串转换得到的字节数组
messageDigest.update(bytes);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA签名过程中出现错误,算法异常");
}
//转换并返回结果,也是字节数组,包含16个元素
byte[] digest = messageDigest.digest();
//字符数组转换成字符串返回
String result = byteArrayToHexString(digest);
//转换大写
return uppercase ? result.toUpperCase() : result;
}
/**
* 将字节数组转为16进制字符串
*
* @param bytes 要转换的字节数组
* @return
*/
private String byteArrayToHexString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
//java.lang.Integer.toHexString() 方法的参数是int(32位)类型,
//如果输入一个byte(8位)类型的数字,这个方法会把这个数字的高24为也看作有效位,就会出现错误
//如果使用& 0XFF操作,可以把高24位置0以避免这样错误
String temp = Integer.toHexString(b & 0xFF);
if (temp.length() == 1) {
//1得到一位的进行补0操作
builder.append("0");
}
builder.append(temp);
}
return builder.toString();
}
}

@ -1,185 +0,0 @@
//package com.sztzjy.trade.util.excel;
//
//
//import cn.hutool.core.util.IdUtil;
//import com.alibaba.excel.context.AnalysisContext;
//import com.alibaba.excel.metadata.data.ReadCellData;
//import com.alibaba.excel.read.listener.ReadListener;
//import com.alibaba.excel.util.ConverterUtils;
//import com.alibaba.excel.util.ListUtils;
//
//
//import lombok.extern.slf4j.Slf4j;
//
//import java.util.*;
//
//
//// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去
//@Slf4j
//
//public class DemoDataListener implements ReadListener<StuLearningAssessment> {
//
//
// /**
// * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收
// */
// private static final int BATCH_COUNT = 200;
// /**
// * 缓存的数据
// */
// private List<StuLearningAssessment> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
// /**
// * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
// */
// private StuLearningAssessmentMapper demoDAO;
// private String userId;
// private String schoolId;
// private String schoolName;
// // 存储错误信息
// private List<String> errorList = new ArrayList<>();
//
// List<String> list = new ArrayList<String>();
//
// /**
// * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
// *
// * @param demoDAO
// */
// public DemoDataListener(StuLearningAssessmentMapper demoDAO, String userId, String schoolId,String schoolName) {
// this.schoolId = schoolId;
// this.userId = userId;
// this.demoDAO = demoDAO;
// this.schoolName = schoolName;
// }
//
//
// /**
// * 这里会一行行的返回头
// *
// * @param headMap
// * @param context
// */
// @Override
// public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
// // log.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
//
// Map<Integer, String> integerStringMap = ConverterUtils.convertToStringMap(headMap, context);
//
// //log.info("转换解析到的一条头数据:{}", integerStringMap);
//
//
// Set<Integer> integers = integerStringMap.keySet();
// for (Integer integer : integers) {
// list.add(integerStringMap.get(integer));
// }
//
//
// // 如果想转成成 Map<Integer,String>
// // 方案1: 不要implements ReadListener 而是 extends AnalysisEventListener
// // 方案2: 调用 ConverterUtils.convertToStringMap(headMap, context) 自动会转换
// }
//
// /**
// * 这个每一条数据解析都会来调用
// *
// * @param data one row value. Is is same as {@link AnalysisContext#readRowHolder()}
// * @param context
// */
// @Override
// public void invoke(StuLearningAssessment data, AnalysisContext context) {
//
//
// StringBuilder errorMsg = new StringBuilder();
// boolean isValid = true;
//
// // 校验 data 中的字段,:
//// if (data.getAttributionChapter() == null || data.getAttributionChapter().isEmpty()) {
//// isValid = false;
//// errorMsg.append("模块为空, ");
//// }
//
// if (data.getAttributionChapter() == null || data.getAttributionChapter().isEmpty()) {
// isValid = false;
// errorMsg.append("模块为空, ");
// }
//
// if (data.getTopicType() == null || data.getTopicType().isEmpty()) {
// isValid = false;
// errorMsg.append("题型为空, ");
// }
//
// if (data.getTopicName() == null || data.getTopicName().isEmpty()) {
// isValid = false;
// errorMsg.append("题干为空, ");
// }
//
//
// if (data.getTopicScore() == null ) {
// isValid = false;
// errorMsg.append("分值为空或不是数字, ");
// }
//
// if (data.getAnswer() == null || data.getAnswer().isEmpty()) {
// isValid = false;
// errorMsg.append("答案为空, ");
// }
//
// if (!isValid) {
// // 如果校验失败,将错误信息记录下来
// errorList.add("第" + (context.readRowHolder().getRowIndex() + 1) +"行"+ ": " + errorMsg.toString());
// } else {
// cachedDataList.add(data);
// if (cachedDataList.size() >= BATCH_COUNT) {
// saveData();
// cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
// }
// }
//
//
//
//// //log.info("解析到一条数据:{}", JSON.toJSONString(data));
//// cachedDataList.add(data);
//// // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
//// if (cachedDataList.size() >= BATCH_COUNT) {
//// saveData();
//// // 存储完成清理 list
//// cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
//// }
// }
//
// /**
// * 所有数据解析完成了 都会来调用
// *
// * @param context
// */
// @Override
// public void doAfterAllAnalysed(AnalysisContext context) {
//
// saveData();
// log.info("所有数据解析完成!" + ",当前线程:" + Thread.currentThread().getName());
//
// }
//
// /**
// * 加上存储数据库
// */
// private void saveData() {
//
// //数据量比较小遍历导入
//
// cachedDataList.forEach(item -> {
// item.setTopicId(IdUtil.simpleUUID() + System.currentTimeMillis());
// item.setSchoolId(schoolId);
// item.setUploadUser(userId);
// item.setReason(schoolName);
// demoDAO.insertSelective(item);
// });
//
//
// }
//
// // 添加一个方法来获取错误列表
// public List<String> getErrorList() {
// return errorList;
// }
//}

@ -1,47 +0,0 @@
package com.sztzjy.trade.util.excel;
import lombok.Getter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Excel通用数据对象封装 若需要复杂表头和更多样式等、需定义导出模板
*/
@Getter
public class ExcelData {
private List<List<String>> contents;
private ExcelData() {
this.contents = new ArrayList<>();
}
public ExcelData addRow(List<Object> rowData) {
List<String> dataList = rowData.stream().map(i -> i == null ? null : i.toString()).collect(Collectors.toList());
this.contents.add(dataList);
return this;
}
/**
* 创建无标题文档
*
* @return /
*/
public static ExcelData create() {
return ExcelData.create(null);
}
/**
* 创建有标题文档
*
* @param titleList 内容|标题
* @return 数据对象
*/
public static ExcelData create(List<String> titleList) {
ExcelData excelData = new ExcelData();
if (titleList != null && !titleList.isEmpty())
excelData.contents.add(titleList);
return excelData;
}
}

@ -1,35 +0,0 @@
package com.sztzjy.trade.util.excel;
import com.sztzjy.trade.annotation.ExcelValid;
import java.lang.reflect.Field;
import java.util.Objects;
public class ExcelImportValid {
/**
* Excel导入字段校验
* @param object 校验的JavaBean 其属性须有自定义注解
*/
public static String valid(Object object) {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
//设置可访问
field.setAccessible(true);
//属性的值
Object fieldValue = null;
try {
fieldValue = field.get(object);
} catch (IllegalAccessException e) {
throw new RuntimeException(field.getAnnotation(ExcelValid.class).message());
// return field.getAnnotation(ExcelValid.class).message();
}
//是否包含必填校验注解
boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
if (isExcelValid && Objects.isNull(fieldValue)) {
//throw new RuntimeException(field.getAnnotation(ExcelValid.class).message());
return field.getAnnotation(ExcelValid.class).message();
}
}
return "成功";
}
}

@ -1,39 +0,0 @@
package com.sztzjy.trade.util.excel;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Arrays;
public class ExcelProvider {
private static Logger logger = LoggerFactory.getLogger(ExcelProvider.class);
/**
* 简单通用excel导出 若需要复杂表头和更多样式等、需定义导出模板
* 输出无样式的excel
*
* @param data 待导出的数据
*/
public static void SimpleExcelExport(ExcelData data, OutputStream out){
Assert.notNull(data, "无可导出的数据");
Assert.notEmpty(data.getContents(), "无可导出的数据");
ExcelWriter bigWriter = ExcelUtil.getBigWriter();
bigWriter.write(data.getContents());
bigWriter.flush(out,true);
}
public static void main(String[] args) throws Exception {
ExcelData excelData = ExcelData.create(Arrays.asList("t1","t2"))
.addRow(Arrays.asList("11","12"))
.addRow(Arrays.asList("21","22"));
FileOutputStream fileOut = new FileOutputStream("D:/111.xlsx");
ExcelProvider.SimpleExcelExport(excelData,fileOut);
fileOut.close();
}
}

@ -1,130 +0,0 @@
package com.sztzjy.trade.util.excel;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
/*
* @author xcj
* @Date 2023/10/10
*/
public class FilePortUtil {
private static final Logger log = LoggerFactory.getLogger(FilePortUtil.class);
/**
* 导出功能
* 注意:泛型T类字段名和containBean集合里字段名字的一致性
*
* @param response
* @param title 表名
* @param headers 表头
* @param list 数据集
* @param containBean 数据集类型字段
* @param <T>
* @throws Exception
*/
public static <T> void exportExcel(HttpServletResponse response, String title, String[] headers, List<T> list, List<String> containBean) throws Exception {
HSSFWorkbook workbook = null;
try {
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
HSSFRow row = sheet.createRow(0);
/*创建第一行表头*/
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
Iterator<T> it = list.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
/*反射得到字段*/
Field[] fields = t.getClass().getDeclaredFields();
/*如果需要匹配*/
if (CollectionUtils.isNotEmpty(containBean)) {
for (int j = 0; j < containBean.size(); j++) {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (!field.getName().equals(containBean.get(j)))
continue;
/*给每一列set值*/
setCellValue(t, field, row, j);
}
}
} else {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
setCellValue(t, field, row, i);
}
}
}
/*application/vnd.ms-excel告诉浏览器要下载的是个excel*/
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
/*请求头设置,Content-Disposition为下载标识,attachment标识以附件方式下载*/
response.addHeader("Content-Disposition", "attachment;filename=" + new String((title).getBytes(), "ISO8859-1") + ".xls");
workbook.write(response.getOutputStream());
} finally {
if (workbook != null) {
workbook.close();
}
}
}
/**
* 设置每一行中的列
*
* @param t
* @param field
* @param row
* @param index
* @param <T>
*/
private static <T> void setCellValue(T t, Field field, HSSFRow row, int index) {
HSSFCell cell = row.createCell(index);
Object value = invoke(t, field);
String textValue = null;
if (value != null) {
if (value instanceof Date) {
Date date = (Date) value;
textValue = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
} else {
textValue = value.toString();
}
}
if (textValue != null) {
cell.setCellValue(textValue);
}
}
/**
* 反射映射数据集字段
*
* @param t
* @param field
* @param <T>
* @return
*/
private static <T> Object invoke(T t, Field field) {
try {
String fieldName = field.getName();
PropertyDescriptor pd = new PropertyDescriptor(fieldName, t.getClass());
Method method = pd.getReadMethod();
return method.invoke(t);
} catch (Exception e) {
return null;
}
}
}

@ -1,149 +0,0 @@
package com.sztzjy.trade.util.excel;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
@Component
public class ImportExcelUtil {
private final static String excel2003L = ".xls"; //2003- 版本的excel
private final static String excel2007U = ".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List<List<Object>>对象
*
* @param in,fileName
* @return
* @throws Exception
*/
public static List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception {
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = ImportExcelUtil.getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null) {
continue;
}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum() + 1; j++) {
row = sheet.getRow(j);
if (row == null || row.getFirstCellNum() == j) {
continue;
}
//遍历所有的列
List<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(ImportExcelUtil.getCellValue(cell));
}
list.add(li);
}
}
// work.close();
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
*
* @param inStr,fileName
* @return
* @throws Exception
*/
public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inStr); //2003-
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inStr); //2007+
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
*
* @param cell
* @return
*/
public static Object getCellValue(Cell cell) {
Object val = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
// DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
if (cell != null) {
if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) {
val = cell.getNumericCellValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
} else {
if ((Double) val % 1 > 0) {
val = new BigDecimal(val.toString());
} else {
val = new DecimalFormat("0").format(val);
}
}
} else if (cell.getCellTypeEnum() == CellType.STRING) {
val = cell.getStringCellValue();
} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
val = cell.getBooleanCellValue();
} else if (cell.getCellTypeEnum() == CellType.ERROR) {
val = cell.getErrorCellValue();
}
// switch (cell.getCellType()) {
// case Cell.CELL_TYPE_STRING:
// value = cell.getRichStringCellValue().getString();
// break;
// case Cell.CELL_TYPE_NUMERIC:
// if("General".equals(cell.getCellStyle().getDataFormatString())){
// value = df.format(cell.getNumericCellValue());
// }
// else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
// value = sdf.format(cell.getDateCellValue());
// }
// else{
// value = sdf.format(cell.getDateCellValue());
// }
// break;
// case Cell.CELL_TYPE_BOOLEAN:
// value = cell.getBooleanCellValue();
// break;
// case Cell.CELL_TYPE_BLANK:
// value = "";
// break;
// default:
// break;
// }
}
return val;
}
}

@ -1,87 +0,0 @@
package com.sztzjy.trade.util.file;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
/**
* 文件上传下载接口定义
*
* @author 陈沅
*/
public interface IFileUtil {
/**
* 从http请求上传文件
*
* @param file form传参http文件对象
* @return 返回文件在服务器上保存的相对路径
*/
String upload(MultipartFile file);
/**
* 根据文件流上传文件
*
* @param objectName 指定文件名(带扩展名)
* @param fileIn 文件流
* @return 返回文件在服务器上保存的相对路径
*/
String upload(String objectName, InputStream fileIn);
/**
* 删除服务器上的一个文件
*
* @param path 文件在服务器上保存的相对路径
* @return 返回true则表示删除成功
*/
boolean remove(String path);
/**
* 下载文件流,指定文件名
*
* @param response
* @param fileName 指定下载文件名称
* @param filePath 文件保存的相对路径
*/
void download(HttpServletResponse response, String fileName, String filePath);
/**
* 下载文件流,不指定文件名
*
* @param response
* @param filePath 文件保存的相对路径
*/
void download(HttpServletResponse response, String filePath);
/**
* 相对路径
*
* @param relativePath 文件保存的相对路径
* @return 文件保存的绝对路径
*/
String getFullPath(String relativePath);
/**
* 获取文件后缀名
*
* @param fileName 文件名称
* @return suffix
*/
String getSuffix(String fileName);
/**
* 获取文件存储至磁盘的相对路径
*
* @param fileName 文件名
* @param suffix 动态拼接的文件后缀,若该值为空则不拼接
* @return 相对路径
*/
String getDiskRelativePath(String fileName, String suffix);
}

@ -1,176 +0,0 @@
package com.sztzjy.trade.util.file;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class LocalFileUtil implements IFileUtil{
private final static List<String> excludeSp = Arrays.asList("exe", "bin", "sh");
private final String localPath;
public LocalFileUtil(String localPath) {
this.localPath = localPath;
}
@Override
public String upload(MultipartFile file) {
return upload(null, file);
}
@Override
public String upload(String objectName, InputStream fileIn) {
Assert.notNull(fileIn, "文件不能为空");
Assert.hasText(objectName, "文件名为空");
Assert.isTrue(objectName.lastIndexOf(".") > 0, "文件名称需携带扩展后缀");
FileOutputStream out = null;
try {
String relativePath = getDiskRelativePath(objectName, null);
File file = new File(getFullPath(relativePath));
file.getParentFile().mkdirs();
out = new FileOutputStream(file);
byte[] buff = new byte[4096];
int len;
while ((len = fileIn.read(buff)) != -1) {
out.write(buff, 0, len);
}
out.flush();
return relativePath;
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException("上传文件失败,IO错误");
} finally {
try {
fileIn.close();
if (out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public boolean remove(String path) {
if (!StringUtils.hasText(path)) return false;
File file = new File(getFullPath(path));
if (!file.exists()) return false;
return file.delete();
}
@Override
public void download(HttpServletResponse response, String fileName, String relativePath) {
Assert.hasText(relativePath, "路径为空");
System.out.println("------------------------------------" + getFullPath(relativePath));
File file = new File(getFullPath(relativePath));
Assert.isTrue(file.exists(), "附件不存在");
String sp = relativePath.substring(relativePath.lastIndexOf(".") + 1);
Assert.isTrue(!excludeSp.contains(sp.toLowerCase()), "文件类型错误");
if (!StringUtils.hasText(fileName)) {
fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
}
InputStream fis = null;
try {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode((fileName + "." + sp), CharsetUtil.UTF_8));
fis = new BufferedInputStream(Files.newInputStream(file.toPath()));
response.addHeader("Content-Length", String.valueOf(fis.available()));
byte[] buff = new byte[4096];
int len;
while ((len = fis.read(buff)) != -1) {
response.getOutputStream().write(buff, 0, len);
}
} catch (Exception e) {
throw new IllegalArgumentException("下载文件失败: " + e.getMessage());
} finally {
try {
if (fis != null) fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void download(HttpServletResponse response, String relativePath) {
download(response, null, relativePath);
}
@Override
public String getFullPath(String relativePath) {
if (!relativePath.startsWith("/")) {
relativePath = "/" + relativePath;
}
return localPath + relativePath;
}
@Override
public String getSuffix(String fileName) {
Assert.hasText(fileName, "文件名不存在!");
if (fileName.lastIndexOf(".") < 0) {
return null;
}
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
public String upload(String fileName, MultipartFile file) {
return upload(fileName, file, null);
}
@Override
public String getDiskRelativePath(String fileName, String suffix) {
Calendar c = Calendar.getInstance();
Date d = new Date();
c.setTime(d);
String year = Integer.toString(c.get(Calendar.YEAR));
String month = Integer.toString(c.get(Calendar.MONTH) + 1);
String day = Integer.toString(c.get(Calendar.DATE));
StringBuilder path = new StringBuilder();
path.append("/").append(year)
.append("/").append(month)
.append("/").append(day)
.append("/").append(fileName);
if (StringUtils.hasText(suffix)) path.append(".").append(suffix);
return path.toString();
}
private String upload(String fileName, MultipartFile file, String relativePath) {
Assert.isTrue(!file.isEmpty(), "文件不存在");
String originalFilename = file.getOriginalFilename();
if (fileName == null) fileName = IdUtil.simpleUUID();
String sp = getSuffix(originalFilename);
Assert.notNull(sp, "文件类型错误");
Assert.isTrue(!excludeSp.contains(sp.toLowerCase()), "文件类型错误");
try {
String filePath;
if (relativePath == null) {
filePath = getDiskRelativePath(fileName, sp);
} else {
relativePath = relativePath.endsWith("/") ? relativePath : relativePath + "/";
filePath = relativePath + fileName + "." + sp;
}
File destFile = new File(getFullPath(filePath));
destFile.getParentFile().mkdirs();
file.transferTo(destFile);
return filePath;
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("上传文件失败,FileNotFound错误");
} catch (IOException e) {
throw new IllegalArgumentException("上传文件失败,IO错误");
}
}
}

@ -1,194 +0,0 @@
package com.sztzjy.trade.util.pdfUtils;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import java.awt.*;
@Component
public class HeaderAndFooterEvent extends PdfPageEventHelper {
public static PdfTemplate tpl = null;
public static boolean PAGE_NUMBER = false;
public static Rectangle rect = PageSize.A4;
private static Font font;
public static String HeaderFooterFontName = "黑体";
public static int HeaderFooterFontSize = 10;
public static Color HeaderFooterFontColor = Color.BLACK;
public static String HeaderLeft;
public static String HeaderRight;
public static String FooterLeft;
public static String FooterRight;
public static void SetPageSize(String type) {
switch (type.trim()) {
case "A4":
rect = PageSize.A4;
break;
case "A8":
rect = PageSize.A8;
break;
}
}
@SneakyThrows
public static void SetFont(BaseColor color, String fontName, float size, int style) {
BaseFont baseFont;
// String FONT_PATH="C:/Windows/Fonts/";
String FONT_PATH="/usr/share/fonts/";
switch (fontName) {
case "黑体":
// baseFont = BaseFont.createFont("SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
baseFont = BaseFont.createFont(FONT_PATH+"simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
break;
case "华文中宋":
// baseFont = BaseFont.createFont("STZHONGS.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
break;
case "宋体":
// baseFont = BaseFont.createFont("SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
break;
default:
// baseFont = BaseFont.createFont("SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
break;
}
font = new Font(baseFont, size, style,color);
}
@Override
public void onEndPage(PdfWriter writer, Document document) {
if (PAGE_NUMBER) {
Font HeaderFooterFont = new Font(font.getBaseFont(), HeaderFooterFontSize, Font.NORMAL);
Phrase header_left = new Phrase(HeaderLeft, HeaderFooterFont);
Phrase header_right = new Phrase(HeaderRight, HeaderFooterFont);
Phrase footer_left = new Phrase(FooterLeft, HeaderFooterFont);
Phrase footer_center = new Phrase("第" + (writer.getPageNumber()) + "页/共 页", HeaderFooterFont);
Phrase footer_right = new Phrase(FooterRight, HeaderFooterFont);
PdfContentByte cb = writer.getDirectContent();
cb.addTemplate(tpl, document.right() - 290 + document.leftMargin(), document.bottom() - 15);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header_right,
document.right() - 50 + document.leftMargin(), document.top() + 15, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header_left,
document.right() - 500 + document.leftMargin(), document.top() + 15, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer_left,
document.right() - 535 + document.leftMargin(), document.bottom() - 15, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer_center,
document.right() - 300 + document.leftMargin(), document.bottom() - 15, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer_right,
document.right() - 80 + document.leftMargin(), document.bottom() - 15, 0);
}
}
@Override
public void onStartPage(PdfWriter writer, Document document) {
if (PAGE_NUMBER) {
writer.setPageCount(writer.getPageNumber());
}
}
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
tpl.beginText();
tpl.setFontAndSize(font.getBaseFont(), HeaderFooterFontSize);
tpl.showText(String.valueOf(writer.getPageNumber()));
tpl.endText();
tpl.closePath();
}
public static Paragraph AddParagraph(String content, int Alignment, float SpacingAfter, float SpacingBefore, float MultipliedLeading) {
Paragraph pra = new Paragraph(content, font);
pra.setAlignment(Alignment);
pra.setSpacingAfter(SpacingAfter);
pra.setSpacingBefore(SpacingBefore);
// pra.setMultipliedLeading(MultipliedLeading);
return pra;
}
public static Paragraph AddParagraph(String content, int Alignment, float MultipliedLeading) {
Paragraph pra = new Paragraph(content, font);
pra.setAlignment(Alignment);
// pra.setMultipliedLeading(MultipliedLeading);
return pra;
}
public static Paragraph AddParagraph(String content, int Alignment) {
Paragraph pra = new Paragraph(content, font);
pra.setAlignment(Alignment);
return pra;
}
public static Paragraph AddParagraph(String content) {
Paragraph pra = new Paragraph(content, font);
return pra;
}
public static PdfPCell AddCell(String content, int horizontalAlignment, int verticalAlignment, float borderWidth) {
PdfPCell cell = new PdfPCell(new Phrase(content, font));
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
cell.setBorderWidth(borderWidth);
return cell;
}
public static PdfPCell AddCell(String content, int horizontalAlignment, int verticalAlignment) {
PdfPCell cell = new PdfPCell(new Phrase(content, font));
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
return cell;
}
public static PdfPCell AddCell(String content, int horizontalAlignment) {
PdfPCell cell = new PdfPCell(new Phrase(content, font));
cell.setHorizontalAlignment(horizontalAlignment);
return cell;
}
public static PdfPCell AddCell(String content) {
PdfPCell cell = new PdfPCell(new Phrase(content, font));
return cell;
}
public static PdfPCell AddCell(Image image, int horizontalAlignment, int verticalAlignment, float borderWidth) {
PdfPCell cell = new PdfPCell(image);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
cell.setBorderWidth(borderWidth);
return cell;
}
public static PdfPCell AddCell(Image image, int horizontalAlignment, int verticalAlignment) {
PdfPCell cell = new PdfPCell(image);
cell.setHorizontalAlignment(horizontalAlignment);
cell.setVerticalAlignment(verticalAlignment);
return cell;
}
public static PdfPCell AddCell(Image image, int horizontalAlignment) {
PdfPCell cell = new PdfPCell(image);
cell.setHorizontalAlignment(horizontalAlignment);
return cell;
}
public static PdfPCell AddCell(Image image) {
PdfPCell cell = new PdfPCell(image);
return cell;
}
}

@ -1,538 +0,0 @@
package com.sztzjy.trade.util.pdfUtils;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.xslf.usermodel.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.sztzjy.trade.util.pdfUtils.PDFConvertUtil.TypeEnum.*;
/**
* 功能描述: <br>
* PDF 转换工具
*
* @Author: lx
* @Date: 2022/12/13 16:26
*/
public final class PDFConvertUtil {
final private static Map<TypeEnum, List<String>> types = new HashMap<>();
public static enum TypeEnum {
WORD, EXCEL, PPT, PPTX, IMG, OTHER
}
static {
types.put(WORD, Arrays.asList("DOC", "DOCX"));
types.put(EXCEL, Arrays.asList("XLS", "XLSX"));
types.put(PPT, Arrays.asList("PPT"));
types.put(PPTX, Arrays.asList("PPTX"));
// types.put(IMG, Arrays.asList("JPEG", "JPG", "PNG"));
types.put(OTHER, Arrays.asList("OOXML", "RTF HTML", "OpenDocument", "EPUB", "XPS", "SWF"));
}
/**
* @param inputStream 源文件输入流
* @param outputStream pdf文件输出流
**/
public static boolean imgToPdf(InputStream inputStream, OutputStream outputStream) {
Document document = null; PdfWriter pdfWriter = null;
try {
//此处处理乱码和小方块
//如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
//指定文件库内容路径
FontSettings.getDefaultInstance().setFontsFolders(
new String[] {"/usr/share/fonts", "/usr/share/fonts/chinese"}
, true);
// 创建文档,设置PDF页面的大小 A2-A9, 个人觉得A3最合适
document = new Document(PageSize.A6, 0, 0, 0, 0);
// 新建pdf文档,具体逻辑看.getInstance方法
pdfWriter = PdfWriter.getInstance(document, outputStream);
document.open();
document.newPage();
// 将文件流转换为字节流,便于格式转换
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int length = 0 ;
while (-1 != (length = bufferedInputStream.read(bytes))) {
byteArrayOutputStream.write(bytes, 0, length);
}
// 处理img图片
Image image = Image.getInstance(byteArrayOutputStream.toByteArray());
float height = image.getHeight();
float width = image.getWidth();
float percent = 0.0f;
// 设置像素或者长宽高,将会影响图片的清晰度,因为只是对图片放大或缩小
if (height > width) {
// A4 - A9
percent = PageSize.A6.getHeight() / height * 100;
} else {
percent = PageSize.A6.getWidth() / width * 100;
}
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent);
// 将图片放入文档中,完成pdf转换
document.add(image);
System.out.println("image转换完毕");
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
close(document, pdfWriter);
closeOutput(outputStream);
closeInput(inputStream);
}
return true;
}
/**
* @param inputStream 源文件输入流
* @param outputStream pdf文件输出流
**/
public static boolean wordToPdfByAspose(InputStream inputStream, OutputStream outputStream) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return false;
}
try {
//此处处理乱码和小方块
//如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
//指定文件库内容路径
FontSettings.getDefaultInstance().setFontsFolders(
new String[] {"/usr/share/fonts", "/usr/share/fonts/win"}
, true);
// 将源文件保存在com.aspose.words.Document中,具体的转换格式依靠里面的save方法
com.aspose.words.Document doc = new com.aspose.words.Document(inputStream);
// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换
doc.save(outputStream, SaveFormat.PDF);
System.out.println("word转换完毕");
} catch (Exception e) {
e.printStackTrace();
return false;
}finally {
closeOutput(outputStream);
closeInput(inputStream);
}
return true;
}
/**
* 关闭输出流
* @param outputStream
*/
private static void closeOutput(OutputStream outputStream) {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭输出流
* @param inputStream
*/
private static void closeInput(InputStream inputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void close(Document document, PdfWriter pdfWriter) {
if (document != null) {
document.close();
}
if (pdfWriter != null) {
pdfWriter.close();
}
}
// 官方文档的要求 无需理会
public static boolean getLicense() {
boolean result = false;
try {
String s = "<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Words for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
" </Data>\n" +
" <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param inputStream 源文件输入流
* @param outputStream pdf文件输出流
**/
public static boolean excelToPdf(InputStream inputStream, OutputStream outputStream) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getExcelLicense()) {
return false;
}
try {
//此处处理乱码和小方块
//如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
//指定文件库内容路径
FontSettings.getDefaultInstance().setFontsFolders(
new String[] {"/usr/share/fonts", "/usr/share/fonts/win"}
, true);
// 原始excel路径
com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(inputStream);
com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(false);
int[] autoDrawSheets={3};
//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
autoDraw(wb,autoDrawSheets);
int[] showSheets={0};
//隐藏workbook中不需要的sheet页。
printSheetPage(wb,showSheets);
wb.save(outputStream, pdfSaveOptions);
System.out.println("excel转换完毕");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally {
closeOutput(outputStream);
closeInput(inputStream);
}
return true;
}
/**
* 设置打印的sheet 自动拉伸比例
* @param wb
* @param page 自动拉伸的页的sheet数组
*/
public static void autoDraw(com.aspose.cells.Workbook wb,int[] page){
if(null!=page&&page.length>0){
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
}
}
}
/**
* 隐藏workbook中不需要的sheet页。
*
* @param wb
* @param page 显示页的sheet数组
*/
public static void printSheetPage(com.aspose.cells.Workbook wb, int[] page) {
for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
wb.getWorksheets().get(i).setVisible(false);
}
if (null == page || page.length == 0) {
wb.getWorksheets().get(0).setVisible(true);
} else {
for (int i = 0; i < page.length; i++) {
wb.getWorksheets().get(i).setVisible(true);
}
}
}
public static boolean getExcelLicense() {
boolean result = false;
try {
String s = "<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Cells for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>29991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>29991231</LicenseExpiry>\n" +
" <SerialNumber>evilrule</SerialNumber>\n" +
" </Data>\n" +
" <Signature>evilrule</Signature>\n" +
"</License>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
com.aspose.cells.License aposeLic = new com.aspose.cells.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* pptToPdf
* @param inputStream
* @param outputStream
* @return
*/
public static boolean pptToPdf(InputStream inputStream, OutputStream outputStream) {
Document document = null;
HSLFSlideShow hslfSlideShow = null;
PdfWriter pdfWriter = null;
try {
//此处处理乱码和小方块
//如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
//指定文件库内容路径
FontSettings.getDefaultInstance().setFontsFolders(
new String[] {"/usr/share/fonts", "/usr/share/fonts/win"}
, true);
hslfSlideShow = new HSLFSlideShow(inputStream);
// 获取ppt文件页面
Dimension dimension = hslfSlideShow.getPageSize();
document = new Document();
// pdfWriter实例
pdfWriter = PdfWriter.getInstance(document, outputStream);
document.open();
PdfPTable pdfPTable = new PdfPTable(1);
List<HSLFSlide> hslfSlideList = hslfSlideShow.getSlides();
for (int i=0; i < hslfSlideList.size(); i++) {
HSLFSlide hslfSlide = hslfSlideList.get(i);
// 设置字体, 解决中文乱码
for (HSLFShape shape : hslfSlide.getShapes()) {
if (shape instanceof HSLFTextShape) {
HSLFTextShape textShape = (HSLFTextShape) shape;
for (HSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
for (HSLFTextRun textRun : textParagraph.getTextRuns()) {
textRun.setFontFamily("宋体");
}
}
}
}
BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2d = bufferedImage.createGraphics();
graphics2d.setPaint(Color.white);
graphics2d.setFont(new Font("宋体", Font.PLAIN, 12));
hslfSlide.draw(graphics2d);
graphics2d.dispose();
Image image = Image.getInstance(bufferedImage, null);
image.scalePercent(56f);
// 写入单元格
pdfPTable.addCell(new PdfPCell(image, true));
document.add(image);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
close(document, pdfWriter);
closeOutput(outputStream);
closeInput(inputStream);
}
System.out.println("ppt转换完毕");
return true;
}
/**
* pptxToPdf
* @param inputStream
* @param outputStream
* @return
*/
public static boolean pptxToPdf(InputStream inputStream, OutputStream outputStream) {
Document document = null;
XMLSlideShow slideShow = null;
PdfWriter pdfWriter = null;
try {
//此处处理乱码和小方块
//如果在本地运行,此处报错,请注释这个这是字体,主要是为了解决linux环境下面运行jar时找不到中文字体的问题
//指定文件库内容路径
FontSettings.getDefaultInstance().setFontsFolders(
new String[] {"/usr/share/fonts", "/usr/share/fonts/win"}
, true);
slideShow = new XMLSlideShow(inputStream);
Dimension dimension = slideShow.getPageSize();
document = new Document();
pdfWriter = PdfWriter.getInstance(document, outputStream);
document.open();
PdfPTable pdfPTable = new PdfPTable(1);
List<XSLFSlide> slideList = slideShow.getSlides();
for (int i = 0, row = slideList.size(); i < row; i++) {
XSLFSlide slide = slideList.get(i);
// 设置字体, 解决中文乱码
for (XSLFShape shape : slide.getShapes()) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape textShape = (XSLFTextShape) shape;
for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
textRun.setFontFamily("宋体");
}
}
}
}
BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2d = bufferedImage.createGraphics();
graphics2d.setPaint(Color.white);
graphics2d.setFont(new Font("宋体", Font.PLAIN, 12));
slide.draw(graphics2d);
graphics2d.dispose();
Image image = Image.getInstance(bufferedImage, null);
//image.scalePercent(50f);
image.scalePercent(56f);
// 写入单元格
pdfPTable.addCell(new PdfPCell(image, true));
document.add(image);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
close(document, pdfWriter);
closeOutput(outputStream);
closeInput(inputStream);
}
System.out.println("pptx转换完毕");
return true;
}
/**
* 功能描述: <br>
* 通过文件名后缀来进行转换
*
* @return {@link boolean}
* @Author: lx
* @Date: 2022/12/13 16:37
*/
public static boolean convertToPDFByFileNameSuffix(String fileName, InputStream inputStream, OutputStream outputStream) {
String fileSuffix = getFileSuffix(fileName).toUpperCase();
if (types.get(WORD).contains(fileSuffix)) {
return wordToPdfByAspose(inputStream, outputStream);
}
if (types.get(EXCEL).contains(fileSuffix)) {
return excelToPdf(inputStream, outputStream);
}
if (types.get(PPT).contains(fileSuffix)) {
return pptToPdf(inputStream, outputStream);
}
if (types.get(PPTX).contains(fileSuffix)) {
return pptxToPdf(inputStream, outputStream);
}
// if (types.get(IMG).contains(fileSuffix)) {
// return imgToPdf(inputStream, outputStream);
// }
if (types.get(OTHER).contains(fileSuffix)) {
return wordToPdfByAspose(inputStream, outputStream);
}
return false;
}
/**
* 判断是否可以生成PDF文件
* @param fileName
* @return
*/
public static boolean isCreatePdf(String fileName) {
return types.values().stream().anyMatch(item -> item.contains(getFileSuffix(fileName).toUpperCase()));
}
/**
* 功能描述: <br>
* 取文件名后缀
*
* @param fileName
* @return {@link String}
* @Author: lx
* @Date: 2022/12/13 21:51
*/
private static String getFileSuffix(String fileName) {
if (!fileName.contains(".")) {
throw new RuntimeException("非法的文件名,文件名必须要有文件类型!");
}
String[] split = fileName.split("\\.");
return split[split.length - 1];
}
}

@ -26,9 +26,9 @@ file:
url: "https://szmy.sztzjy.com:218/file"
item:
name: trade
#
#item:
# name: trade

@ -7,7 +7,7 @@
<!-- <property name="suppressAllComments" value="true"/>-->
<!-- </commentGenerator>-->
<!-- type值为自定义的MyCommentGenerator-->
<commentGenerator type="com.sztzjy.trade.util.MyCommentGenerator">
<commentGenerator type="com.sztzjy.linkCommerce.util.MyCommentGenerator">
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="false"/>
<property name="suppressDate" value="false"/>
@ -30,7 +30,7 @@
</jdbcConnection>
<!-- 配置实体类的位置 -->
<javaModelGenerator targetPackage="com.sztzjy.trade.entity" targetProject="src/main/java">
<javaModelGenerator targetPackage="com.sztzjy.linkCommerce.entity" targetProject="src/main/java">
<!-- 生成的Java模型是否支持序列化 -->
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
@ -42,7 +42,7 @@
</sqlMapGenerator>
<!-- 配置Mapper接口的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.sztzjy.trade.mapper" targetProject="src/main/java">
<javaClientGenerator type="XMLMAPPER" targetPackage="com.sztzjy.linkCommerce.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sztzjy.trade.mapper.StuUserMapper">
<resultMap id="BaseResultMap" type="com.sztzjy.trade.entity.StuUser">
<resultMap id="BaseResultMap" type="com.sztzjy.linkCommerce.entity.StuUser">
<id column="user_id" jdbcType="VARCHAR" property="userId" />
<result column="student_id" jdbcType="VARCHAR" property="studentId" />
<result column="name" jdbcType="VARCHAR" property="name" />
@ -101,7 +101,7 @@
digital_technology_trade, digital_service_trade, data_trade, digital_trade_marketing,
aigc_digital_operations
</sql>
<select id="selectByExample" parameterType="com.sztzjy.trade.entity.StuUserExample" resultMap="BaseResultMap">
<select id="selectByExample" parameterType="com.sztzjy.linkCommerce.entity.StuUserExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
@ -125,13 +125,13 @@
delete from stu_user
where user_id = #{userId,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="com.sztzjy.trade.entity.StuUserExample">
<delete id="deleteByExample" parameterType="com.sztzjy.linkCommerce.entity.StuUserExample">
delete from stu_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.sztzjy.trade.entity.StuUser">
<insert id="insert" parameterType="com.sztzjy.linkCommerce.entity.StuUser">
insert into stu_user (user_id, student_id, name,
password, role_id, class_id,
class_name, major, school_id,
@ -159,7 +159,7 @@
#{digitalServiceTrade,jdbcType=DECIMAL}, #{dataTrade,jdbcType=DECIMAL}, #{digitalTradeMarketing,jdbcType=DECIMAL},
#{aigcDigitalOperations,jdbcType=DECIMAL})
</insert>
<insert id="insertSelective" parameterType="com.sztzjy.trade.entity.StuUser">
<insert id="insertSelective" parameterType="com.sztzjy.linkCommerce.entity.StuUser">
insert IGNORE into stu_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userId != null">
@ -352,7 +352,7 @@
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.sztzjy.trade.entity.StuUserExample" resultType="java.lang.Long">
<select id="countByExample" parameterType="com.sztzjy.linkCommerce.entity.StuUserExample" resultType="java.lang.Long">
select count(*) from stu_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
@ -496,7 +496,7 @@
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.sztzjy.trade.entity.StuUser">
<update id="updateByPrimaryKeySelective" parameterType="com.sztzjy.linkCommerce.entity.StuUser">
update stu_user
<set>
<if test="studentId != null">
@ -592,7 +592,7 @@
</set>
where user_id = #{userId,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.sztzjy.trade.entity.StuUser">
<update id="updateByPrimaryKey" parameterType="com.sztzjy.linkCommerce.entity.StuUser">
update stu_user
set student_id = #{studentId,jdbcType=VARCHAR},
name = #{name,jdbcType=VARCHAR},
@ -627,7 +627,7 @@
where user_id = #{userId,jdbcType=VARCHAR}
</update>
<select id="getStartCourseNameList" resultMap="BaseResultMap" resultType="com.sztzjy.trade.entity.StuUser">
<select id="getStartCourseNameList" resultMap="BaseResultMap" resultType="com.sztzjy.linkCommerce.entity.StuUser">
SELECT * FROM stu_user
<where>
<!-- 使用foreach标签遍历传入的className列表 -->
@ -636,7 +636,7 @@
</foreach>
</where>
</select>
<select id="selectByCourseName" resultMap="BaseResultMap" resultType="com.sztzjy.trade.entity.StuUser">
<select id="selectByCourseName" resultMap="BaseResultMap" resultType="com.sztzjy.linkCommerce.entity.StuUser">
SELECT * FROM `stu_user` WHERE class_name=#{startCourseName}
</select>
@ -652,7 +652,7 @@
</foreach>
</where>
</select>
<select id="selectStuList" resultMap="BaseResultMap" resultType="com.sztzjy.trade.entity.StuUser">
<select id="selectStuList" resultMap="BaseResultMap" resultType="com.sztzjy.linkCommerce.entity.StuUser">
select * from stu_user
<where>
school_id=#{schoolId} and

Loading…
Cancel
Save