框架搭建
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.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,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,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,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,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,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,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,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,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,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,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,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,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,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;
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue