拆分think模块包
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
package com.gxwebsoft.common.core;
|
||||
|
||||
/**
|
||||
* 系统常量
|
||||
* Created by WebSoft on 2019-10-29 15:55
|
||||
*/
|
||||
public class Constants {
|
||||
/**
|
||||
* 默认成功码
|
||||
*/
|
||||
public static final int RESULT_OK_CODE = 0;
|
||||
|
||||
/**
|
||||
* 默认失败码
|
||||
*/
|
||||
public static final int RESULT_ERROR_CODE = 1;
|
||||
|
||||
/**
|
||||
* 默认成功信息
|
||||
*/
|
||||
public static final String RESULT_OK_MSG = "操作成功";
|
||||
|
||||
/**
|
||||
* 默认失败信息
|
||||
*/
|
||||
public static final String RESULT_ERROR_MSG = "操作失败";
|
||||
|
||||
/**
|
||||
* 无权限错误码
|
||||
*/
|
||||
public static final int UNAUTHORIZED_CODE = 403;
|
||||
|
||||
/**
|
||||
* 无权限提示信息
|
||||
*/
|
||||
public static final String UNAUTHORIZED_MSG = "没有访问权限";
|
||||
|
||||
/**
|
||||
* 未认证错误码
|
||||
*/
|
||||
public static final int UNAUTHENTICATED_CODE = 401;
|
||||
|
||||
/**
|
||||
* 未认证提示信息
|
||||
*/
|
||||
public static final String UNAUTHENTICATED_MSG = "请先登录";
|
||||
|
||||
/**
|
||||
* 登录过期错误码
|
||||
*/
|
||||
public static final int TOKEN_EXPIRED_CODE = 401;
|
||||
|
||||
/**
|
||||
* 登录过期提示信息
|
||||
*/
|
||||
public static final String TOKEN_EXPIRED_MSG = "登录已过期";
|
||||
|
||||
/**
|
||||
* 非法token错误码
|
||||
*/
|
||||
public static final int BAD_CREDENTIALS_CODE = 401;
|
||||
|
||||
/**
|
||||
* 非法token提示信息
|
||||
*/
|
||||
public static final String BAD_CREDENTIALS_MSG = "请退出重新登录";
|
||||
|
||||
/**
|
||||
* 表示升序的值
|
||||
*/
|
||||
public static final String ORDER_ASC_VALUE = "asc";
|
||||
|
||||
/**
|
||||
* 表示降序的值
|
||||
*/
|
||||
public static final String ORDER_DESC_VALUE = "desc";
|
||||
|
||||
/**
|
||||
* token通过header传递的名称
|
||||
*/
|
||||
public static final String TOKEN_HEADER_NAME = "Authorization";
|
||||
|
||||
/**
|
||||
* token通过参数传递的名称
|
||||
*/
|
||||
public static final String TOKEN_PARAM_NAME = "access_token";
|
||||
|
||||
/**
|
||||
* token认证类型
|
||||
*/
|
||||
public static final String TOKEN_TYPE = "Bearer";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 操作日志记录注解
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-21 17:03:08
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.METHOD})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OperationLog {
|
||||
|
||||
/**
|
||||
* 操作功能
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* 操作模块
|
||||
*/
|
||||
String module() default "";
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
String comments() default "";
|
||||
|
||||
/**
|
||||
* 是否记录请求参数
|
||||
*/
|
||||
boolean param() default true;
|
||||
|
||||
/**
|
||||
* 是否记录返回结果
|
||||
*/
|
||||
boolean result() default true;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 操作日志模块注解
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-01 20:48:16
|
||||
*/
|
||||
@Documented
|
||||
@Target({ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface OperationModule {
|
||||
|
||||
/**
|
||||
* 模块名称
|
||||
*/
|
||||
String value();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 查询条件注解
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-01 20:48:16
|
||||
*/
|
||||
@Documented
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
|
||||
public @interface QueryField {
|
||||
|
||||
// 字段名称
|
||||
String value() default "";
|
||||
|
||||
// 查询方式
|
||||
QueryType type() default QueryType.LIKE;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.gxwebsoft.common.core.annotation;
|
||||
|
||||
/**
|
||||
* 查询方式
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-01 20:48:16
|
||||
*/
|
||||
public enum QueryType {
|
||||
// 等于
|
||||
EQ,
|
||||
// 不等于
|
||||
NE,
|
||||
// 大于
|
||||
GT,
|
||||
// 大于等于
|
||||
GE,
|
||||
// 小于
|
||||
LT,
|
||||
// 小于等于
|
||||
LE,
|
||||
// 包含
|
||||
LIKE,
|
||||
// 不包含
|
||||
NOT_LIKE,
|
||||
// 结尾等于
|
||||
LIKE_LEFT,
|
||||
// 开头等于
|
||||
LIKE_RIGHT,
|
||||
// 为NULL
|
||||
IS_NULL,
|
||||
// 不为空
|
||||
IS_NOT_NULL,
|
||||
// IN
|
||||
IN,
|
||||
// NOT IN
|
||||
NOT_IN,
|
||||
// IN条件解析逗号分割
|
||||
IN_STR,
|
||||
// NOT IN条件解析逗号分割
|
||||
NOT_IN_STR
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.gxwebsoft.common.core.aspect;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.servlet.ServletUtil;
|
||||
import cn.hutool.http.useragent.UserAgent;
|
||||
import cn.hutool.http.useragent.UserAgentUtil;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.common.core.annotation.OperationModule;
|
||||
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||
import com.gxwebsoft.common.system.entity.OperationRecord;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.OperationRecordService;
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.annotation.*;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 操作日志记录
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-21 16:58:16:05
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
public class OperationLogAspect {
|
||||
@Resource
|
||||
private OperationRecordService operationRecordService;
|
||||
|
||||
// 参数、返回结果、错误信息等最大保存长度
|
||||
private static final int MAX_LENGTH = 1000;
|
||||
// 用于记录请求耗时
|
||||
private final ThreadLocal<Long> startTime = new ThreadLocal<>();
|
||||
|
||||
@Pointcut("@annotation(com.gxwebsoft.common.core.annotation.OperationLog)")
|
||||
public void operationLog() {
|
||||
}
|
||||
|
||||
@Before("operationLog()")
|
||||
public void doBefore(JoinPoint joinPoint) throws Throwable {
|
||||
startTime.set(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
@AfterReturning(pointcut = "operationLog()", returning = "result")
|
||||
public void doAfterReturning(JoinPoint joinPoint, Object result) {
|
||||
saveLog(joinPoint, result, null);
|
||||
}
|
||||
|
||||
@AfterThrowing(value = "operationLog()", throwing = "e")
|
||||
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
|
||||
saveLog(joinPoint, null, e);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存操作记录
|
||||
*/
|
||||
private void saveLog(JoinPoint joinPoint, Object result, Exception e) {
|
||||
OperationRecord record = new OperationRecord();
|
||||
// 记录操作耗时
|
||||
if (startTime.get() != null) {
|
||||
record.setSpendTime(System.currentTimeMillis() - startTime.get());
|
||||
}
|
||||
// 记录当前登录用户id、租户id
|
||||
User user = getLoginUser();
|
||||
if (user != null) {
|
||||
record.setUserId(user.getUserId());
|
||||
record.setTenantId(user.getTenantId());
|
||||
}
|
||||
// 记录请求地址、请求方式、ip
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
HttpServletRequest request = (attributes == null ? null : attributes.getRequest());
|
||||
if (request != null) {
|
||||
record.setUrl(request.getRequestURI());
|
||||
record.setRequestMethod(request.getMethod());
|
||||
UserAgent ua = UserAgentUtil.parse(ServletUtil.getHeaderIgnoreCase(request, "User-Agent"));
|
||||
record.setOs(ua.getPlatform().toString());
|
||||
record.setDevice(ua.getOs().toString());
|
||||
record.setBrowser(ua.getBrowser().toString());
|
||||
record.setIp(ServletUtil.getClientIP(request));
|
||||
}
|
||||
// 记录异常信息
|
||||
if (e != null) {
|
||||
record.setStatus(1);
|
||||
record.setError(StrUtil.sub(e.toString(), 0, MAX_LENGTH));
|
||||
}
|
||||
// 记录模块名、操作功能、请求方法、请求参数、返回结果
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
record.setMethod(joinPoint.getTarget().getClass().getName() + "." + signature.getName());
|
||||
Method method = signature.getMethod();
|
||||
if (method != null) {
|
||||
OperationLog ol = method.getAnnotation(OperationLog.class);
|
||||
if (ol != null) {
|
||||
// 记录操作功能
|
||||
record.setDescription(getDescription(method, ol));
|
||||
// 记录操作模块
|
||||
record.setModule(getModule(joinPoint, ol));
|
||||
// 记录备注
|
||||
if (StrUtil.isNotEmpty(ol.comments())) {
|
||||
record.setComments(ol.comments());
|
||||
}
|
||||
// 记录请求参数
|
||||
if (ol.param() && request != null) {
|
||||
record.setParams(StrUtil.sub(getParams(joinPoint, request), 0, MAX_LENGTH));
|
||||
}
|
||||
// 记录请求结果
|
||||
if (ol.result() && result != null) {
|
||||
record.setResult(StrUtil.sub(JSONUtil.toJSONString(result), 0, MAX_LENGTH));
|
||||
}
|
||||
}
|
||||
}
|
||||
operationRecordService.saveAsync(record);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户
|
||||
*/
|
||||
private User getLoginUser() {
|
||||
Authentication subject = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (subject != null) {
|
||||
Object object = subject.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
return (User) object;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取请求参数
|
||||
*
|
||||
* @param joinPoint JoinPoint
|
||||
* @param request HttpServletRequest
|
||||
* @return String
|
||||
*/
|
||||
private String getParams(JoinPoint joinPoint, HttpServletRequest request) {
|
||||
String params;
|
||||
Map<String, String> paramsMap = ServletUtil.getParamMap(request);
|
||||
if (paramsMap.keySet().size() > 0) {
|
||||
params = JSONUtil.toJSONString(paramsMap);
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object arg : joinPoint.getArgs()) {
|
||||
if (ObjectUtil.isNull(arg)
|
||||
|| arg instanceof MultipartFile
|
||||
|| arg instanceof HttpServletRequest
|
||||
|| arg instanceof HttpServletResponse) {
|
||||
continue;
|
||||
}
|
||||
sb.append(JSONUtil.toJSONString(arg)).append(" ");
|
||||
}
|
||||
params = sb.toString();
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取操作模块
|
||||
*
|
||||
* @param joinPoint JoinPoint
|
||||
* @param ol OperationLog
|
||||
* @return String
|
||||
*/
|
||||
private String getModule(JoinPoint joinPoint, OperationLog ol) {
|
||||
if (StrUtil.isNotEmpty(ol.module())) {
|
||||
return ol.module();
|
||||
}
|
||||
OperationModule om = joinPoint.getTarget().getClass().getAnnotation(OperationModule.class);
|
||||
if (om != null && StrUtil.isNotEmpty(om.value())) {
|
||||
return om.value();
|
||||
}
|
||||
Api api = joinPoint.getTarget().getClass().getAnnotation(Api.class);
|
||||
if (api != null && api.tags() != null) {
|
||||
return ArrayUtil.join(api.tags(), ",");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取操作功能
|
||||
*
|
||||
* @param method Method
|
||||
* @param ol OperationLog
|
||||
* @return String
|
||||
*/
|
||||
private String getDescription(Method method, OperationLog ol) {
|
||||
if (StrUtil.isNotEmpty(ol.value())) {
|
||||
return ol.value();
|
||||
}
|
||||
ApiOperation ao = method.getAnnotation(ApiOperation.class);
|
||||
if (ao != null && StrUtil.isNotEmpty(ao.value())) {
|
||||
return ao.value();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* 系统配置属性
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-30 17:58:16
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "config")
|
||||
public class ConfigProperties {
|
||||
/**
|
||||
* 文件上传磁盘位置
|
||||
*/
|
||||
private Integer uploadLocation = 0;
|
||||
|
||||
/**
|
||||
* 文件上传是否使用uuid命名
|
||||
*/
|
||||
private Boolean uploadUuidName = true;
|
||||
|
||||
/**
|
||||
* 文件上传生成缩略图的大小(kb)
|
||||
*/
|
||||
private Integer thumbnailSize = 60;
|
||||
|
||||
/**
|
||||
* OpenOffice的安装目录
|
||||
*/
|
||||
private String openOfficeHome;
|
||||
|
||||
/**
|
||||
* swagger扫描包
|
||||
*/
|
||||
private String swaggerBasePackage;
|
||||
|
||||
/**
|
||||
* swagger文档标题
|
||||
*/
|
||||
private String swaggerTitle;
|
||||
|
||||
/**
|
||||
* swagger文档描述
|
||||
*/
|
||||
private String swaggerDescription;
|
||||
|
||||
/**
|
||||
* swagger文档版本号
|
||||
*/
|
||||
private String swaggerVersion;
|
||||
|
||||
/**
|
||||
* swagger地址
|
||||
*/
|
||||
private String swaggerHost;
|
||||
|
||||
/**
|
||||
* token过期时间, 单位秒
|
||||
*/
|
||||
private Long tokenExpireTime = 60 * 60 * 30 * 24L;
|
||||
|
||||
/**
|
||||
* token快要过期自动刷新时间, 单位分钟
|
||||
*/
|
||||
private int tokenRefreshTime = 30;
|
||||
|
||||
/**
|
||||
* 生成token的密钥Key的base64字符
|
||||
*/
|
||||
private String tokenKey;
|
||||
|
||||
/**
|
||||
* 文件上传目录
|
||||
*/
|
||||
private String uploadPath;
|
||||
|
||||
/**
|
||||
* 本地文件上传目录(开发环境)
|
||||
*/
|
||||
private String localUploadPath;
|
||||
|
||||
/**
|
||||
* 文件服务器
|
||||
*/
|
||||
private String fileServer;
|
||||
|
||||
/**
|
||||
* 网关地址
|
||||
*/
|
||||
private String serverUrl;
|
||||
|
||||
/**
|
||||
* 阿里云存储 OSS
|
||||
* Endpoint
|
||||
*/
|
||||
private String endpoint;
|
||||
private String accessKeyId;
|
||||
private String accessKeySecret;
|
||||
private String bucketName;
|
||||
private String bucketDomain;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class HttpMessageConverter extends MappingJackson2HttpMessageConverter {
|
||||
public HttpMessageConverter(){
|
||||
List<MediaType> mediaTypes = new ArrayList<>();
|
||||
mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
setSupportedMediaTypes(mediaTypes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import net.sf.jsqlparser.expression.Expression;
|
||||
import net.sf.jsqlparser.expression.LongValue;
|
||||
import net.sf.jsqlparser.expression.NullValue;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* MybatisPlus配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:28
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor(HttpServletRequest request) {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
|
||||
// 多租户插件配置
|
||||
TenantLineHandler tenantLineHandler = new TenantLineHandler() {
|
||||
|
||||
@Override
|
||||
public Expression getTenantId() {
|
||||
// 从域名拿ID
|
||||
String Domain = request.getHeader("Domain");
|
||||
if (StrUtil.isNotBlank(Domain)) {
|
||||
String key = "Domain:" + Domain;
|
||||
String tenantId = redisUtil.get(key);
|
||||
if(tenantId != null){
|
||||
System.out.println("授权域名" + Domain + " => " + tenantId);
|
||||
return new LongValue(tenantId);
|
||||
}
|
||||
}
|
||||
// 从请求头拿ID
|
||||
final String tenantId = request.getHeader("tenantId");
|
||||
if(tenantId != null){
|
||||
return new LongValue(tenantId);
|
||||
}
|
||||
return getLoginUserTenantId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean ignoreTable(String tableName) {
|
||||
return Arrays.asList(
|
||||
"sys_tenant",
|
||||
"sys_dictionary",
|
||||
"sys_dictionary_data",
|
||||
"sys_user_oauth",
|
||||
"sys_email_record",
|
||||
"sys_plug",
|
||||
"sys_version",
|
||||
"sys_order",
|
||||
"sys_white_domain"
|
||||
).contains(tableName);
|
||||
}
|
||||
};
|
||||
TenantLineInnerInterceptor tenantLineInnerInterceptor = new TenantLineInnerInterceptor(tenantLineHandler);
|
||||
interceptor.addInnerInterceptor(tenantLineInnerInterceptor);
|
||||
|
||||
// 分页插件配置
|
||||
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
|
||||
interceptor.addInnerInterceptor(paginationInnerInterceptor);
|
||||
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录用户的租户id
|
||||
*
|
||||
* @return Integer
|
||||
*/
|
||||
public Expression getLoginUserTenantId() {
|
||||
try {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
return new LongValue(((User) object).getTenantId());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
return new NullValue();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
|
||||
@Configuration
|
||||
public class RestTemplateConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
|
||||
RestTemplate restTemplate = new RestTemplate(factory);
|
||||
restTemplate.getMessageConverters().add(new HttpMessageConverter());
|
||||
return restTemplate;
|
||||
}
|
||||
@Bean
|
||||
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
// ms
|
||||
factory.setReadTimeout(60000);
|
||||
// ms
|
||||
factory.setConnectTimeout(60000);
|
||||
|
||||
return factory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @Author ds
|
||||
* @Date 2022-05-05
|
||||
*/
|
||||
@Component
|
||||
public class SpringContextUtil implements ApplicationContextAware {
|
||||
/**
|
||||
* spring的应用上下文
|
||||
*/
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
/**
|
||||
* 初始化时将应用上下文设置进applicationContext
|
||||
* @param applicationContext
|
||||
* @throws BeansException
|
||||
*/
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringContextUtil.applicationContext=applicationContext;
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext(){
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据bean名称获取某个bean对象
|
||||
*
|
||||
* @param name bean名称
|
||||
* @return Object
|
||||
* @throws BeansException
|
||||
*/
|
||||
public static Object getBean(String name) throws BeansException {
|
||||
return applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据bean的class获取某个bean对象
|
||||
* @param beanClass
|
||||
* @param <T>
|
||||
* @return
|
||||
* @throws BeansException
|
||||
*/
|
||||
public static <T> T getBean(Class<T> beanClass) throws BeansException {
|
||||
return applicationContext.getBean(beanClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取spring.profiles.active
|
||||
* @return
|
||||
*/
|
||||
public static String getProfile(){
|
||||
return getApplicationContext().getEnvironment().getActiveProfiles()[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import springfox.documentation.builders.ApiInfoBuilder;
|
||||
import springfox.documentation.builders.PathSelectors;
|
||||
import springfox.documentation.builders.RequestHandlerSelectors;
|
||||
import springfox.documentation.oas.annotations.EnableOpenApi;
|
||||
import springfox.documentation.service.*;
|
||||
import springfox.documentation.spi.DocumentationType;
|
||||
import springfox.documentation.spi.service.contexts.SecurityContext;
|
||||
import springfox.documentation.spring.web.plugins.Docket;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Swagger配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:05
|
||||
*/
|
||||
@EnableOpenApi
|
||||
@Configuration
|
||||
public class SwaggerConfig {
|
||||
@Resource
|
||||
private ConfigProperties config;
|
||||
|
||||
@Bean
|
||||
public Docket createRestApi() {
|
||||
Docket docket = new Docket(DocumentationType.OAS_30);
|
||||
if (StrUtil.isNotBlank(config.getSwaggerHost())) {
|
||||
docket.host(config.getSwaggerHost());
|
||||
}
|
||||
return docket
|
||||
.apiInfo(apiInfo())
|
||||
.select()
|
||||
.apis(RequestHandlerSelectors.basePackage(config.getSwaggerBasePackage()))
|
||||
.paths(PathSelectors.any())
|
||||
.build()
|
||||
.securitySchemes(securitySchemes())
|
||||
.securityContexts(securityContexts());
|
||||
}
|
||||
|
||||
private ApiInfo apiInfo() {
|
||||
return new ApiInfoBuilder()
|
||||
.title(config.getSwaggerTitle())
|
||||
.description(config.getSwaggerDescription())
|
||||
.version(config.getSwaggerVersion())
|
||||
.termsOfServiceUrl("")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<SecurityScheme> securitySchemes() {
|
||||
return Collections.singletonList(
|
||||
new ApiKey("Authorization", "Authorization", "header")
|
||||
);
|
||||
}
|
||||
|
||||
private List<SecurityContext> securityContexts() {
|
||||
AuthorizationScope[] scopes = {new AuthorizationScope("global", "accessEverything")};
|
||||
List<SecurityReference> references = Collections.singletonList(
|
||||
new SecurityReference("Authorization", scopes)
|
||||
);
|
||||
return Collections.singletonList(SecurityContext.builder()
|
||||
.securityReferences(references)
|
||||
.build());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.gxwebsoft.common.core.config;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* WebMvc配置, 拦截器、资源映射等都在此配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2019-06-12 10:11:16
|
||||
*/
|
||||
@Configuration
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
/**
|
||||
* 支持跨域访问
|
||||
*/
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedHeaders("*")
|
||||
.exposedHeaders(Constants.TOKEN_HEADER_NAME)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
|
||||
.allowCredentials(true)
|
||||
.maxAge(3600);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class BalanceConstants {
|
||||
// 余额变动场景
|
||||
public static final Integer BALANCE_RECHARGE = 10; // 用户充值
|
||||
public static final Integer BALANCE_USE = 20; // 用户消费
|
||||
public static final Integer BALANCE_RE_LET = 21; // 续租
|
||||
public static final Integer BALANCE_ADMIN = 30; // 管理员操作
|
||||
public static final Integer BALANCE_REFUND = 40; // 订单退款
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class DomainConstants {
|
||||
public static final String ROOT_DOMAIN = "websoft.top"; // 根域名
|
||||
public static final String PREFIX = "https://"; // 域名前缀
|
||||
public static final String ADMIN_SUFFIX = ".".concat(ROOT_DOMAIN); // 后台管理域名拼接
|
||||
public static final String WEB_SUFFIX = ".wsdns.cn"; // 应用域名拼接
|
||||
public static final String DOMAIN = PREFIX.concat(ROOT_DOMAIN); // 完整域名
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class OrderConstants {
|
||||
// 支付方式
|
||||
public static final String PAY_METHOD_BALANCE = "10"; // 余额支付
|
||||
public static final String PAY_METHOD_WX = "20"; // 微信支付
|
||||
public static final String PAY_METHOD_ALIPAY = "30"; // 支付宝支付
|
||||
public static final String PAY_METHOD_OTHER = "40"; // 其他支付
|
||||
|
||||
// 付款状态
|
||||
public static final Integer PAY_STATUS_NO_PAY = 10; // 未付款
|
||||
public static final Integer PAY_STATUS_SUCCESS = 20; // 已付款
|
||||
|
||||
// 发货状态
|
||||
public static final Integer DELIVERY_STATUS_NO = 10; // 未发货
|
||||
public static final Integer DELIVERY_STATUS_YES = 20; // 已发货
|
||||
public static final Integer DELIVERY_STATUS_30 = 30; // 部分发货
|
||||
|
||||
// 收货状态
|
||||
public static final Integer RECEIPT_STATUS_NO = 10; // 未收货
|
||||
public static final Integer RECEIPT_STATUS_YES = 20; // 已收货
|
||||
public static final Integer RECEIPT_STATUS_RETURN = 30; // 已退货
|
||||
|
||||
// 订单状态
|
||||
public static final Integer ORDER_STATUS_DOING = 10; // 进行中
|
||||
public static final Integer ORDER_STATUS_CANCEL = 20; // 已取消
|
||||
public static final Integer ORDER_STATUS_TO_CANCEL = 21; // 待取消
|
||||
public static final Integer ORDER_STATUS_COMPLETED = 30; // 已完成
|
||||
|
||||
// 订单结算状态
|
||||
public static final Integer ORDER_SETTLED_YES = 1; // 已结算
|
||||
public static final Integer ORDER_SETTLED_NO = 0; // 未结算
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class PlatformConstants {
|
||||
public static final String MP_OFFICIAL = "MP-OFFICIAL"; // 微信公众号
|
||||
public static final String MP_WEIXIN = "MP-WEIXIN"; // 微信小程序
|
||||
public static final String MP_ALIPAY = "MP-ALIPAY"; // 支付宝小程序
|
||||
public static final String WEB = "WEB"; // web(同H5)
|
||||
public static final String H5 = "H5"; // H5(推荐使用 WEB)
|
||||
public static final String APP = "APP"; // App
|
||||
public static final String MP_BAIDU = "MP-BAIDU"; // 百度小程序
|
||||
public static final String MP_TOUTIAO = "MP-TOUTIAO"; // 百度小程序
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class ProfitConstants {
|
||||
// 收益类型
|
||||
public static final Integer PROFIT_TYPE10 = 10; // 推广收益
|
||||
public static final Integer PROFIT_TYPE20 = 20; // 团队收益
|
||||
public static final Integer PROFIT_TYPE30 = 30; // 门店收益
|
||||
public static final Integer PROFIT_TYPE40 = 30; // 区域收益
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.gxwebsoft.common.core.constants;
|
||||
|
||||
public class RedisConstants {
|
||||
// 短信验证码Key
|
||||
public static final String SMS_CODE_KEY = "sms";
|
||||
// 验证码过期时间
|
||||
public static final Long SMS_CODE_TTL = 5L;
|
||||
// 微信凭证access-token
|
||||
public static final String ACCESS_TOKEN_KEY = "access-token";
|
||||
// 空值防止击穿数据库
|
||||
public static final Long CACHE_NULL_TTL = 2L;
|
||||
// 商户信息
|
||||
public static final String MERCHANT_KEY = "merchant";
|
||||
// 添加商户定位点
|
||||
public static final String MERCHANT_GEO_KEY = "merchant-geo";
|
||||
|
||||
// token
|
||||
public static final String TOKEN_USER_ID = "cache:token:";
|
||||
// 排行榜
|
||||
public static final String USER_RANKING_BY_APPS = "userRankingByApps";
|
||||
// 搜索历史
|
||||
public static final String SEARCH_HISTORY = "searchHistory";
|
||||
// 租户系统设置信息
|
||||
public static final String TEN_ANT_SETTING_KEY = "setting";
|
||||
// 排行榜Key
|
||||
public static final String USER_RANKING_BY_APPS_5 = "cache5:userRankingByApps";
|
||||
|
||||
|
||||
|
||||
// 哗啦啦key
|
||||
public static final String getAllShop = "allShop";
|
||||
public static final String getBaseInfo = "baseInfo";
|
||||
public static final String getFoodClassCategory = "foodCategory";
|
||||
public static final String getOpenFood = "openFood";
|
||||
public static final String haulalaGeoKey = "cache10:hualala-geo";
|
||||
public static final String HLL_CART_KEY = "hll-cart"; // hll-cart[shopId]:[userId]
|
||||
public static final String HLL_CART_FOOD_KEY = "hll-cart-list"; // hll-cart-list[shopId]:[userId]
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.gxwebsoft.common.core.enums;
|
||||
|
||||
public enum ChatMessageType {
|
||||
TEXT( 1, "text"),
|
||||
IMAGE(2, "image"),
|
||||
VOICE(3, "voice"),
|
||||
CARD(4, "card"),
|
||||
;
|
||||
|
||||
private int index;
|
||||
|
||||
private String name;
|
||||
ChatMessageType(int i, String text) {
|
||||
this.name = text;
|
||||
this.index = i;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getIndex() {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.gxwebsoft.common.core.enums;
|
||||
|
||||
public enum GreenWebType {
|
||||
/**
|
||||
* 用户昵称
|
||||
*/
|
||||
nickname_detection,
|
||||
/**
|
||||
* 聊天互动
|
||||
*/
|
||||
chat_detection,
|
||||
/**
|
||||
* 动态评论
|
||||
*/
|
||||
comment_detection,
|
||||
/**
|
||||
* 教学无聊
|
||||
*/
|
||||
pgc_detection,
|
||||
/**
|
||||
* 图片检测service: baselineCheck通用基线检测
|
||||
*/
|
||||
baselineCheck,
|
||||
/**
|
||||
* 视频检测
|
||||
*/
|
||||
videoDetection;
|
||||
|
||||
public enum ChatMessageType {
|
||||
TEXT( 1, "text"),
|
||||
IMAGE(2, "image"),
|
||||
VOICE(3, "voice"),
|
||||
CARD(4, "card"),
|
||||
;
|
||||
|
||||
private int index;
|
||||
|
||||
private String name;
|
||||
ChatMessageType(int i, String text) {
|
||||
this.name = text;
|
||||
this.index = i;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getIndex() {
|
||||
return index;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.gxwebsoft.common.core.exception;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
|
||||
/**
|
||||
* 自定义业务异常
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:28
|
||||
*/
|
||||
public class BusinessException extends RuntimeException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Integer code;
|
||||
|
||||
public BusinessException() {
|
||||
this(Constants.RESULT_ERROR_MSG);
|
||||
}
|
||||
|
||||
public BusinessException(String message) {
|
||||
this(Constants.RESULT_ERROR_CODE, message);
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public BusinessException(Integer code, String message, Throwable cause,
|
||||
boolean enableSuppression, boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(Integer code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.gxwebsoft.common.core.exception;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-02-22 11:29:30
|
||||
*/
|
||||
@ControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
private final Logger logger = LoggerFactory.getLogger(getClass());
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ApiResult<?> methodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e,
|
||||
HttpServletResponse response) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, "请求方式不正确").setError(e.toString());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ApiResult<?> accessDeniedExceptionHandler(AccessDeniedException e, HttpServletResponse response) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG).setError(e.toString());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ApiResult<?> businessExceptionHandler(BusinessException e, HttpServletResponse response) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(e.getCode(), e.getMessage());
|
||||
}
|
||||
|
||||
@ResponseBody
|
||||
@ExceptionHandler(Throwable.class)
|
||||
public ApiResult<?> exceptionHandler(Throwable e, HttpServletResponse response) {
|
||||
logger.error(e.getMessage(), e);
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG).setError(e.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 没有访问权限异常处理
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-25 00:35:03
|
||||
*/
|
||||
@Component
|
||||
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
|
||||
throws IOException, ServletException {
|
||||
CommonUtil.responseError(response, Constants.UNAUTHORIZED_CODE, Constants.UNAUTHORIZED_MSG, e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 没有登录异常处理
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-25 00:35:03
|
||||
*/
|
||||
@Component
|
||||
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
|
||||
throws IOException, ServletException {
|
||||
CommonUtil.responseError(response, Constants.UNAUTHENTICATED_CODE, Constants.UNAUTHENTICATED_MSG,
|
||||
e.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.core.utils.SignCheckUtil;
|
||||
import com.gxwebsoft.common.system.entity.LoginRecord;
|
||||
import com.gxwebsoft.common.system.entity.Menu;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.LoginRecordService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.ExpiredJwtException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 处理携带token的请求过滤器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-30 20:48:05
|
||||
*/
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
@Resource
|
||||
private LoginRecordService loginRecordService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String access_token = JwtUtil.getAccessToken(request);
|
||||
if (StrUtil.isNotBlank(access_token)) {
|
||||
try {
|
||||
// 解析token
|
||||
Claims claims = JwtUtil.parseToken(access_token, configProperties.getTokenKey());
|
||||
JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
|
||||
|
||||
// 校验服务器域名白名单
|
||||
final SignCheckUtil checkUtil = new SignCheckUtil();
|
||||
String key = "WhiteDomain:" + jwtSubject.getTenantId();
|
||||
List<String> whiteDomains = redisUtil.get(key, List.class);
|
||||
if (!checkUtil.checkWhiteDomains(whiteDomains, request.getServerName())) {
|
||||
throw new UsernameNotFoundException("The requested domain name is not on the whitelist");
|
||||
}
|
||||
|
||||
User user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());
|
||||
if (user == null) {
|
||||
throw new UsernameNotFoundException("Username not found");
|
||||
}
|
||||
List<Menu> authorities = user.getAuthorities().stream()
|
||||
.filter(m -> StrUtil.isNotBlank(m.getAuthority())).collect(Collectors.toList());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
user, null, authorities);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
// token将要过期签发新token, 防止突然退出登录
|
||||
long expiration = (claims.getExpiration().getTime() - new Date().getTime()) / 1000 / 60;
|
||||
if (expiration < configProperties.getTokenRefreshTime()) {
|
||||
String token = JwtUtil.buildToken(jwtSubject, configProperties.getTokenExpireTime(),
|
||||
configProperties.getTokenKey());
|
||||
response.addHeader(Constants.TOKEN_HEADER_NAME, token);
|
||||
loginRecordService.saveAsync(user.getUsername(), LoginRecord.TYPE_REFRESH, null,
|
||||
user.getTenantId(), request);
|
||||
}
|
||||
} catch (ExpiredJwtException e) {
|
||||
CommonUtil.responseError(response, Constants.TOKEN_EXPIRED_CODE, Constants.TOKEN_EXPIRED_MSG,
|
||||
e.getMessage());
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
CommonUtil.responseError(response, Constants.BAD_CREDENTIALS_CODE, Constants.BAD_CREDENTIALS_MSG,
|
||||
e.toString());
|
||||
return;
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* Jwt载体
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-03 00:11:12
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class JwtSubject implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 账号
|
||||
*/
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* 租户id
|
||||
*/
|
||||
private Integer tenantId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.servlet.ServletUtil;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.utils.JSONUtil;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.io.Encoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.security.Key;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* JWT工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-01-21 16:30:59
|
||||
*/
|
||||
public class JwtUtil {
|
||||
|
||||
/**
|
||||
* 获取请求中的access_token
|
||||
*
|
||||
* @param request HttpServletRequest
|
||||
* @return String
|
||||
*/
|
||||
public static String getAccessToken(HttpServletRequest request) {
|
||||
String access_token = ServletUtil.getHeaderIgnoreCase(request, Constants.TOKEN_HEADER_NAME);
|
||||
if (StrUtil.isNotBlank(access_token)) {
|
||||
if (access_token.startsWith(Constants.TOKEN_TYPE)) {
|
||||
access_token = StrUtil.removePrefix(access_token, Constants.TOKEN_TYPE).trim();
|
||||
}
|
||||
} else {
|
||||
access_token = request.getParameter(Constants.TOKEN_PARAM_NAME);
|
||||
}
|
||||
return access_token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
*
|
||||
* @param subject 载体
|
||||
* @param expire 过期时间
|
||||
* @param base64EncodedKey base64编码的Key
|
||||
* @return token
|
||||
*/
|
||||
public static String buildToken(JwtSubject subject, Long expire, String base64EncodedKey) {
|
||||
return buildToken(JSONUtil.toJSONString(subject), expire, decodeKey(base64EncodedKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成token
|
||||
*
|
||||
* @param subject 载体
|
||||
* @param expire 过期时间
|
||||
* @param key 密钥
|
||||
* @return token
|
||||
*/
|
||||
public static String buildToken(String subject, Long expire, Key key) {
|
||||
Date expireDate = new Date(new Date().getTime() + 1000 * expire);
|
||||
return Jwts.builder()
|
||||
.setSubject(subject)
|
||||
.setExpiration(expireDate)
|
||||
.setIssuedAt(new Date())
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析token
|
||||
*
|
||||
* @param token token
|
||||
* @param base64EncodedKey base64编码的Key
|
||||
* @return Claims
|
||||
*/
|
||||
public static Claims parseToken(String token, String base64EncodedKey) {
|
||||
return parseToken(token, decodeKey(base64EncodedKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析token
|
||||
*
|
||||
* @param token token
|
||||
* @param key 密钥
|
||||
* @return Claims
|
||||
*/
|
||||
public static Claims parseToken(String token, Key key) {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取JwtSubject
|
||||
*
|
||||
* @param claims Claims
|
||||
* @return JwtSubject
|
||||
*/
|
||||
public static JwtSubject getJwtSubject(Claims claims) {
|
||||
return JSONUtil.parseObject(claims.getSubject(), JwtSubject.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成Key
|
||||
*
|
||||
* @return Key
|
||||
*/
|
||||
public static Key randomKey() {
|
||||
return Keys.secretKeyFor(SignatureAlgorithm.HS256);
|
||||
}
|
||||
|
||||
/**
|
||||
* base64编码key
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String encodeKey(Key key) {
|
||||
return Encoders.BASE64.encode(key.getEncoded());
|
||||
}
|
||||
|
||||
/**
|
||||
* base64编码Key
|
||||
*
|
||||
* @param base64EncodedKey base64编码的key
|
||||
* @return Key
|
||||
*/
|
||||
public static Key decodeKey(String base64EncodedKey) {
|
||||
if (StrUtil.isBlank(base64EncodedKey)) {
|
||||
return null;
|
||||
}
|
||||
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(base64EncodedKey));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.gxwebsoft.common.core.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* Spring Security配置
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-23 18:04:52
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Resource
|
||||
private JwtAccessDeniedHandler jwtAccessDeniedHandler;
|
||||
@Resource
|
||||
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
|
||||
@Resource
|
||||
private JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers(HttpMethod.OPTIONS, "/**")
|
||||
.permitAll()
|
||||
.antMatchers(HttpMethod.GET, "/api/file/**","/**", "/api/captcha", "/")
|
||||
.permitAll()
|
||||
.antMatchers(
|
||||
"/api/login",
|
||||
"/api/register",
|
||||
"/api/existence",
|
||||
"/api/oss/upload",
|
||||
"/druid/**",
|
||||
"/swagger-resources/**",
|
||||
"/webjars/**",
|
||||
"/hxz/v1/**",
|
||||
"/api/sendSmsCaptcha",
|
||||
"/api/loginBySms",
|
||||
"/api/parseToken/*",
|
||||
"/api/login-alipay/*",
|
||||
"/api/wx-login/loginByMpWxPhone",
|
||||
"/api/wx-login/loginByOpenId",
|
||||
"/api/system/wx-native-pay/**",
|
||||
"/api/system/wx-pay/**",
|
||||
"/api/wxWorkQrConnect",
|
||||
"/api/sys/user-plan-log/wx-pay/**",
|
||||
"/api/wx-official/**",
|
||||
"/lvQ4EoivKJ.txt"
|
||||
)
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.and()
|
||||
.sessionManagement()
|
||||
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
|
||||
.and()
|
||||
.csrf()
|
||||
.disable()
|
||||
.cors()
|
||||
.and()
|
||||
.logout()
|
||||
.disable()
|
||||
.headers()
|
||||
.frameOptions()
|
||||
.disable()
|
||||
.and()
|
||||
.exceptionHandling()
|
||||
.accessDeniedHandler(jwtAccessDeniedHandler)
|
||||
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
|
||||
.and()
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BCryptPasswordEncoder bCryptPasswordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.gxwebsoft.common.core.socketio.cache;
|
||||
|
||||
import com.corundumstudio.socketio.SocketIOClient;
|
||||
import com.corundumstudio.socketio.SocketIOServer;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* @Author
|
||||
* @Description 用户信息缓存
|
||||
* @Date 14:00 2022/1/21
|
||||
* @Param
|
||||
* @return
|
||||
**/
|
||||
@Component
|
||||
public class ClientCache {
|
||||
|
||||
private static Map<String, HashMap<UUID, SocketIOClient>> concurrentHashMap = new ConcurrentHashMap<>();
|
||||
|
||||
private static SocketIOServer socketIOServer;
|
||||
|
||||
public static SocketIOServer getSocketIOServer() {
|
||||
return socketIOServer;
|
||||
}
|
||||
|
||||
public static void setSocketIOServer(SocketIOServer instance) {
|
||||
socketIOServer = instance;
|
||||
}
|
||||
public void saveClient(String userId,UUID sessionId,SocketIOClient socketIOClient){
|
||||
HashMap<UUID, SocketIOClient> sessionIdClientCache = concurrentHashMap.get(userId);
|
||||
if(sessionIdClientCache == null){
|
||||
sessionIdClientCache = new HashMap<>();
|
||||
}
|
||||
sessionIdClientCache.put(sessionId,socketIOClient);
|
||||
concurrentHashMap.put(userId,sessionIdClientCache);
|
||||
}
|
||||
|
||||
|
||||
public HashMap<UUID,SocketIOClient> getUserClient(String userId){
|
||||
return concurrentHashMap.get(userId);
|
||||
}
|
||||
|
||||
public void deleteSessionClientByUserId(String userId,UUID sessionId){
|
||||
concurrentHashMap.get(userId).remove(sessionId);
|
||||
}
|
||||
|
||||
|
||||
public void deleteUserCacheByUserId(String userId){
|
||||
concurrentHashMap.remove(userId);
|
||||
}
|
||||
|
||||
public int getOnLineCount(){
|
||||
return concurrentHashMap.size();
|
||||
}
|
||||
|
||||
public void sendUserEvent(String userId,String event, Object message) {
|
||||
// 发送到接收方
|
||||
HashMap<UUID, SocketIOClient> userClient = concurrentHashMap.get(userId);
|
||||
|
||||
// 查看对方是否在线
|
||||
if(!CollectionUtils.isEmpty(userClient)){
|
||||
for (UUID uuid : userClient.keySet()) {
|
||||
SocketIOClient ioClient = userClient.get(uuid);
|
||||
ioClient.sendEvent(event, message);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.gxwebsoft.common.core.socketio.config;
|
||||
|
||||
import com.corundumstudio.socketio.SocketIOServer;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.security.JwtSubject;
|
||||
import com.gxwebsoft.common.core.security.JwtUtil;
|
||||
import com.gxwebsoft.common.core.socketio.cache.ClientCache;
|
||||
import com.gxwebsoft.common.core.socketio.handler.SocketIOHandler;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import io.jsonwebtoken.Claims;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* socket服务配置
|
||||
* @author machenike
|
||||
*/
|
||||
@Configuration
|
||||
public class SocketIOConfig implements InitializingBean {
|
||||
|
||||
private final static Logger logger = LoggerFactory.getLogger(SocketIOConfig.class);
|
||||
@Value("${socketio.host}")
|
||||
private String host;
|
||||
|
||||
@Value("${socketio.port}")
|
||||
private Integer port;
|
||||
|
||||
@Resource
|
||||
private SocketIOHandler socketIOHandler;
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
|
||||
//设置host
|
||||
config.setHostname(host);
|
||||
//设置端口
|
||||
config.setPort(port);
|
||||
config.setBossThreads(1);
|
||||
config.setAuthorizationListener(handshakeData -> {
|
||||
String userId =handshakeData.getSingleUrlParam("userId");
|
||||
String token = handshakeData.getSingleUrlParam("token");
|
||||
logger.info("身份验证 token:{}", token);
|
||||
if(!StringUtils.hasText(token) || !StringUtils.hasText(userId)){
|
||||
return false;
|
||||
}
|
||||
// 身份验证
|
||||
Claims claims = JwtUtil.parseToken(token, configProperties.getTokenKey());
|
||||
JwtSubject jwtSubject = JwtUtil.getJwtSubject(claims);
|
||||
User user = userService.getByUsername(jwtSubject.getUsername(), jwtSubject.getTenantId());
|
||||
|
||||
if (user == null || !user.getUserId().equals(Integer.valueOf(userId))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
InputStream resourceAsStream = this.getClass().getResourceAsStream("/jks/love.jks"); // 读取证书文件流
|
||||
config.setKeyStore(resourceAsStream); // 设置证书文件
|
||||
config.setKeyStorePassword("123456"); // 设置证书密码
|
||||
|
||||
// 启动socket服务
|
||||
// SocketIOServer server = new SocketIOServer(config);
|
||||
// server.addListeners(socketIOHandler);
|
||||
// server.start();
|
||||
// ClientCache.setSocketIOServer(server);
|
||||
// logger.debug("Netty SocketIO启动:{}:{}",host,port);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.gxwebsoft.common.core.socketio.handler;
|
||||
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import com.corundumstudio.socketio.AckRequest;
|
||||
import com.corundumstudio.socketio.SocketIOClient;
|
||||
import com.corundumstudio.socketio.annotation.OnConnect;
|
||||
import com.corundumstudio.socketio.annotation.OnDisconnect;
|
||||
import com.corundumstudio.socketio.annotation.OnEvent;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.socketio.cache.ClientCache;
|
||||
import com.gxwebsoft.common.system.entity.ChatMessage;
|
||||
import com.gxwebsoft.common.system.service.ChatConversationService;
|
||||
import com.gxwebsoft.common.system.service.ChatMessageService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.UUID;
|
||||
|
||||
|
||||
/**
|
||||
* socket处理拦截器
|
||||
* @author machenike
|
||||
*/
|
||||
|
||||
@Component
|
||||
public class SocketIOHandler {
|
||||
|
||||
|
||||
@Resource
|
||||
private ChatMessageService messageService;
|
||||
|
||||
@Resource
|
||||
private ChatConversationService conversationService;
|
||||
|
||||
@Resource
|
||||
private ClientCache clientCache;
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
/**
|
||||
* 日志
|
||||
*/
|
||||
private final static Logger logger = LoggerFactory.getLogger(SocketIOHandler.class);
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 客户端连上socket服务器时执行此事件
|
||||
* @param client
|
||||
*/
|
||||
@OnConnect
|
||||
public void onConnect(SocketIOClient client) {
|
||||
String userId = client.getHandshakeData().getSingleUrlParam("userId");
|
||||
logger.debug("socket client auth success [userId="+userId+"]");
|
||||
UUID sessionId = client.getSessionId();
|
||||
|
||||
|
||||
// 管理员
|
||||
String isAdmin = client.getHandshakeData().getSingleUrlParam("isAdmin");
|
||||
if(StringUtils.isNotBlank(isAdmin)){
|
||||
// todo 权限验证
|
||||
clientCache.saveClient("admin",sessionId, client);
|
||||
}else {
|
||||
clientCache.saveClient(userId,sessionId, client);
|
||||
}
|
||||
|
||||
System.out.println("userId: "+userId+"连接建立成功 - "+sessionId);
|
||||
logger.info("当前在线人数:{}",clientCache.getOnLineCount());
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 客户端断开socket服务器时执行此事件
|
||||
* @param client
|
||||
*/
|
||||
@OnDisconnect
|
||||
public void onDisconnect(SocketIOClient client) {
|
||||
String userId = client.getHandshakeData().getSingleUrlParam("userId");
|
||||
UUID sessionId = client.getSessionId();
|
||||
clientCache.deleteSessionClientByUserId(userId,sessionId);
|
||||
System.out.println("userId: "+userId+"连接关闭成功 - "+sessionId);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param client
|
||||
*/
|
||||
@OnEvent( value = "message")
|
||||
@Transactional
|
||||
public void onMessage(SocketIOClient client, AckRequest request, ChatMessage message) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.AlipayConstants;
|
||||
import com.alipay.api.CertAlipayRequest;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 支付宝工具类
|
||||
* @author leng
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class AlipayConfigUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
public Integer tenantId;
|
||||
public String gateway;
|
||||
public JSONObject config;
|
||||
public String appId;
|
||||
public String privateKey;
|
||||
public String appCertPublicKey;
|
||||
public String alipayCertPublicKey;
|
||||
public String alipayRootCert;
|
||||
|
||||
@Resource
|
||||
private ConfigProperties pathConfig;
|
||||
|
||||
public AlipayConfigUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
// 实例化客户端
|
||||
public DefaultAlipayClient alipayClient(Integer tenantId) throws AlipayApiException {
|
||||
this.gateway = "https://openapi.alipay.com/gateway.do";
|
||||
this.tenantId = tenantId;
|
||||
this.payment(tenantId);
|
||||
CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
|
||||
certAlipayRequest.setServerUrl(this.gateway);
|
||||
certAlipayRequest.setAppId(this.appId);
|
||||
certAlipayRequest.setPrivateKey(this.privateKey);
|
||||
certAlipayRequest.setFormat(AlipayConstants.FORMAT_JSON);
|
||||
certAlipayRequest.setCharset(AlipayConstants.CHARSET_UTF8);
|
||||
certAlipayRequest.setSignType(AlipayConstants.SIGN_TYPE_RSA2);
|
||||
certAlipayRequest.setCertPath(this.appCertPublicKey);
|
||||
certAlipayRequest.setAlipayPublicCertPath(this.alipayCertPublicKey);
|
||||
certAlipayRequest.setRootCertPath(this.alipayRootCert);
|
||||
// System.out.println("this.appId = " + this.appId);
|
||||
// System.out.println("this.appId = " + this.gateway);
|
||||
// System.out.println("this.appId = " + this.privateKey);
|
||||
// System.out.println("this.appId = " + this.appCertPublicKey);
|
||||
// System.out.println("this.appId = " + this.alipayCertPublicKey);
|
||||
// System.out.println("this.appId = " + this.alipayRootCert);
|
||||
// System.out.println("this.config = " + this.config);
|
||||
return new DefaultAlipayClient(certAlipayRequest);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取支付宝秘钥
|
||||
*/
|
||||
public JSONObject payment(Integer tenantId) {
|
||||
System.out.println("tenantId = " + tenantId);
|
||||
String key = "cache".concat(tenantId.toString()).concat(":setting:payment");
|
||||
System.out.println("key = " + key);
|
||||
String cache = stringRedisTemplate.opsForValue().get(key);
|
||||
if (cache == null) {
|
||||
throw new BusinessException("支付方式未配置");
|
||||
}
|
||||
// 解析json数据
|
||||
JSONObject payment = JSON.parseObject(cache.getBytes());
|
||||
this.config = payment;
|
||||
this.appId = payment.getString("alipayAppId");
|
||||
this.privateKey = payment.getString("privateKey");
|
||||
this.appCertPublicKey = pathConfig.getUploadPath() + "file" + payment.getString("appCertPublicKey");
|
||||
this.alipayCertPublicKey = pathConfig.getUploadPath() + "file" + payment.getString("alipayCertPublicKey");
|
||||
this.alipayRootCert = pathConfig.getUploadPath() + "file" + payment.getString("alipayRootCert");
|
||||
return payment;
|
||||
}
|
||||
|
||||
public String appId(){
|
||||
return this.appId;
|
||||
}
|
||||
|
||||
public String privateKey(){
|
||||
return this.privateKey;
|
||||
}
|
||||
|
||||
public String appCertPublicKey(){
|
||||
return this.appCertPublicKey;
|
||||
}
|
||||
|
||||
public String alipayCertPublicKey(){
|
||||
return this.alipayCertPublicKey;
|
||||
}
|
||||
|
||||
public String alipayRootCert(){
|
||||
return this.alipayRootCert;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.result.RedisResult;
|
||||
import org.springframework.data.geo.Point;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.CACHE_NULL_TTL;
|
||||
|
||||
@Component
|
||||
public class CacheClient {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
public static Integer tenantId;
|
||||
|
||||
public CacheClient(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
*/
|
||||
public <T> void set(String key, T entity){
|
||||
stringRedisTemplate.opsForValue().set(prefix(key), JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant,1L,TimeUnit.DAYS)
|
||||
*/
|
||||
public <T> void set(String key, T entity, Long time, TimeUnit unit){
|
||||
stringRedisTemplate.opsForValue().set(prefix(key), JSONUtil.toJSONString(entity),time,unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* 示例 cacheClient.get(key)
|
||||
* @return merchant
|
||||
*/
|
||||
public String get(String key) {
|
||||
return stringRedisTemplate.opsForValue().get(prefix(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param clazz Merchant.class
|
||||
* @param <T>
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T get(String key, Class<T> clazz) {
|
||||
String json = stringRedisTemplate.opsForValue().get(prefix(key));
|
||||
if(StrUtil.isNotBlank(json)){
|
||||
return JSONUtil.parseObject(json, clazz);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public <T> void hPut(String key, String field, T entity) {
|
||||
stringRedisTemplate.opsForHash().put(prefix(key),field,JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param map 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public void hPutAll(String key, Map<String,String> map) {
|
||||
stringRedisTemplate.opsForHash().putAll(prefix(key),map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存(哈希类型)
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T hGet(String key, String field, Class<T> clazz) {
|
||||
Object obj = stringRedisTemplate.opsForHash().get(prefix(key), field);
|
||||
return JSONUtil.parseObject(JSONUtil.toJSONString(obj),clazz);
|
||||
}
|
||||
|
||||
public List<Object> hValues(String key){
|
||||
return stringRedisTemplate.opsForHash().values(prefix(key));
|
||||
}
|
||||
|
||||
public Long hSize(String key){
|
||||
return stringRedisTemplate.opsForHash().size(prefix(key));
|
||||
}
|
||||
|
||||
// 逻辑过期方式写入redis
|
||||
public <T> void setWithLogicalExpire(String key, T value, Long time, TimeUnit unit){
|
||||
// 设置逻辑过期时间
|
||||
final RedisResult<T> redisResult = new RedisResult<>();
|
||||
redisResult.setData(value);
|
||||
redisResult.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
|
||||
stringRedisTemplate.opsForValue().set(prefix(key),JSONUtil.toJSONString(redisResult));
|
||||
}
|
||||
|
||||
// 读取redis
|
||||
public <R,ID> R query(String keyPrefix, ID id, Class<R> clazz, Function<ID,R> dbFallback, Long time, TimeUnit unit){
|
||||
String key = keyPrefix + id;
|
||||
// 1.从redis查询缓存
|
||||
final String json = stringRedisTemplate.opsForValue().get(prefix(key));
|
||||
// 2.判断是否存在
|
||||
if (StrUtil.isNotBlank(json)) {
|
||||
// 3.存在,直接返回
|
||||
return JSONUtil.parseObject(json,clazz);
|
||||
}
|
||||
// 判断命中的是否为空值
|
||||
if (json != null) {
|
||||
return null;
|
||||
}
|
||||
// 4. 不存在,跟进ID查询数据库
|
||||
R r = dbFallback.apply(id);
|
||||
// 5. 数据库不存在,返回错误
|
||||
if(r == null){
|
||||
// 空值写入数据库
|
||||
this.set(prefix(key),"",CACHE_NULL_TTL,TimeUnit.MINUTES);
|
||||
return null;
|
||||
}
|
||||
// 写入redis
|
||||
this.set(prefix(key),r,time,unit);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加商户定位点
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoAdd("merchant-geo",merchant)
|
||||
*/
|
||||
public <T> void geoAdd(String key, Double x, Double y, String id){
|
||||
stringRedisTemplate.opsForGeo().add(prefix(key),new Point(x,y),id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除定位
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoRemove("merchant-geo",id)
|
||||
*/
|
||||
public void geoRemove(String key, Integer id){
|
||||
stringRedisTemplate.opsForGeo().remove(prefix(key),id.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public <T> void sAdd(String key, T entity){
|
||||
stringRedisTemplate.opsForSet().add(prefix(key),JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
public <T> Set<String> sMembers(String key){
|
||||
return stringRedisTemplate.opsForSet().members(prefix(key));
|
||||
}
|
||||
|
||||
// 更新排行榜
|
||||
public void zAdd(String key, Integer userId, Double value) {
|
||||
stringRedisTemplate.opsForZSet().add(prefix(key),userId.toString(),value);
|
||||
}
|
||||
// 增加元素的score值,并返回增加后的值
|
||||
public Double zIncrementScore(String key,Integer userId, Double delta){
|
||||
return stringRedisTemplate.opsForZSet().incrementScore(key, userId.toString(), delta);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> range(String key, Integer start, Integer end) {
|
||||
return stringRedisTemplate.opsForZSet().range(prefix(key), start, end);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> reverseRange(String key, Integer start, Integer end){
|
||||
return stringRedisTemplate.opsForZSet().reverseRange(prefix(key), start, end);
|
||||
}
|
||||
// 获取分数
|
||||
public Double score(String key, Object value){
|
||||
return stringRedisTemplate.opsForZSet().score(prefix(key), value);
|
||||
}
|
||||
|
||||
public void delete(String key){
|
||||
stringRedisTemplate.delete(prefix(key));
|
||||
}
|
||||
|
||||
// 存储在list头部
|
||||
public void leftPush(String key, String keyword){
|
||||
stringRedisTemplate.opsForList().leftPush(prefix(key),keyword);
|
||||
}
|
||||
|
||||
// 获取列表指定范围内的元素
|
||||
public List<String> listRange(String key,Long start, Long end){
|
||||
return stringRedisTemplate.opsForList().range(prefix(key), start, end);
|
||||
}
|
||||
|
||||
// 获取列表长度
|
||||
public Long listSize(String key){
|
||||
return stringRedisTemplate.opsForList().size(prefix(key));
|
||||
}
|
||||
|
||||
// 裁剪list
|
||||
public void listTrim(String key){
|
||||
stringRedisTemplate.opsForList().trim(prefix(key), 0L, 100L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取后台系统设置信息
|
||||
* @param keyName 键名wx-word
|
||||
* @param tenantId 租户ID
|
||||
* @return
|
||||
* key示例 cache10048:setting:wx-work
|
||||
*/
|
||||
public JSONObject getSettingInfo(String keyName,Integer tenantId){
|
||||
String key = "cache" + tenantId + ":setting:" + keyName;
|
||||
final String cache = stringRedisTemplate.opsForValue().get(key);
|
||||
assert cache != null;
|
||||
return JSON.parseObject(cache);
|
||||
}
|
||||
|
||||
/**
|
||||
* KEY前缀
|
||||
* cache[tenantId]:[key+id]
|
||||
*/
|
||||
public static String prefix(String key){
|
||||
String prefix = "cache";
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
final Integer tenantId = ((User) object).getTenantId();
|
||||
prefix = prefix.concat(tenantId.toString()).concat(":");
|
||||
}
|
||||
}
|
||||
return prefix.concat(key);
|
||||
}
|
||||
|
||||
// 组装key
|
||||
public String key(String name,Integer id){
|
||||
return name.concat(":").concat(id.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.date.DatePattern;
|
||||
import cn.hutool.core.date.DateTime;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 常用工具方法
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:22
|
||||
*/
|
||||
public class CommonUtil {
|
||||
// 生成uuid的字符
|
||||
private static final String[] chars = new String[]{
|
||||
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
|
||||
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
|
||||
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
|
||||
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
|
||||
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成8位uuid
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String randomUUID8() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
for (int i = 0; i < 8; i++) {
|
||||
String str = uuid.substring(i * 4, i * 4 + 4);
|
||||
int x = Integer.parseInt(str, 16);
|
||||
sb.append(chars[x % 0x3E]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成16位uuid
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String randomUUID16() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
for (int i = 0; i < 16; i++) {
|
||||
String str = uuid.substring(i * 2, i * 2 + 2);
|
||||
int x = Integer.parseInt(str, 16);
|
||||
sb.append(chars[x % 0x3E]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String currentTime() {
|
||||
Date date = new Date();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
|
||||
return sdf.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成10位随机用户名
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String randomUsername(String prefix) {
|
||||
Date date = new Date();
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
|
||||
String currentTime = sdf.format(date);
|
||||
return prefix + currentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单号
|
||||
* 20233191166110426
|
||||
* 20230419135802391412
|
||||
* @return
|
||||
*/
|
||||
public static String createOrderNo() {
|
||||
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
|
||||
return prefix + RandomUtil.randomNumbers(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单号
|
||||
* @param tenantId
|
||||
* 20233191166110426
|
||||
* 20230419135802391412
|
||||
* @return
|
||||
*/
|
||||
public static String createOrderNo(String tenantId) {
|
||||
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
|
||||
return prefix + tenantId + RandomUtil.randomNumbers(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成订单水流号
|
||||
* @param tenantId
|
||||
* @return
|
||||
*/
|
||||
public static String serialNo(int tenantId) {
|
||||
String prefix = DateTime.now().toString(DatePattern.PURE_DATETIME_PATTERN);
|
||||
return prefix + tenantId + RandomUtil.randomNumbers(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查List是否有重复元素
|
||||
*
|
||||
* @param list List
|
||||
* @param mapper 获取需要检查的字段的Function
|
||||
* @param <T> 数据的类型
|
||||
* @param <R> 需要检查的字段的类型
|
||||
* @return boolean
|
||||
*/
|
||||
public static <T, R> boolean checkRepeat(List<T> list, Function<? super T, ? extends R> mapper) {
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
for (int j = 0; j < list.size(); j++) {
|
||||
if (i != j && mapper.apply(list.get(i)).equals(mapper.apply(list.get(j)))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* List转为树形结构
|
||||
*
|
||||
* @param data List
|
||||
* @param parentId 顶级的parentId
|
||||
* @param parentIdMapper 获取parentId的Function
|
||||
* @param idMapper 获取id的Function
|
||||
* @param consumer 赋值children的Consumer
|
||||
* @param <T> 数据的类型
|
||||
* @param <R> parentId的类型
|
||||
* @return List<T>
|
||||
*/
|
||||
public static <T, R> List<T> toTreeData(List<T> data, R parentId,
|
||||
Function<? super T, ? extends R> parentIdMapper,
|
||||
Function<? super T, ? extends R> idMapper,
|
||||
BiConsumer<T, List<T>> consumer) {
|
||||
List<T> result = new ArrayList<>();
|
||||
for (T d : data) {
|
||||
R dParentId = parentIdMapper.apply(d);
|
||||
if (ObjectUtil.equals(parentId, dParentId)) {
|
||||
R dId = idMapper.apply(d);
|
||||
List<T> children = toTreeData(data, dId, parentIdMapper, idMapper, consumer);
|
||||
consumer.accept(d, children);
|
||||
result.add(d);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历树形结构数据
|
||||
*
|
||||
* @param data List
|
||||
* @param consumer 回调
|
||||
* @param mapper 获取children的Function
|
||||
* @param <T> 数据的类型
|
||||
*/
|
||||
public static <T> void eachTreeData(List<T> data, Consumer<T> consumer, Function<T, List<T>> mapper) {
|
||||
for (T d : data) {
|
||||
consumer.accept(d);
|
||||
List<T> children = mapper.apply(d);
|
||||
if (children != null && children.size() > 0) {
|
||||
eachTreeData(children, consumer, mapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合中的第一条数据
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 第一条数据
|
||||
*/
|
||||
public static <T> T listGetOne(List<T> records) {
|
||||
return records == null || records.size() == 0 ? null : records.get(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 支持跨域
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
*/
|
||||
public static void addCrossHeaders(HttpServletResponse response) {
|
||||
response.setHeader("Access-Control-Max-Age", "3600");
|
||||
response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
response.setHeader("Access-Control-Allow-Methods", "*");
|
||||
response.setHeader("Access-Control-Allow-Headers", "*");
|
||||
response.setHeader("Access-Control-Expose-Headers", Constants.TOKEN_HEADER_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出错误信息
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
* @param code 错误码
|
||||
* @param message 提示信息
|
||||
* @param error 错误信息
|
||||
*/
|
||||
public static void responseError(HttpServletResponse response, Integer code, String message, String error) {
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
try {
|
||||
PrintWriter out = response.getWriter();
|
||||
out.write(JSONUtil.toJSONString(new ApiResult<>(code, message, null, error)));
|
||||
out.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.DomainConstants.*;
|
||||
|
||||
public class DomainUtil {
|
||||
|
||||
/**
|
||||
* 根域名
|
||||
* @return domain.com
|
||||
*/
|
||||
public static String getRootDomain() {
|
||||
return ROOT_DOMAIN;
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理后台地址
|
||||
* @return https://{tenantId}.websoft.top
|
||||
*/
|
||||
public static String getAdminUrl(String tenantId) {
|
||||
return PREFIX.concat(tenantId).concat(ADMIN_SUFFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用网址
|
||||
* @param tenantId
|
||||
* @return https://{tenantId}.wsdns.cn
|
||||
*/
|
||||
public static String getSiteUrl(String tenantId){
|
||||
return PREFIX.concat(tenantId).concat(WEB_SUFFIX);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.img.ImgUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.io.IORuntimeException;
|
||||
import cn.hutool.core.io.IoUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.apache.tika.Tika;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URLEncoder;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 文件上传下载工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-14 08:38:53
|
||||
*/
|
||||
public class FileServerUtil {
|
||||
// 除 text/* 外也需要设置输出编码的 content-type
|
||||
private final static List<String> SET_CHARSET_CONTENT_TYPES = Arrays.asList(
|
||||
"application/json",
|
||||
"application/javascript"
|
||||
);
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*
|
||||
* @param file MultipartFile
|
||||
* @param directory 文件保存的目录
|
||||
* @param uuidName 是否用uuid命名
|
||||
* @return File
|
||||
*/
|
||||
public static File upload(MultipartFile file, String directory, boolean uuidName)
|
||||
throws IOException, IllegalStateException {
|
||||
File outFile = getUploadFile(file.getOriginalFilename(), directory, uuidName);
|
||||
if (!outFile.getParentFile().exists()) {
|
||||
if (!outFile.getParentFile().mkdirs()) {
|
||||
throw new RuntimeException("make directory fail");
|
||||
}
|
||||
}
|
||||
file.transferTo(outFile);
|
||||
return outFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传base64格式文件
|
||||
*
|
||||
* @param base64 base64编码字符
|
||||
* @param fileName 文件名称, 为空使用uuid命名
|
||||
* @param directory 文件保存的目录
|
||||
* @return File
|
||||
*/
|
||||
public static File upload(String base64, String fileName, String directory)
|
||||
throws FileNotFoundException, IORuntimeException {
|
||||
if (StrUtil.isBlank(base64) || !base64.startsWith("data:image/") || !base64.contains(";base64,")) {
|
||||
throw new RuntimeException("base64 data error");
|
||||
}
|
||||
String suffix = "." + base64.substring(11, base64.indexOf(";")); // 获取文件后缀
|
||||
boolean uuidName = StrUtil.isBlank(fileName);
|
||||
File outFile = getUploadFile(uuidName ? suffix : fileName, directory, uuidName);
|
||||
byte[] bytes = Base64.getDecoder().decode(base64.substring(base64.indexOf(";") + 8).getBytes());
|
||||
IoUtil.write(new FileOutputStream(outFile), true, bytes);
|
||||
return outFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上传文件位置
|
||||
*
|
||||
* @param name 文件名称
|
||||
* @param directory 上传目录
|
||||
* @param uuidName 是否使用uuid命名
|
||||
* @return File
|
||||
*/
|
||||
public static File getUploadFile(String name, String directory, boolean uuidName) {
|
||||
// 当前日期作为上传子目录
|
||||
String dir = new SimpleDateFormat("yyyyMMdd/").format(new Date());
|
||||
// 获取文件后缀
|
||||
String suffix = (name == null || !name.contains(".")) ? "" : name.substring(name.lastIndexOf("."));
|
||||
// 使用uuid命名
|
||||
if (uuidName || name == null) {
|
||||
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
|
||||
return new File(directory, dir + uuid + suffix);
|
||||
}
|
||||
// 使用原名称, 存在相同则加(1)
|
||||
File file = new File(directory, dir + name);
|
||||
String prefix = StrUtil.removeSuffix(name, suffix);
|
||||
int sameSize = 2;
|
||||
while (file.exists()) {
|
||||
file = new File(directory, dir + prefix + "(" + sameSize + ")" + suffix);
|
||||
sameSize++;
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看文件, 支持断点续传
|
||||
*
|
||||
* @param file 文件
|
||||
* @param pdfDir office转pdf输出目录
|
||||
* @param officeHome openOffice安装目录
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void preview(File file, String pdfDir, String officeHome,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
preview(file, false, null, pdfDir, officeHome, response, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看文件, 支持断点续传
|
||||
*
|
||||
* @param file 文件
|
||||
* @param forceDownload 是否强制下载
|
||||
* @param fileName 强制下载的文件名称
|
||||
* @param pdfDir office转pdf输出目录
|
||||
* @param officeHome openOffice安装目录
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void preview(File file, boolean forceDownload, String fileName, String pdfDir, String officeHome,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
CommonUtil.addCrossHeaders(response);
|
||||
if (file == null || !file.exists()) {
|
||||
outNotFund(response);
|
||||
return;
|
||||
}
|
||||
if (forceDownload) {
|
||||
setDownloadHeader(response, StrUtil.isBlank(fileName) ? file.getName() : fileName);
|
||||
} else {
|
||||
// office转pdf预览
|
||||
if (OpenOfficeUtil.canConverter(file.getName())) {
|
||||
File pdfFile = OpenOfficeUtil.converterToPDF(file.getAbsolutePath(), pdfDir, officeHome);
|
||||
if (pdfFile != null) {
|
||||
file = pdfFile;
|
||||
}
|
||||
}
|
||||
// 获取文件类型
|
||||
String contentType = getContentType(file);
|
||||
if (contentType != null) {
|
||||
response.setContentType(contentType);
|
||||
// 设置编码
|
||||
if (contentType.startsWith("text/") || SET_CHARSET_CONTENT_TYPES.contains(contentType)) {
|
||||
try {
|
||||
String charset = JChardetFacadeUtil.detectCodepage(file.toURI().toURL());
|
||||
if (charset != null) {
|
||||
response.setCharacterEncoding(charset);
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setDownloadHeader(response, file.getName());
|
||||
}
|
||||
}
|
||||
response.setHeader("Cache-Control", "public");
|
||||
output(file, response, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查看缩略图
|
||||
*
|
||||
* @param file 原文件
|
||||
* @param thumbnail 缩略图文件
|
||||
* @param size 缩略图文件的最大值(kb)
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void previewThumbnail(File file, File thumbnail, Integer size,
|
||||
HttpServletResponse response, HttpServletRequest request) {
|
||||
// 如果是图片并且缩略图不存在则生成
|
||||
if (!thumbnail.exists() && isImage(file)) {
|
||||
long fileSize = file.length();
|
||||
if ((fileSize / 1024) > size) {
|
||||
try {
|
||||
if (thumbnail.getParentFile().mkdirs()) {
|
||||
System.out.println("生成缩略图1>>>>>>>>>>>>>>>> = " + thumbnail);
|
||||
ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
|
||||
if (thumbnail.exists() && thumbnail.length() > file.length()) {
|
||||
FileUtil.copy(file, thumbnail, true);
|
||||
}
|
||||
}else{
|
||||
System.out.println("生成缩略图2>>>>>>>>>>>>>>>> = " + thumbnail);
|
||||
ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
|
||||
if (thumbnail.exists() && thumbnail.length() > file.length()) {
|
||||
FileUtil.copy(file, thumbnail, true);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
preview(file, null, null, response, request);
|
||||
return;
|
||||
}
|
||||
}
|
||||
preview(thumbnail.exists() ? thumbnail : file, null, null, response, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流, 支持断点续传
|
||||
*
|
||||
* @param file 文件
|
||||
* @param response HttpServletResponse
|
||||
* @param request HttpServletRequest
|
||||
*/
|
||||
public static void output(File file, HttpServletResponse response, HttpServletRequest request) {
|
||||
long length = file.length(); // 文件总大小
|
||||
long start = 0, to = length - 1; // 开始读取位置, 结束读取位置
|
||||
long lastModified = file.lastModified(); // 文件修改时间
|
||||
response.setHeader("Accept-Ranges", "bytes");
|
||||
response.setHeader("ETag", "\"" + length + "-" + lastModified + "\"");
|
||||
response.setHeader("Last-Modified", new Date(lastModified).toString());
|
||||
String range = request.getHeader("Range");
|
||||
if (range != null) {
|
||||
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||
String[] ranges = range.replace("bytes=", "").split("-");
|
||||
start = Long.parseLong(ranges[0].trim());
|
||||
if (ranges.length > 1) {
|
||||
to = Long.parseLong(ranges[1].trim());
|
||||
}
|
||||
response.setHeader("Content-Range", "bytes " + start + "-" + to + "/" + length);
|
||||
}
|
||||
response.setHeader("Content-Length", String.valueOf(to - start + 1));
|
||||
try {
|
||||
output(file, response.getOutputStream(), 2048, start, to);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流
|
||||
*
|
||||
* @param file 文件
|
||||
* @param os 输出流
|
||||
*/
|
||||
public static void output(File file, OutputStream os) {
|
||||
output(file, os, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流
|
||||
*
|
||||
* @param file 文件
|
||||
* @param os 输出流
|
||||
* @param size 读取缓冲区大小
|
||||
*/
|
||||
public static void output(File file, OutputStream os, Integer size) {
|
||||
output(file, os, size, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出文件流, 支持分片
|
||||
*
|
||||
* @param file 文件
|
||||
* @param os 输出流
|
||||
* @param size 读取缓冲区大小
|
||||
* @param start 开始位置
|
||||
* @param to 结束位置
|
||||
*/
|
||||
public static void output(File file, OutputStream os, Integer size, Long start, Long to) {
|
||||
BufferedInputStream is = null;
|
||||
try {
|
||||
is = new BufferedInputStream(new FileInputStream(file));
|
||||
if (start != null) {
|
||||
long skip = is.skip(start);
|
||||
if (skip < start) {
|
||||
System.out.println("ERROR: skip fail[ skipped=" + skip + ", start= " + start + " ]");
|
||||
}
|
||||
to = to - start + 1;
|
||||
}
|
||||
byte[] bytes = new byte[size == null ? 2048 : size];
|
||||
int len;
|
||||
if (to == null) {
|
||||
while ((len = is.read(bytes)) != -1) {
|
||||
os.write(bytes, 0, len);
|
||||
}
|
||||
} else {
|
||||
while (to > 0 && (len = is.read(bytes)) != -1) {
|
||||
os.write(bytes, 0, to < len ? (int) ((long) to) : len);
|
||||
to -= len;
|
||||
}
|
||||
}
|
||||
os.flush();
|
||||
} catch (IOException ignored) {
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (os != null) {
|
||||
try {
|
||||
os.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
if (is != null) {
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件类型
|
||||
*
|
||||
* @param file 文件
|
||||
* @return String
|
||||
*/
|
||||
public static String getContentType(File file) {
|
||||
String contentType = null;
|
||||
if (file.exists()) {
|
||||
try {
|
||||
contentType = new Tika().detect(file);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return contentType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件是否是图片类型
|
||||
*
|
||||
* @param file 文件
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isImage(File file) {
|
||||
return isImage(getContentType(file));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件是否是图片类型
|
||||
*
|
||||
* @param contentType 文件类型
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isImage(String contentType) {
|
||||
return contentType != null && contentType.startsWith("image/");
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置下载文件的header
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
* @param fileName 文件名称
|
||||
*/
|
||||
public static void setDownloadHeader(HttpServletResponse response, String fileName) {
|
||||
response.setContentType("application/force-download");
|
||||
try {
|
||||
fileName = URLEncoder.encode(fileName, "utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出404错误页面
|
||||
*
|
||||
* @param response HttpServletResponse
|
||||
*/
|
||||
public static void outNotFund(HttpServletResponse response) {
|
||||
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
|
||||
outMessage("404 Not Found", null, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出错误页面
|
||||
*
|
||||
* @param title 标题
|
||||
* @param message 内容
|
||||
* @param response HttpServletResponse
|
||||
*/
|
||||
public static void outMessage(String title, String message, HttpServletResponse response) {
|
||||
response.setContentType("text/html;charset=UTF-8");
|
||||
try {
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.write("<!doctype html>");
|
||||
writer.write("<title>" + title + "</title>");
|
||||
writer.write("<h1 style=\"text-align: center\">" + title + "</h1>");
|
||||
if (message != null) {
|
||||
writer.write(message);
|
||||
}
|
||||
writer.write("<hr/><p style=\"text-align: center\">WebSoft File Server</p>");
|
||||
writer.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.alibaba.fastjson2.TypeReference;
|
||||
import com.aliyun.green20220302.Client;
|
||||
import com.aliyun.green20220302.models.*;
|
||||
import com.aliyun.teaopenapi.models.Config;
|
||||
import com.aliyun.teautil.models.RuntimeOptions;
|
||||
import com.gxwebsoft.common.core.enums.GreenWebType;
|
||||
import com.gxwebsoft.common.system.vo.faceId.HeadPortraitResult;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
|
||||
@Component
|
||||
public class GreenWebUtils {
|
||||
private static Client contentGreenClient = null;
|
||||
|
||||
static final String accessKeyId = "LTAI5t8UTh8CTXEi2dYxobhj";
|
||||
static final String accessKeySecret = "fNdJOT4KAjrVrzHNAcSJuUCy9ZljD9";
|
||||
|
||||
static final String[] badAudioLabel = {"violence", "political_content", "sexual_content", "sexual_sounds", "contraband", "profanity", "religion", "cyberbullying", "negative_content", "specified_speaking", "specified_lyrics"};
|
||||
// static final String[] badVideoLabel = {"pornographic_adultContent","pornographic_adultToys","pornographic_artwork","pornographic_adultContent_tii","sexual_suggestiveContent","sexual_breastNudity","sexual_cleavage","sexual_femaleUnderwear","sexual_maleTopless","sexual_femaleShoulder","sexual_cartoon","sexual_pregnancy","sexual_underage","political_politicalFigure_1","political_politicalFigure_2","political_politicalFigure_3","political_politicalFigure_name_tii",""};
|
||||
|
||||
private static class ContentGreenClientHolder {
|
||||
private static final Client INSTANCE = createContentGreenClient();
|
||||
}
|
||||
|
||||
private static Client createContentGreenClient() {
|
||||
Config config = new Config();
|
||||
config.setAccessKeyId(accessKeyId);
|
||||
config.setAccessKeySecret(accessKeySecret);
|
||||
config.setRegionId("cn-shenzhen");
|
||||
config.setEndpoint("green-cip.cn-shenzhen.aliyuncs.com");
|
||||
config.setReadTimeout(6000);
|
||||
config.setConnectTimeout(3000);
|
||||
try {
|
||||
return new Client(config);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static Client getContentGreenClient() {
|
||||
|
||||
if (contentGreenClient == null) {
|
||||
contentGreenClient = ContentGreenClientHolder.INSTANCE;
|
||||
}
|
||||
return contentGreenClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文本审核
|
||||
*
|
||||
* @param text
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
public static boolean testText(String text, GreenWebType type) {
|
||||
if (!StringUtils.hasText(text)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
JSONObject serviceParameters = new JSONObject();
|
||||
serviceParameters.put("content", text);
|
||||
|
||||
// 创建RuntimeObject实例并设置运行参数。
|
||||
RuntimeOptions runtime = new RuntimeOptions();
|
||||
runtime.readTimeout = 10000;
|
||||
runtime.connectTimeout = 10000;
|
||||
|
||||
TextModerationRequest textModerationRequest = new TextModerationRequest();
|
||||
textModerationRequest.setService(type.name());
|
||||
textModerationRequest.setServiceParameters(serviceParameters.toJSONString());
|
||||
|
||||
// try {
|
||||
TextModerationResponse response = null;
|
||||
try {
|
||||
response = getContentGreenClient().textModerationWithOptions(textModerationRequest, runtime);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
if (response.statusCode != 200) {
|
||||
return false;
|
||||
}
|
||||
|
||||
TextModerationResponseBody result = response.getBody();
|
||||
Integer code = result.getCode();
|
||||
if (code != null && code == 200) {
|
||||
TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
|
||||
return !StringUtils.hasText(data.getReason());
|
||||
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片审核
|
||||
*
|
||||
* @param imgUrl
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
|
||||
public static boolean testImage(String imgUrl, GreenWebType type) {
|
||||
|
||||
if(!imgUrl.contains("?x-oss-process=image/resize")) {
|
||||
imgUrl += "?x-oss-process=image/resize,w_750/quality,Q_90";
|
||||
}
|
||||
|
||||
Map<String, String> serviceParameters = new HashMap<>();
|
||||
//公网可访问的URL。
|
||||
serviceParameters.put("imageUrl", imgUrl);
|
||||
serviceParameters.put("dataId", UUID.randomUUID().toString());
|
||||
|
||||
ImageModerationRequest request = new ImageModerationRequest();
|
||||
// 图片检测service: baselineCheck通用基线检测。
|
||||
request.setService(type.name());
|
||||
request.setServiceParameters(JSON.toJSONString(serviceParameters));
|
||||
|
||||
RuntimeOptions runtime = new RuntimeOptions();
|
||||
runtime.readTimeout = 10000;
|
||||
runtime.connectTimeout = 10000;
|
||||
ImageModerationResponse response = null;
|
||||
try {
|
||||
response = getContentGreenClient().imageModerationWithOptions(request, runtime);
|
||||
System.out.println(response);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
|
||||
ImageModerationResponseBody body = response.getBody();
|
||||
|
||||
String[] unSafeLabelArr = {"pornographic_adultContent_tii","pornographic_adultContent","sexual_suggestiveContent",""};
|
||||
if (body.getCode() == 200) {
|
||||
ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
|
||||
System.out.println("dataId=" + data.getDataId());
|
||||
List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
|
||||
for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
|
||||
|
||||
if (!"nonLabel".equals(result.getLabel())) {
|
||||
System.out.println(String.format("Label: %s,Confidence: %f",result.getLabel(),result.getConfidence()));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 视频审核(异步)
|
||||
*
|
||||
* @param videoUrl
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
public static String testVideo(String videoUrl, GreenWebType type) {
|
||||
|
||||
JSONObject serviceParameters = new JSONObject();
|
||||
serviceParameters.put("url", videoUrl);
|
||||
|
||||
VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
|
||||
// 检测类型:videoDetection
|
||||
videoModerationRequest.setService(type.name());
|
||||
videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());
|
||||
|
||||
|
||||
try {
|
||||
VideoModerationResponse response = getContentGreenClient().videoModeration(videoModerationRequest);
|
||||
if (response.getStatusCode() == 200) {
|
||||
VideoModerationResponseBody result = response.getBody();
|
||||
System.out.println(JSON.toJSONString(result));
|
||||
System.out.println("requestId = " + result.getRequestId());
|
||||
System.out.println("code = " + result.getCode());
|
||||
System.out.println("msg = " + result.getMessage());
|
||||
Integer code = result.getCode();
|
||||
if (200 == code) {
|
||||
VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
|
||||
return data.taskId;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取视频审核结果
|
||||
*
|
||||
* @param taskId
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
public static boolean getTestVideoResult(String taskId, GreenWebType type) {
|
||||
|
||||
|
||||
JSONObject serviceParameters = new JSONObject();
|
||||
// 提交任务时返回的taskId。
|
||||
serviceParameters.put("taskId", taskId);
|
||||
VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
|
||||
videoModerationResultRequest.setService(type.name());
|
||||
videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
|
||||
try {
|
||||
VideoModerationResultResponse response = getContentGreenClient().videoModerationResult(videoModerationResultRequest);
|
||||
if (response.getStatusCode() == 200) {
|
||||
VideoModerationResultResponseBody result = response.getBody();
|
||||
System.out.println("requestId=" + result.getRequestId());
|
||||
System.out.println("code=" + result.getCode());
|
||||
System.out.println("msg=" + result.getMessage());
|
||||
if (200 == result.getCode()) {
|
||||
VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
|
||||
VideoModerationResultResponseBody.VideoModerationResultResponseBodyDataAudioResult audioResult = data.getAudioResult();
|
||||
VideoModerationResultResponseBody.VideoModerationResultResponseBodyDataFrameResult frameResult = data.getFrameResult();
|
||||
boolean hasBadAudio = audioResult.sliceDetails.stream().filter(w -> {
|
||||
String labels = w.getLabels();
|
||||
String[] labelArr = labels.split(",");
|
||||
return Arrays.stream(labelArr).filter(l -> {
|
||||
return Arrays.stream(badAudioLabel).filter(b -> b.equals(l)).findFirst().isPresent();
|
||||
}).findFirst().isPresent();
|
||||
}).findFirst().isPresent();
|
||||
if (hasBadAudio) {
|
||||
return false;
|
||||
}
|
||||
boolean hasBadVideo = frameResult.getFrames().stream().filter(w -> {
|
||||
return w.getResults().stream().filter(r -> {
|
||||
return r.getResult().stream().filter(r2 -> {
|
||||
return !"nonLabel".equals(r2.label);
|
||||
}).findFirst().isPresent();
|
||||
}).findFirst().isPresent();
|
||||
}).findFirst().isPresent();
|
||||
if (hasBadVideo) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 鉴别头像是否是真人头像(非卡通) 2. 鉴别图片是否有性感,色情信息 3. 鉴别头像是否有广告,敏感信息,以及二维码等 4. 鉴别头像性别。
|
||||
*
|
||||
* @param imageBase64
|
||||
* @param imageType
|
||||
* @param genter
|
||||
* @return
|
||||
*/
|
||||
public static boolean testAvatar(String imageBase64, String imageType, Integer genter) {
|
||||
String host = "https://edishead.market.alicloudapi.com";
|
||||
String path = "/faceId/headPortrait/getResult";
|
||||
String method = "POST";
|
||||
String appcode = "566b5786c5874464909d8c0b7f64cdc7";
|
||||
Map<String, String> headers = new HashMap<String, String>();
|
||||
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
|
||||
headers.put("Authorization", "APPCODE " + appcode);
|
||||
//根据API的要求,定义相对应的Content-Type
|
||||
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
|
||||
Map<String, String> querys = new HashMap<String, String>();
|
||||
Map<String, String> bodys = new HashMap<String, String>();
|
||||
bodys.put("image", imageBase64);
|
||||
bodys.put("imageType", imageType);
|
||||
HttpResponse response = null;
|
||||
try {
|
||||
response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
|
||||
HttpEntity entity = response.getEntity();
|
||||
String string = EntityUtils.toString(entity);
|
||||
HeadPortraitResult result = JSONObject.parseObject(string, new TypeReference<HeadPortraitResult>() {
|
||||
});
|
||||
if (!"0000".equals(result.getCode())) {
|
||||
return false;
|
||||
}
|
||||
if (!"normal".equals(result.getPorn()) || !"normal".equals(result.getAd())) {
|
||||
return false;
|
||||
}
|
||||
if (result.getFaceCount() != 1 || result.getCartoonImg()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!genter.equals(result.getGenterList()[0])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
System.out.println(response.toString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpDelete;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpPut;
|
||||
import org.apache.http.conn.ClientConnectionManager;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.entity.ByteArrayEntity;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpUtils {
|
||||
|
||||
/**
|
||||
* get
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doGet(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpGet request = new HttpGet(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* post form
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param bodys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPost(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
Map<String, String> bodys)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (bodys != null) {
|
||||
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
|
||||
|
||||
for (String key : bodys.keySet()) {
|
||||
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
|
||||
}
|
||||
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
|
||||
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
|
||||
request.setEntity(formEntity);
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Post String
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPost(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
String body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
request.setEntity(new StringEntity(body, "utf-8"));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Post stream
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPost(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
byte[] body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPost request = new HttpPost(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (body != null) {
|
||||
request.setEntity(new ByteArrayEntity(body));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put String
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPut(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
String body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(body)) {
|
||||
request.setEntity(new StringEntity(body, "utf-8"));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Put stream
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @param body
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doPut(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys,
|
||||
byte[] body)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpPut request = new HttpPut(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
if (body != null) {
|
||||
request.setEntity(new ByteArrayEntity(body));
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete
|
||||
*
|
||||
* @param host
|
||||
* @param path
|
||||
* @param method
|
||||
* @param headers
|
||||
* @param querys
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static HttpResponse doDelete(String host, String path, String method,
|
||||
Map<String, String> headers,
|
||||
Map<String, String> querys)
|
||||
throws Exception {
|
||||
HttpClient httpClient = wrapClient(host);
|
||||
|
||||
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
|
||||
for (Map.Entry<String, String> e : headers.entrySet()) {
|
||||
request.addHeader(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
return httpClient.execute(request);
|
||||
}
|
||||
|
||||
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
|
||||
StringBuilder sbUrl = new StringBuilder();
|
||||
sbUrl.append(host);
|
||||
if (!StringUtils.isBlank(path)) {
|
||||
sbUrl.append(path);
|
||||
}
|
||||
if (null != querys) {
|
||||
StringBuilder sbQuery = new StringBuilder();
|
||||
for (Map.Entry<String, String> query : querys.entrySet()) {
|
||||
if (0 < sbQuery.length()) {
|
||||
sbQuery.append("&");
|
||||
}
|
||||
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
|
||||
sbQuery.append(query.getValue());
|
||||
}
|
||||
if (!StringUtils.isBlank(query.getKey())) {
|
||||
sbQuery.append(query.getKey());
|
||||
if (!StringUtils.isBlank(query.getValue())) {
|
||||
sbQuery.append("=");
|
||||
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (0 < sbQuery.length()) {
|
||||
sbUrl.append("?").append(sbQuery);
|
||||
}
|
||||
}
|
||||
|
||||
return sbUrl.toString();
|
||||
}
|
||||
|
||||
private static HttpClient wrapClient(String host) {
|
||||
HttpClient httpClient = new DefaultHttpClient();
|
||||
if (host.startsWith("https://")) {
|
||||
sslClient(httpClient);
|
||||
}
|
||||
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
private static void sslClient(HttpClient httpClient) {
|
||||
try {
|
||||
SSLContext ctx = SSLContext.getInstance("TLS");
|
||||
X509TrustManager tm = new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
public void checkClientTrusted(X509Certificate[] xcs, String str) {
|
||||
|
||||
}
|
||||
public void checkServerTrusted(X509Certificate[] xcs, String str) {
|
||||
|
||||
}
|
||||
};
|
||||
ctx.init(null, new TrustManager[] { tm }, null);
|
||||
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
|
||||
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
||||
ClientConnectionManager ccm = httpClient.getConnectionManager();
|
||||
SchemeRegistry registry = ccm.getSchemeRegistry();
|
||||
registry.register(new Scheme("https", 443, ssf));
|
||||
} catch (KeyManagementException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.codec.Base64Encoder;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class ImageUtil {
|
||||
public static String ImageBase64(String imgUrl) {
|
||||
URL url = null;
|
||||
InputStream is = null;
|
||||
ByteArrayOutputStream outStream = null;
|
||||
HttpURLConnection httpUrl = null;
|
||||
try{
|
||||
url = new URL(imgUrl);
|
||||
httpUrl = (HttpURLConnection) url.openConnection();
|
||||
httpUrl.connect();
|
||||
httpUrl.getInputStream();
|
||||
is = httpUrl.getInputStream();
|
||||
|
||||
outStream = new ByteArrayOutputStream();
|
||||
//创建一个Buffer字符串
|
||||
byte[] buffer = new byte[1024];
|
||||
//每次读取的字符串长度,如果为-1,代表全部读取完毕
|
||||
int len = 0;
|
||||
//使用一个输入流从buffer里把数据读取出来
|
||||
while( (len=is.read(buffer)) != -1 ){
|
||||
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
|
||||
outStream.write(buffer, 0, len);
|
||||
}
|
||||
// 对字节数组Base64编码
|
||||
return new Base64Encoder().encode(outStream.toByteArray());
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally{
|
||||
if(is != null)
|
||||
{
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if(outStream != null)
|
||||
{
|
||||
try {
|
||||
outStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if(httpUrl != null)
|
||||
{
|
||||
httpUrl.disconnect();
|
||||
}
|
||||
}
|
||||
return imgUrl;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,69 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectWriter;
|
||||
|
||||
/**
|
||||
* JSON解析工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:39
|
||||
*/
|
||||
public class JSONUtil {
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
|
||||
|
||||
/**
|
||||
* 对象转json字符串
|
||||
*
|
||||
* @param value 对象
|
||||
* @return String
|
||||
*/
|
||||
public static String toJSONString(Object value) {
|
||||
return toJSONString(value, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对象转json字符串
|
||||
*
|
||||
* @param value 对象
|
||||
* @param pretty 是否格式化输出
|
||||
* @return String
|
||||
*/
|
||||
public static String toJSONString(Object value, boolean pretty) {
|
||||
if (value != null) {
|
||||
if (value instanceof String) {
|
||||
return (String) value;
|
||||
}
|
||||
try {
|
||||
if (pretty) {
|
||||
return objectWriter.writeValueAsString(value);
|
||||
}
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* json字符串转对象
|
||||
*
|
||||
* @param json String
|
||||
* @param clazz Class
|
||||
* @return T
|
||||
*/
|
||||
public static <T> T parseObject(String json, Class<T> clazz) {
|
||||
if (StrUtil.isNotBlank(json) && clazz != null) {
|
||||
try {
|
||||
return objectMapper.readValue(json, clazz);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.extra.qrcode.QrCodeUtil;
|
||||
import cn.hutool.extra.qrcode.QrConfig;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* 常用工具方法
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:22
|
||||
*/
|
||||
public class MyQrCodeUtil {
|
||||
private static final String logoUrl = "https://file.wsdns.cn/20230430/6fa31aca3b0d47af98a149cf2dd26a4f.jpeg";
|
||||
|
||||
/**
|
||||
* 生成二维码
|
||||
* 用户ID
|
||||
*/
|
||||
public static String getCode(Integer loginUserId) throws IOException {
|
||||
return createQrCode(loginUserId,loginUserId.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成二维码
|
||||
* 支持自定义类型和内容
|
||||
*/
|
||||
public String getCode(Integer loginUserId,String content) throws IOException {
|
||||
return createQrCode(loginUserId,content);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带水印的二维码
|
||||
* @return https://file.gxwebsoft.com/qrcode/870.jpg?v=1682925307569
|
||||
*/
|
||||
public static String createQrCode(Integer userId,String content) throws IOException {
|
||||
// 将URL转为BufferedImage
|
||||
BufferedImage bufferedImage = ImageIO.read(new URL(logoUrl));
|
||||
// 生成二维码
|
||||
QrConfig config = new QrConfig(300, 300);
|
||||
// 设置边距,既二维码和背景之间的边距
|
||||
config.setMargin(1);
|
||||
// 附带小logo
|
||||
config.setImg(bufferedImage);
|
||||
// 保存路径
|
||||
// String filePath = "/Users/gxwebsoft/Documents/uploads/" + "file/qrcode/" + userId + ".jpg";
|
||||
String filePath = "/www/wwwroot/file.ws/" + "file/qrcode/" + userId + ".jpg";
|
||||
String qrcodeUrl = "https://file.gxwebsoft.com/qrcode/" + userId + ".jpg" + "?v=" + DateUtil.current();
|
||||
// 生成二维码
|
||||
System.out.println("config = " + config);
|
||||
System.out.println("con = " + content);
|
||||
System.out.println("filePath = " + filePath);
|
||||
QrCodeUtil.generate(content, config, FileUtil.file(filePath));
|
||||
return qrcodeUrl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.artofsolving.jodconverter.OfficeDocumentConverter;
|
||||
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
|
||||
import org.artofsolving.jodconverter.office.OfficeManager;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* OpenOfficeUtil
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2018-12-14 08:38:19
|
||||
*/
|
||||
public class OpenOfficeUtil {
|
||||
// 支持转换pdf的文件后缀列表
|
||||
private static final String[] CAN_CONVERTER_FILES = new String[]{
|
||||
"doc", "docx", "xls", "xlsx", "ppt", "pptx"
|
||||
};
|
||||
|
||||
/**
|
||||
* 文件转pdf
|
||||
*
|
||||
* @param filePath 源文件路径
|
||||
* @param outDir 输出目录
|
||||
* @param officeHome OpenOffice安装路径
|
||||
* @return File
|
||||
*/
|
||||
public static File converterToPDF(String filePath, String outDir, String officeHome) {
|
||||
return converterToPDF(filePath, outDir, officeHome, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件转pdf
|
||||
*
|
||||
* @param filePath 源文件路径
|
||||
* @param outDir 输出目录
|
||||
* @param officeHome OpenOffice安装路径
|
||||
* @param cache 是否使用上次转换过的文件
|
||||
* @return File
|
||||
*/
|
||||
public static File converterToPDF(String filePath, String outDir, String officeHome, boolean cache) {
|
||||
if (StrUtil.isBlank(filePath)) {
|
||||
return null;
|
||||
}
|
||||
File srcFile = new File(filePath);
|
||||
if (!srcFile.exists()) {
|
||||
return null;
|
||||
}
|
||||
// 是否转换过
|
||||
String outPath = Base64.getEncoder().encodeToString(filePath.getBytes())
|
||||
.replace("/", "-").replace("+", "-");
|
||||
File outFile = new File(outDir, outPath + ".pdf");
|
||||
if (cache && outFile.exists()) {
|
||||
return outFile;
|
||||
}
|
||||
// 转换
|
||||
OfficeManager officeManager = null;
|
||||
try {
|
||||
officeManager = getOfficeManager(officeHome);
|
||||
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
|
||||
return converterFile(srcFile, outFile, converter);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (officeManager != null) {
|
||||
officeManager.stop();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换文件
|
||||
*
|
||||
* @param inFile 源文件
|
||||
* @param outFile 输出文件
|
||||
* @param converter OfficeDocumentConverter
|
||||
* @return File
|
||||
*/
|
||||
public static File converterFile(File inFile, File outFile, OfficeDocumentConverter converter) {
|
||||
if (!outFile.getParentFile().exists()) {
|
||||
if (!outFile.getParentFile().mkdirs()) {
|
||||
return outFile;
|
||||
}
|
||||
}
|
||||
converter.convert(inFile, outFile);
|
||||
return outFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文件后缀是否可以转换pdf
|
||||
*
|
||||
* @param path 文件路径
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean canConverter(String path) {
|
||||
try {
|
||||
String suffix = path.substring(path.lastIndexOf(".") + 1);
|
||||
return Arrays.asList(CAN_CONVERTER_FILES).contains(suffix);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接并启动OpenOffice
|
||||
*
|
||||
* @param officeHome OpenOffice安装路径
|
||||
* @return OfficeManager
|
||||
*/
|
||||
public static OfficeManager getOfficeManager(String officeHome) {
|
||||
if (officeHome == null || officeHome.trim().isEmpty()) return null;
|
||||
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
|
||||
config.setOfficeHome(officeHome); // 设置OpenOffice安装目录
|
||||
OfficeManager officeManager = config.buildOfficeManager();
|
||||
officeManager.start(); // 启动OpenOffice服务
|
||||
return officeManager;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import com.gxwebsoft.common.system.vo.PushMessageVO;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 个推推送消息工具类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:39
|
||||
*/
|
||||
@Component
|
||||
public class PushUtil {
|
||||
@Resource
|
||||
RedisUtil redisUtil;
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
private static final String url = "https://fc-mp-ba98f1e0-713d-457b-a0a4-27a7939371e6.next.bspapp.com/unipush";
|
||||
|
||||
/**
|
||||
* 获取鉴权token
|
||||
* @return
|
||||
*/
|
||||
public String getToken() {
|
||||
String key = "token:oOVaDtYDYQ8q3lNjhLh401";
|
||||
|
||||
if(redisUtil.get(key) != null){
|
||||
return redisUtil.get(key);
|
||||
}
|
||||
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
long timeMillis = System.currentTimeMillis();
|
||||
String sign = SecureUtil.sha256("AC6IghgsUx7Mwjb7G5eqv" + timeMillis + "JVRkOCXXzA6EyE2Fi5sPr9");
|
||||
map.put("sign",sign);
|
||||
map.put("timestamp",timeMillis);
|
||||
map.put("appkey","AC6IghgsUx7Mwjb7G5eqv");
|
||||
final String body = HttpRequest.post(url.concat("/auth")).body(JSONUtil.toJSONString(map)).execute().body();
|
||||
final JSONObject jsonObject = JSONObject.parseObject(body);
|
||||
final String data = jsonObject.getString("data");
|
||||
final JSONObject jsonData = JSONObject.parseObject(data);
|
||||
|
||||
final String token = jsonData.getString("token");
|
||||
final Long expireTime = Long.valueOf(jsonData.getString("expire_time"));
|
||||
// 保存token
|
||||
|
||||
redisUtil.set(key,token, expireTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS);
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行cid单推
|
||||
* cid数组,只能填一个cid
|
||||
*
|
||||
*/
|
||||
public static boolean toSingle(PushMessageVO pushMessageVO){
|
||||
final String body = HttpRequest.post(url).body(JSONUtil.toJSONString(pushMessageVO)).execute().body();
|
||||
JSONObject jsonObject = JSONObject.parseObject(body);
|
||||
if("success".equals(jsonObject.get("errMsg"))){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public boolean toSingle(Integer userId,String title, String content,String type, Object obj){
|
||||
PushMessageVO.Payload payload = new PushMessageVO.Payload();
|
||||
payload.setType(type);
|
||||
payload.setData(obj);
|
||||
|
||||
String clientId = userService.getById(userId).getClientId();
|
||||
HashSet<String> clientIds = new HashSet<>();
|
||||
clientIds.add(clientId);
|
||||
|
||||
PushMessageVO messageVO = PushMessageVO.builder().title(title).content(content).payload(payload).push_clientid(clientIds).build();
|
||||
|
||||
final String body = HttpRequest.post(url).body(JSONUtil.toJSONString(messageVO)).execute().body();
|
||||
|
||||
JSONObject jsonObject = JSONObject.parseObject(body);
|
||||
if("success".equals(jsonObject.get("errMsg"))){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.result.RedisResult;
|
||||
import org.springframework.data.geo.Point;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.CACHE_NULL_TTL;
|
||||
|
||||
@Component
|
||||
public class RedisUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
public static Integer tenantId;
|
||||
|
||||
public RedisUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant)
|
||||
*/
|
||||
public <T> void set(String key, T entity){
|
||||
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param entity 实体类对象
|
||||
* 示例 cacheClient.set("merchant:"+id,merchant,1L,TimeUnit.DAYS)
|
||||
*/
|
||||
public <T> void set(String key, T entity, Long time, TimeUnit unit){
|
||||
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJSONString(entity),time,unit);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* 示例 cacheClient.get(key)
|
||||
* @return merchant
|
||||
*/
|
||||
public String get(String key) {
|
||||
return stringRedisTemplate.opsForValue().get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存
|
||||
* @param key [表名]:id
|
||||
* @param clazz Merchant.class
|
||||
* @param <T>
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T get(String key, Class<T> clazz) {
|
||||
String json = stringRedisTemplate.opsForValue().get(key);
|
||||
if(StrUtil.isNotBlank(json)){
|
||||
return JSONUtil.parseObject(json, clazz);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public <T> void hPut(String key, String field, T entity) {
|
||||
stringRedisTemplate.opsForHash().put(key,field,JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写redis缓存(哈希类型)
|
||||
* @param key [表名]:id
|
||||
* @param map 字段
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
*/
|
||||
public void hPutAll(String key, Map<String,String> map) {
|
||||
stringRedisTemplate.opsForHash().putAll(key,map);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取redis缓存(哈希类型)
|
||||
* 示例 cacheClient.get("merchant:"+id,Merchant.class)
|
||||
* @param key [表名]:id
|
||||
* @param field 字段
|
||||
* @return merchant
|
||||
*/
|
||||
public <T> T hGet(String key, String field, Class<T> clazz) {
|
||||
Object obj = stringRedisTemplate.opsForHash().get(key, field);
|
||||
return JSONUtil.parseObject(JSONUtil.toJSONString(obj),clazz);
|
||||
}
|
||||
|
||||
public List<Object> hValues(String key){
|
||||
return stringRedisTemplate.opsForHash().values(key);
|
||||
}
|
||||
|
||||
public Long hSize(String key){
|
||||
return stringRedisTemplate.opsForHash().size(key);
|
||||
}
|
||||
|
||||
// 逻辑过期方式写入redis
|
||||
public <T> void setWithLogicalExpire(String key, T value, Long time, TimeUnit unit){
|
||||
// 设置逻辑过期时间
|
||||
final RedisResult<T> redisResult = new RedisResult<>();
|
||||
redisResult.setData(value);
|
||||
redisResult.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
|
||||
stringRedisTemplate.opsForValue().set(key,JSONUtil.toJSONString(redisResult));
|
||||
}
|
||||
|
||||
// 读取redis
|
||||
public <R,ID> R query(String keyPrefix, ID id, Class<R> clazz, Function<ID,R> dbFallback, Long time, TimeUnit unit){
|
||||
String key = keyPrefix + id;
|
||||
// 1.从redis查询缓存
|
||||
final String json = stringRedisTemplate.opsForValue().get(key);
|
||||
// 2.判断是否存在
|
||||
if (StrUtil.isNotBlank(json)) {
|
||||
// 3.存在,直接返回
|
||||
return JSONUtil.parseObject(json,clazz);
|
||||
}
|
||||
// 判断命中的是否为空值
|
||||
if (json != null) {
|
||||
return null;
|
||||
}
|
||||
// 4. 不存在,跟进ID查询数据库
|
||||
R r = dbFallback.apply(id);
|
||||
// 5. 数据库不存在,返回错误
|
||||
if(r == null){
|
||||
// 空值写入数据库
|
||||
this.set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
|
||||
return null;
|
||||
}
|
||||
// 写入redis
|
||||
this.set(key,r,time,unit);
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加商户定位点
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoAdd("merchant-geo",merchant)
|
||||
*/
|
||||
public <T> void geoAdd(String key, Double x, Double y, String id){
|
||||
stringRedisTemplate.opsForGeo().add(key,new Point(x,y),id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除定位
|
||||
* @param key geo
|
||||
* @param id
|
||||
* 示例 cacheClient.geoRemove("merchant-geo",id)
|
||||
*/
|
||||
public void geoRemove(String key, Integer id){
|
||||
stringRedisTemplate.opsForGeo().remove(key,id.toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public <T> void sAdd(String key, T entity){
|
||||
stringRedisTemplate.opsForSet().add(key,JSONUtil.toJSONString(entity));
|
||||
}
|
||||
|
||||
public <T> Set<String> sMembers(String key){
|
||||
return stringRedisTemplate.opsForSet().members(key);
|
||||
}
|
||||
|
||||
// 更新排行榜
|
||||
public void zAdd(String key, Integer userId, Double value) {
|
||||
stringRedisTemplate.opsForZSet().add(key,userId.toString(),value);
|
||||
}
|
||||
// 增加元素的score值,并返回增加后的值
|
||||
public Double zIncrementScore(String key,Integer userId, Double delta){
|
||||
return stringRedisTemplate.opsForZSet().incrementScore(key, userId.toString(), delta);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> range(String key, Integer start, Integer end) {
|
||||
return stringRedisTemplate.opsForZSet().range(key, start, end);
|
||||
}
|
||||
// 获取排名榜
|
||||
public Set<String> reverseRange(String key, Integer start, Integer end){
|
||||
return stringRedisTemplate.opsForZSet().reverseRange(key, start, end);
|
||||
}
|
||||
// 获取分数
|
||||
public Double score(String key, Object value){
|
||||
return stringRedisTemplate.opsForZSet().score(key, value);
|
||||
}
|
||||
|
||||
public void delete(String key){
|
||||
stringRedisTemplate.delete(key);
|
||||
}
|
||||
|
||||
// 存储在list头部
|
||||
public void leftPush(String key, String keyword){
|
||||
stringRedisTemplate.opsForList().leftPush(key,keyword);
|
||||
}
|
||||
|
||||
// 获取列表指定范围内的元素
|
||||
public List<String> listRange(String key,Long start, Long end){
|
||||
return stringRedisTemplate.opsForList().range(key, start, end);
|
||||
}
|
||||
|
||||
// 获取列表长度
|
||||
public Long listSize(String key){
|
||||
return stringRedisTemplate.opsForList().size(key);
|
||||
}
|
||||
|
||||
// 裁剪list
|
||||
public void listTrim(String key){
|
||||
stringRedisTemplate.opsForList().trim(key, 0L, 100L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取后台系统设置信息
|
||||
* @param keyName 键名wx-word
|
||||
* @param tenantId 租户ID
|
||||
* @return
|
||||
* key示例 cache10048:setting:wx-work
|
||||
*/
|
||||
public JSONObject getSettingInfo(String keyName,Integer tenantId){
|
||||
String key = "cache" + tenantId + ":setting:" + keyName;
|
||||
final String cache = stringRedisTemplate.opsForValue().get(key);
|
||||
assert cache != null;
|
||||
return JSON.parseObject(cache);
|
||||
}
|
||||
|
||||
/**
|
||||
* KEY前缀
|
||||
* cache[tenantId]:[key+id]
|
||||
*/
|
||||
public static String prefix(String key){
|
||||
String prefix = "cache";
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
final Integer tenantId = ((User) object).getTenantId();
|
||||
prefix = prefix.concat(tenantId.toString()).concat(":");
|
||||
}
|
||||
}
|
||||
return prefix.concat(key);
|
||||
}
|
||||
|
||||
// 组装key
|
||||
public String key(String name,Integer id){
|
||||
return name.concat(":").concat(id.toString());
|
||||
}
|
||||
|
||||
// 获取上传配置
|
||||
public HashMap<String, String> getUploadConfig(Integer tenantId){
|
||||
String key = "setting:upload:" + tenantId;
|
||||
final String s = get(key);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(s);
|
||||
final String uploadMethod = jsonObject.getString("uploadMethod");
|
||||
final String bucketDomain = jsonObject.getString("bucketDomain");
|
||||
|
||||
final HashMap<String, String> map = new HashMap<>();
|
||||
map.put("uploadMethod",uploadMethod);
|
||||
map.put("bucketDomain",bucketDomain);
|
||||
return map;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.*;
|
||||
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Component
|
||||
public class RequestUtil {
|
||||
private static final String SERVER_HOST = "https://server.gxwebsoft.com/api";
|
||||
private static final String MODULES_HOST = "https://modules.gxwebsoft.com/api";
|
||||
private static String ACCESS_TOKEN;
|
||||
private static String TENANT_ID;
|
||||
|
||||
public void setTenantId(String tenantId) {
|
||||
TENANT_ID = tenantId;
|
||||
}
|
||||
|
||||
public void setAccessToken(String token) {
|
||||
ACCESS_TOKEN = token;
|
||||
}
|
||||
|
||||
|
||||
// 余额支付通知
|
||||
public void pushBalancePayNotify(Transaction transaction, Payment payment) {
|
||||
System.out.println("payment = " + payment);
|
||||
System.out.println("transaction = " + transaction);
|
||||
// 设置租户ID
|
||||
setTenantId(payment.getTenantId().toString());
|
||||
// 推送支付通知地址
|
||||
String path = payment.getNotifyUrl();
|
||||
try {
|
||||
// 链式构建请求
|
||||
HttpRequest.post(path)
|
||||
.header("Tenantid", TENANT_ID)
|
||||
.body(JSONUtil.toJSONString(transaction))//表单内容
|
||||
.timeout(20000)//超时,毫秒
|
||||
.execute().body();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
// 微信支付通知
|
||||
public void pushWxPayNotify(Transaction transaction, Payment payment) {
|
||||
// 设置租户ID
|
||||
setTenantId(payment.getTenantId().toString());
|
||||
// 推送支付通知地址
|
||||
String path = payment.getNotifyUrl();
|
||||
try {
|
||||
// 链式构建请求
|
||||
HttpRequest.post(path)
|
||||
.header("Tenantid", TENANT_ID)
|
||||
.body(JSONUtil.toJSONString(transaction))//表单内容
|
||||
.timeout(20000)//超时,毫秒
|
||||
.execute().body();
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public User getMerchantAccountByPhone(String phone) {
|
||||
String path = "/shop/merchant-account/getMerchantAccountByPhone/" + phone;
|
||||
try {
|
||||
// 链式构建请求
|
||||
String result = HttpRequest.get(MODULES_HOST.concat(path))
|
||||
.header("Authorization", ACCESS_TOKEN)
|
||||
.header("Tenantid", TENANT_ID)
|
||||
.timeout(20000)//超时,毫秒
|
||||
.execute().body();
|
||||
|
||||
JSONObject jsonObject = JSONObject.parseObject(result);
|
||||
final String data = jsonObject.getString("data");
|
||||
return JSONObject.parseObject(data, User.class);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public User getByUserId(Integer userId) {
|
||||
String path = "/system/user/" + userId;
|
||||
try {
|
||||
// 链式构建请求
|
||||
String result = HttpRequest.get(MODULES_HOST.concat(path))
|
||||
.header("Authorization", ACCESS_TOKEN)
|
||||
.header("Tenantid", TENANT_ID)
|
||||
.timeout(20000)//超时,毫秒
|
||||
.execute().body();
|
||||
|
||||
JSONObject jsonObject = JSONObject.parseObject(result);
|
||||
final String data = jsonObject.getString("data");
|
||||
return JSONObject.parseObject(data, User.class);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public User getUserByPhone(String phone) {
|
||||
String path = "/system/user/getByPhone/" + phone;
|
||||
try {
|
||||
// 链式构建请求
|
||||
String result = HttpRequest.get(SERVER_HOST.concat(path))
|
||||
.header("Authorization", ACCESS_TOKEN)
|
||||
.header("Tenantid", TENANT_ID)
|
||||
.timeout(20000)//超时,毫秒
|
||||
.execute().body();
|
||||
|
||||
JSONObject jsonObject = JSONObject.parseObject(result);
|
||||
final String data = jsonObject.getString("data");
|
||||
return JSONObject.parseObject(data, User.class);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// 新增用户
|
||||
public boolean saveUserByPhone(MerchantAccount merchantAccount) {
|
||||
String path = "/system/user/";
|
||||
try {
|
||||
HashMap<String, Object> map = new HashMap<>();
|
||||
map.put("nickname", merchantAccount.getRealName());
|
||||
map.put("username", merchantAccount.getPhone());
|
||||
map.put("realName", merchantAccount.getRealName());
|
||||
map.put("phone", merchantAccount.getPhone());
|
||||
map.put("password", merchantAccount.getPassword());
|
||||
final ArrayList<Object> roles = new ArrayList<>();
|
||||
final UserRole userRole = new UserRole();
|
||||
userRole.setUserId(merchantAccount.getUserId());
|
||||
userRole.setRoleId(merchantAccount.getRoleId());
|
||||
userRole.setTenantId(merchantAccount.getTenantId());
|
||||
roles.add(userRole);
|
||||
map.put("roles", roles);
|
||||
map.put("tenantId", TENANT_ID);
|
||||
// 链式构建请求
|
||||
String result = HttpRequest.post(SERVER_HOST.concat(path))
|
||||
.header("Authorization", ACCESS_TOKEN)
|
||||
.header("Tenantid", TENANT_ID)
|
||||
.body(JSONUtil.toJSONString(map))//表单内容
|
||||
.timeout(20000)//超时,毫秒
|
||||
.execute().body();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.crypto.SecureUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.system.entity.KVEntity;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 签名检查和获取签名
|
||||
* https://blog.csdn.net/u011628753/article/details/110251445
|
||||
* @author leng
|
||||
*
|
||||
*/
|
||||
public class SignCheckUtil {
|
||||
// 签名字段
|
||||
public final static String SIGN = "sign";
|
||||
|
||||
/**
|
||||
* 签名检查,签名参数中,sign是用于校验的加密值,其他参数按照字母顺序排序,加密,并将其内容链接起来
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static boolean signCheck(JSONObject params, String key) {
|
||||
if (null != params) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
map.put(k, v.toString());
|
||||
});
|
||||
return signCheck(map, key);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签名检查,签名参数中,sign是用于校验的加密值,其他参数按照字母顺序排序,加密,并将其内容链接起来
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* 签名key不允许为空
|
||||
* @return
|
||||
*/
|
||||
public static boolean signCheck(Map<String, String> params, String key) {
|
||||
String sign = params.get(SIGN);// 签名
|
||||
if (null == sign) {
|
||||
return false;
|
||||
}
|
||||
String signTemp = getSignString(params,key);
|
||||
if (null == signTemp) {
|
||||
return false;
|
||||
}
|
||||
return signTemp.equals(sign);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取签名的字符串
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getSignString(JSONObject params, String key) {
|
||||
if (null != params) {
|
||||
Map<String, String> map = new HashMap<>();
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
map.put(k, v.toString());
|
||||
});
|
||||
return getSignString(map, key);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取签名的字符串
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getSignString(Map<String, String> params, String key) {
|
||||
// 签名
|
||||
if (null == params || params.size() == 0) {
|
||||
return null;
|
||||
}
|
||||
key = (null == key) ? "" : key;
|
||||
List<KVEntity<String, String>> list = new ArrayList<>(params.size() - 1);
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
if (!SIGN.equals(k)) {
|
||||
list.add(KVEntity.build(k, v));
|
||||
}
|
||||
});
|
||||
|
||||
Collections.sort(list, (obj1, obj2) -> {
|
||||
return obj1.getK().compareTo(obj2.getK());
|
||||
});
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (KVEntity<String, String> kv : list) {
|
||||
String value = kv.getV();
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
sb.append(kv.getV()).append("-");
|
||||
}
|
||||
}
|
||||
sb.append(key);
|
||||
System.out.println("md5加密前的字符串 = " + sb + key);
|
||||
String signTemp = SecureUtil.md5(sb.toString()).toLowerCase();
|
||||
return signTemp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取微信签名的字符串
|
||||
*
|
||||
* 注意签名(sign)的生成方式,具体见官方文档(传参都要参与生成签名,且参数名按照字典序排序,最后接上APP_KEY,转化成大写)
|
||||
*
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getWXSignString(Map<String, String> params, String key) {
|
||||
// 签名
|
||||
if (null == params || params.size() == 0 || StringUtils.isEmpty(key)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<KVEntity<String, String>> list = new ArrayList<>(params.size() - 1);
|
||||
|
||||
params.forEach((k, v) -> {
|
||||
if (!SIGN.equals(k)) {
|
||||
list.add(KVEntity.build(k, v));
|
||||
}
|
||||
});
|
||||
|
||||
Collections.sort(list, (obj1, obj2) -> {
|
||||
return obj1.getK().compareTo(obj2.getK());
|
||||
});
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (KVEntity<String, String> kv : list) {
|
||||
String value = kv.getV();
|
||||
if (!StringUtils.isEmpty(value)) {
|
||||
sb.append(kv.getK() + "=" + value + "&");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("key=" + key);
|
||||
String signTemp = SecureUtil.md5(sb.toString()).toLowerCase();
|
||||
return signTemp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信签名验证
|
||||
* @param params
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static boolean WXsignCheck(Map<String, String> params, String key) {
|
||||
String sign = params.get(SIGN);
|
||||
if (StringUtils.isEmpty(sign)) {
|
||||
return false;
|
||||
}
|
||||
return sign.equals(getWXSignString(params, key));
|
||||
}
|
||||
|
||||
/**
|
||||
* 白名单校验
|
||||
* @param domainName abc.com
|
||||
* @return true
|
||||
*/
|
||||
public boolean checkWhiteDomains(List<String> whiteDomains, String domainName) {
|
||||
if(whiteDomains == null){
|
||||
return true;
|
||||
}
|
||||
if (whiteDomains.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
// 服务器域名白名单列表
|
||||
whiteDomains.add("server.gxwebsoft.com");
|
||||
for(String item: whiteDomains){
|
||||
// System.out.println(">>> domainName = " + domainName);
|
||||
if(Objects.equals(item, domainName)){
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import com.wechat.pay.java.core.Config;
|
||||
|
||||
|
||||
public class WxNativeUtil {
|
||||
|
||||
private static final Map<Integer, Config> tenantConfigs = new HashMap<>();
|
||||
|
||||
public static void addConfig(Integer tenantId, Config config) {
|
||||
tenantConfigs.put(tenantId, config);
|
||||
}
|
||||
|
||||
public static Config getConfig(Integer tenantId) {
|
||||
return tenantConfigs.get(tenantId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.system.service.SettingService;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
/**
|
||||
* 微信公众号工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class WxOfficialUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private Integer tenantId;
|
||||
public String appId;
|
||||
public String appSecret;
|
||||
public String openid;
|
||||
public String unionid;
|
||||
public String access_token;
|
||||
public String expires_in;
|
||||
public String nickname;
|
||||
|
||||
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
@Resource
|
||||
private ConfigProperties pathConfig;
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
public WxOfficialUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
// 实例化客户端
|
||||
public WxOfficialUtil client(Integer tenantId) {
|
||||
if(tenantId > 0){
|
||||
throw new BusinessException(tenantId + "123123");
|
||||
}
|
||||
this.tenantId = tenantId;
|
||||
this.config();
|
||||
System.out.println("this.tenantId = " + this.tenantId);
|
||||
return this;
|
||||
}
|
||||
|
||||
// 开发者ID和秘钥
|
||||
private void config() {
|
||||
String key = "cache"+ this.tenantId +":setting:wx-official";
|
||||
String wxOfficial = stringRedisTemplate.opsForValue().get(key);
|
||||
JSONObject data = JSONObject.parseObject(wxOfficial);
|
||||
if(data != null){
|
||||
this.appId = data.getString("appId");
|
||||
this.appSecret = data.getString("appSecret");
|
||||
}
|
||||
System.out.println("this.appId = " + this.appId);
|
||||
System.out.println("this.appSecret = " + this.appSecret);
|
||||
}
|
||||
|
||||
// 获取appId
|
||||
public String getAppSecret(){
|
||||
return this.appSecret;
|
||||
}
|
||||
|
||||
public String getCodeUrl() throws UnsupportedEncodingException {
|
||||
String encodedReturnUrl = URLEncoder.encode("https://server.gxwebsoft.com/api/open/wx-official/accessToken","UTF-8");
|
||||
return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ this.appId +"&redirect_uri=" + encodedReturnUrl + "&response_type=code&scope=snsapi_userinfo&state="+ this.tenantId +"#wechat_redirect";
|
||||
}
|
||||
|
||||
// 获取access_token
|
||||
public String getAccessToken(String code) {
|
||||
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ this.appId +"&secret="+ this.appSecret +"&code="+ code +"&grant_type=authorization_code";
|
||||
System.out.println("url = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
access_token = jsonObject.getString("access_token");
|
||||
if(access_token == null){
|
||||
throw new BusinessException("获取access_token失败");
|
||||
}
|
||||
this.openid = jsonObject.getString("openid");
|
||||
this.unionid = jsonObject.getString("unionid");
|
||||
this.expires_in = jsonObject.getString("expires_in");
|
||||
return access_token;
|
||||
}
|
||||
|
||||
// 获取userinfo
|
||||
public JSONObject getUserInfo(String access_token) {
|
||||
String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+ access_token +"&openid="+ this.openid +"&lang=zh_CN";
|
||||
System.out.println("url2 = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
if(response == null){
|
||||
throw new BusinessException("获取userinfo失败");
|
||||
}
|
||||
return JSONObject.parseObject(response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 微信小程序工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class WxUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private Integer tenantId;
|
||||
public String appId;
|
||||
public String appSecret;
|
||||
public String access_token;
|
||||
public String expires_in;
|
||||
public String nickname;
|
||||
public String userid;
|
||||
public String user_ticket;
|
||||
public String openid;
|
||||
public String external_userid;
|
||||
public String name;
|
||||
public String position;
|
||||
public String mobile;
|
||||
public String gender;
|
||||
public String email;
|
||||
public String avatar;
|
||||
public String thumb_avatar;
|
||||
public String telephone;
|
||||
public String address;
|
||||
public String alias;
|
||||
public String qr_code;
|
||||
public String open_userid;
|
||||
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
|
||||
public WxUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
|
||||
// 实例化客户端
|
||||
public WxUtil client(Integer tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
this.config();
|
||||
return this;
|
||||
}
|
||||
|
||||
// 开发者ID和秘钥
|
||||
private void config() {
|
||||
JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", this.tenantId);
|
||||
if(settingInfo == null){
|
||||
throw new BusinessException("微信小程序未配置");
|
||||
}
|
||||
this.appId = settingInfo.getString("corpId");
|
||||
this.appSecret = settingInfo.getString("secret");
|
||||
System.out.println("this.appId = " + this.appId);
|
||||
System.out.println("this.appSecret = " + this.appSecret);
|
||||
}
|
||||
|
||||
// 获取access_token
|
||||
public void getAccessToken(String code) {
|
||||
String key = "cache"+ this.tenantId +":ww:access_token";
|
||||
final String access_token = stringRedisTemplate.opsForValue().get(key);
|
||||
if(access_token != null){
|
||||
this.getUserInfo(code,access_token);
|
||||
}else {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +this.appId+ "&corpsecret="+ this.appSecret;
|
||||
System.out.println("url = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
// 获取成功
|
||||
if(jsonObject.getString("access_token") != null){
|
||||
this.access_token = jsonObject.getString("access_token");
|
||||
this.expires_in = jsonObject.getString("expires_in");
|
||||
stringRedisTemplate.opsForValue().set(key,this.access_token,7000, TimeUnit.SECONDS);
|
||||
System.out.println("获取access_token成功 = " + this.access_token);
|
||||
this.getUserInfo(code,this.access_token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取userinfo
|
||||
public void getUserInfo(String code, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" +access_token+ "&code=" + code;
|
||||
System.out.println("url2 = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
final String errcode = jsonObject.getString("errcode");
|
||||
final String errmsg = jsonObject.getString("errmsg");
|
||||
if(!StrUtil.equals(errcode,"0")){
|
||||
throw new BusinessException(errmsg);
|
||||
}
|
||||
this.userid = jsonObject.getString("userid");
|
||||
this.user_ticket = jsonObject.getString("user_ticket");
|
||||
this.openid = jsonObject.getString("openid");
|
||||
this.external_userid = jsonObject.getString("external_userid");
|
||||
System.out.println("获取用户信息成功 = " + jsonObject);
|
||||
}
|
||||
|
||||
public void getUserProfile(String userid, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+ access_token +"&userid=" + userid;
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response3 = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
System.out.println("读取用户详细信息 = " + jsonObject);
|
||||
|
||||
this.name = jsonObject.getString("name");
|
||||
this.position = jsonObject.getString("position");
|
||||
this.gender = jsonObject.getString("gender");
|
||||
this.email = jsonObject.getString("email");
|
||||
this.avatar = jsonObject.getString("avatar");
|
||||
this.thumb_avatar = jsonObject.getString("thumb_avatar");
|
||||
this.telephone = jsonObject.getString("telephone");
|
||||
this.address = jsonObject.getString("address");
|
||||
this.alias = jsonObject.getString("alias");
|
||||
this.qr_code = jsonObject.getString("qr_code");
|
||||
this.open_userid = jsonObject.getString("open_userid");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 企业微信工具类
|
||||
* @author 科技小王子
|
||||
*
|
||||
*/
|
||||
@Component
|
||||
public class WxWorkUtil {
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private Integer tenantId;
|
||||
public String appId;
|
||||
public String appSecret;
|
||||
public String access_token;
|
||||
public String expires_in;
|
||||
public String nickname;
|
||||
public String userid;
|
||||
public String user_ticket;
|
||||
public String openid;
|
||||
public String external_userid;
|
||||
public String name;
|
||||
public String position;
|
||||
public String mobile;
|
||||
public String gender;
|
||||
public String email;
|
||||
public String avatar;
|
||||
public String thumb_avatar;
|
||||
public String telephone;
|
||||
public String address;
|
||||
public String alias;
|
||||
public String qr_code;
|
||||
public String open_userid;
|
||||
|
||||
@Resource
|
||||
private CacheClient cacheClient;
|
||||
|
||||
|
||||
public WxWorkUtil(StringRedisTemplate stringRedisTemplate){
|
||||
this.stringRedisTemplate = stringRedisTemplate;
|
||||
}
|
||||
|
||||
|
||||
// 实例化客户端
|
||||
public WxWorkUtil client(Integer tenantId) {
|
||||
this.tenantId = tenantId;
|
||||
this.config();
|
||||
return this;
|
||||
}
|
||||
|
||||
// 开发者ID和秘钥
|
||||
private void config() {
|
||||
JSONObject settingInfo = cacheClient.getSettingInfo("wx-work", this.tenantId);
|
||||
if(settingInfo == null){
|
||||
throw new BusinessException("企业微信未配置");
|
||||
}
|
||||
this.appId = settingInfo.getString("corpId");
|
||||
this.appSecret = settingInfo.getString("secret");
|
||||
System.out.println("this.appId = " + this.appId);
|
||||
System.out.println("this.appSecret = " + this.appSecret);
|
||||
}
|
||||
|
||||
// 获取access_token
|
||||
public void getAccessToken(String code) {
|
||||
String key = "cache"+ this.tenantId +":ww:access_token";
|
||||
final String access_token = stringRedisTemplate.opsForValue().get(key);
|
||||
if(access_token != null){
|
||||
this.getUserInfo(code,access_token);
|
||||
}else {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" +this.appId+ "&corpsecret="+ this.appSecret;
|
||||
System.out.println("url = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
final JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
// 获取成功
|
||||
if(jsonObject.getString("access_token") != null){
|
||||
this.access_token = jsonObject.getString("access_token");
|
||||
this.expires_in = jsonObject.getString("expires_in");
|
||||
stringRedisTemplate.opsForValue().set(key,this.access_token,7000, TimeUnit.SECONDS);
|
||||
System.out.println("获取access_token成功 = " + this.access_token);
|
||||
this.getUserInfo(code,this.access_token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取userinfo
|
||||
public void getUserInfo(String code, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=" +access_token+ "&code=" + code;
|
||||
System.out.println("url2 = " + url);
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
final String errcode = jsonObject.getString("errcode");
|
||||
final String errmsg = jsonObject.getString("errmsg");
|
||||
if(!StrUtil.equals(errcode,"0")){
|
||||
throw new BusinessException(errmsg);
|
||||
}
|
||||
this.userid = jsonObject.getString("userid");
|
||||
this.user_ticket = jsonObject.getString("user_ticket");
|
||||
this.openid = jsonObject.getString("openid");
|
||||
this.external_userid = jsonObject.getString("external_userid");
|
||||
System.out.println("获取用户信息成功 = " + jsonObject);
|
||||
}
|
||||
|
||||
public void getUserProfile(String userid, String access_token) {
|
||||
String url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token="+ access_token +"&userid=" + userid;
|
||||
String response = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
|
||||
System.out.println("response3 = " + response);
|
||||
JSONObject jsonObject = JSONObject.parseObject(response);
|
||||
System.out.println("读取用户详细信息 = " + jsonObject);
|
||||
|
||||
this.name = jsonObject.getString("name");
|
||||
this.position = jsonObject.getString("position");
|
||||
this.gender = jsonObject.getString("gender");
|
||||
this.email = jsonObject.getString("email");
|
||||
this.avatar = jsonObject.getString("avatar");
|
||||
this.thumb_avatar = jsonObject.getString("thumb_avatar");
|
||||
this.telephone = jsonObject.getString("telephone");
|
||||
this.address = jsonObject.getString("address");
|
||||
this.alias = jsonObject.getString("alias");
|
||||
this.qr_code = jsonObject.getString("qr_code");
|
||||
this.open_userid = jsonObject.getString("open_userid");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 返回结果
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:50
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class ApiResult<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "状态码")
|
||||
private Integer code;
|
||||
|
||||
@ApiModelProperty(value = "状态信息")
|
||||
private String message;
|
||||
|
||||
@ApiModelProperty(value = "返回数据")
|
||||
private T data;
|
||||
|
||||
@ApiModelProperty(value = "错误信息")
|
||||
private String error;
|
||||
|
||||
public ApiResult() {}
|
||||
|
||||
public ApiResult(Integer code) {
|
||||
this(code, null);
|
||||
}
|
||||
|
||||
public ApiResult(Integer code, String message) {
|
||||
this(code, message, null);
|
||||
}
|
||||
|
||||
public ApiResult(Integer code, String message, T data) {
|
||||
this(code, message, data, null);
|
||||
}
|
||||
|
||||
public ApiResult(Integer code, String message, T data, String error) {
|
||||
setCode(code);
|
||||
setMessage(message);
|
||||
setData(data);
|
||||
setError(error);
|
||||
}
|
||||
|
||||
public Integer getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public ApiResult<T> setCode(Integer code) {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public ApiResult<T> setMessage(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
public ApiResult<T> setData(T data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return this.error;
|
||||
}
|
||||
|
||||
public ApiResult<T> setError(String error) {
|
||||
this.error = error;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.system.entity.Company;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.CompanyService;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.bind.WebDataBinder;
|
||||
import org.springframework.web.bind.annotation.InitBinder;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Controller基类
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:19
|
||||
*/
|
||||
public class BaseController {
|
||||
@Resource
|
||||
private HttpServletRequest request;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private CompanyService companyService;
|
||||
@Resource
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
/**
|
||||
* 获取当前登录的user
|
||||
*
|
||||
* @return User
|
||||
*/
|
||||
public User getLoginUser() {
|
||||
try {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication != null) {
|
||||
Object object = authentication.getPrincipal();
|
||||
if (object instanceof User) {
|
||||
((User) object).setUid(13448);
|
||||
System.out.println("object = " + object);
|
||||
return (User) object;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录的userId
|
||||
*
|
||||
* @return userId
|
||||
*/
|
||||
public Integer getLoginUserId() {
|
||||
User loginUser = getLoginUser();
|
||||
return loginUser == null ? null : loginUser.getUserId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录的tenantId
|
||||
*
|
||||
* @return tenantId
|
||||
*/
|
||||
public Integer getTenantId() {
|
||||
// 1 从登录用户拿tenantId
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
return loginUser.getTenantId();
|
||||
}
|
||||
// 2 从域名拿ID
|
||||
String Domain = request.getHeader("Domain");
|
||||
if (StrUtil.isNotBlank(Domain)) {
|
||||
String key = "Domain:" + Domain;
|
||||
String tenantId = redisUtil.get(key);
|
||||
if(tenantId != null){
|
||||
// System.out.println("从域名拿ID = " + tenantId);
|
||||
return Integer.valueOf(tenantId);
|
||||
}
|
||||
}
|
||||
// 3 从请求头拿ID
|
||||
String tenantId = request.getHeader("tenantId");
|
||||
if(StrUtil.isNotBlank(tenantId)){
|
||||
return Integer.valueOf(tenantId);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登录的企业信息
|
||||
*
|
||||
* @return Company
|
||||
*/
|
||||
public Company getCompany() {
|
||||
List<Company> list = companyService.list(new LambdaQueryWrapper<Company>().eq(Company::getAuthoritative, 1));
|
||||
if (!CollectionUtils.isEmpty(list)) {
|
||||
final Company company = list.get(0);
|
||||
return company;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Integer getCompanyId() {
|
||||
Company company = getCompany();
|
||||
return company.getCompanyId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> success() {
|
||||
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> success(String message) {
|
||||
return success().setMessage(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @param data 返回数据
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> success(T data) {
|
||||
return new ApiResult<>(Constants.RESULT_OK_CODE, Constants.RESULT_OK_MSG, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回成功
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> success(String message, T data) {
|
||||
return success(data).setMessage(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回分页查询数据
|
||||
*
|
||||
* @param list 当前页数据
|
||||
* @param count 总数量
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<PageResult<T>> success(List<T> list, Long count) {
|
||||
return success(new PageResult<>(list, count));
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回分页查询数据
|
||||
*
|
||||
* @param iPage IPage
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<PageResult<T>> success(IPage<T> iPage) {
|
||||
return success(iPage.getRecords(), iPage.getTotal());
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> fail() {
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, Constants.RESULT_ERROR_MSG);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @return ApiResult
|
||||
*/
|
||||
public ApiResult<?> fail(String message) {
|
||||
return fail().setMessage(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @param data 返回数据
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> fail(T data) {
|
||||
return fail(Constants.RESULT_ERROR_MSG, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回失败
|
||||
*
|
||||
* @param message 状态信息
|
||||
* @param data 返回数据
|
||||
* @return ApiResult
|
||||
*/
|
||||
public <T> ApiResult<T> fail(String message, T data) {
|
||||
return new ApiResult<>(Constants.RESULT_ERROR_CODE, message, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 请求参数的空字符串转为null
|
||||
*/
|
||||
@InitBinder
|
||||
public void initBinder(WebDataBinder binder) {
|
||||
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
|
||||
}
|
||||
|
||||
// 自定义函数
|
||||
public String getAuthorization() {
|
||||
return request.getHeader("Authorization");
|
||||
}
|
||||
|
||||
public String getSign() {
|
||||
return request.getParameter("sign");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 根据账号|手机号码|邮箱查找用户ID
|
||||
*
|
||||
* @return userId
|
||||
*/
|
||||
public Integer getUserIdByUsername(String username, Integer tenantId) {
|
||||
// 按账号搜素
|
||||
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username).eq(User::getTenantId, tenantId));
|
||||
if (user != null && user.getUserId() > 0) {
|
||||
return user.getUserId();
|
||||
}
|
||||
// 按手机号码搜索
|
||||
User userByPhone = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getPhone, username).eq(User::getTenantId, tenantId));
|
||||
if (userByPhone != null && userByPhone.getUserId() > 0) {
|
||||
return userByPhone.getUserId();
|
||||
}
|
||||
// 按邮箱搜索
|
||||
User userByEmail = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, username).eq(User::getTenantId, tenantId));
|
||||
if (userByEmail != null && userByEmail.getUserId() > 0) {
|
||||
return userByEmail.getUserId();
|
||||
}
|
||||
throw new BusinessException("找不到该用户");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 查询参数基本字段
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-08-26 22:14:43
|
||||
*/
|
||||
@Data
|
||||
public class BaseParam implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("分页查询页码")
|
||||
private Long page;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("分页查询每页数量")
|
||||
private Long limit;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty(value = "排序字段", notes = "排序字段或sql, 如果是sql则order字段无用, 如: `id asc, name desc`")
|
||||
private String sort;
|
||||
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty(value = "排序方式", notes = "sort是字段名称时对应的排序方式, asc升序, desc降序")
|
||||
private String order;
|
||||
|
||||
@QueryField(value = "create_time", type = QueryType.GE)
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("创建时间起始值")
|
||||
private String createTimeStart;
|
||||
|
||||
@QueryField(value = "create_time", type = QueryType.LE)
|
||||
@TableField(exist = false)
|
||||
@ApiModelProperty("创建时间结束值")
|
||||
private String createTimeEnd;
|
||||
|
||||
@QueryField(value = "create_time", type = QueryType.GE)
|
||||
@ApiModelProperty("搜索场景")
|
||||
@TableField(exist = false)
|
||||
private String sceneType;
|
||||
|
||||
@ApiModelProperty(value = "商户ID")
|
||||
@TableField(exist = false)
|
||||
private Integer merchantId;
|
||||
|
||||
@ApiModelProperty("租户ID")
|
||||
@TableField(exist = false)
|
||||
private Integer tenantId;
|
||||
|
||||
@ApiModelProperty("模糊搜素")
|
||||
@TableField(exist = false)
|
||||
private String keywords;
|
||||
|
||||
/**
|
||||
* 获取集合中的第一条数据
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 第一条数据
|
||||
*/
|
||||
public <T> T getOne(List<T> records) {
|
||||
return CommonUtil.listGetOne(records);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 批量修改通用参数
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2020-03-13 00:11:06
|
||||
*/
|
||||
@Data
|
||||
public class BatchParam<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "需要修改的数据id集合")
|
||||
private List<Serializable> ids;
|
||||
|
||||
@ApiModelProperty(value = "需要修改的字段和值")
|
||||
private T data;
|
||||
|
||||
/**
|
||||
* 通用批量修改方法
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField id字段名称
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean update(IService<T> service, String idField) {
|
||||
if (this.data == null) {
|
||||
return false;
|
||||
}
|
||||
return service.update(this.data, new UpdateWrapper<T>().in(idField, this.ids));
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用批量修改方法
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField id字段名称
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean update(IService<T> service, SFunction<T, ?> idField) {
|
||||
if (this.data == null) {
|
||||
return false;
|
||||
}
|
||||
return service.update(this.data, new LambdaUpdateWrapper<T>().in(idField, this.ids));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 检查是否存在通用参数
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-07 22:24:39
|
||||
*/
|
||||
@Data
|
||||
public class ExistenceParam<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "检查的字段")
|
||||
private String field;
|
||||
|
||||
@ApiModelProperty(value = "字段的值")
|
||||
private String value;
|
||||
|
||||
@ApiModelProperty(value = "修改时的主键")
|
||||
private Integer id;
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, String idField) {
|
||||
return isExistence(service, idField, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @param isToUnderlineCase 是否需要把field转为下划线格式
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, String idField, boolean isToUnderlineCase) {
|
||||
if (StrUtil.hasBlank(this.field, this.value)) {
|
||||
return false;
|
||||
}
|
||||
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
|
||||
QueryWrapper<T> wrapper = new QueryWrapper<>();
|
||||
wrapper.eq(fieldName, value);
|
||||
if (id != null) {
|
||||
wrapper.ne(idField, id);
|
||||
}
|
||||
return service.count(wrapper) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, SFunction<T, ?> idField) {
|
||||
return isExistence(service, idField, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否存在
|
||||
*
|
||||
* @param service IService
|
||||
* @param idField 修改时的主键字段
|
||||
* @param isToUnderlineCase 是否需要把field转为下划线格式
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isExistence(IService<T> service, SFunction<T, ?> idField, boolean isToUnderlineCase) {
|
||||
if (StrUtil.hasBlank(this.field, this.value)) {
|
||||
return false;
|
||||
}
|
||||
String fieldName = isToUnderlineCase ? StrUtil.toUnderlineCase(field) : field;
|
||||
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.apply(fieldName + " = {0}", value);
|
||||
if (id != null) {
|
||||
wrapper.ne(idField, id);
|
||||
}
|
||||
return service.count(wrapper) > 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.gxwebsoft.common.core.Constants;
|
||||
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||
import com.gxwebsoft.common.core.utils.CommonUtil;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 分页、排序、搜索参数封装
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2019-04-26 10:34:35
|
||||
*/
|
||||
public class PageParam<T, U extends BaseParam> extends Page<T> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 租户id字段名称
|
||||
*/
|
||||
private static final String TENANT_ID_FIELD = "tenantId";
|
||||
|
||||
/**
|
||||
* 查询条件
|
||||
*/
|
||||
private final U where;
|
||||
|
||||
/**
|
||||
* 是否把字段名称驼峰转下划线
|
||||
*/
|
||||
private final boolean isToUnderlineCase;
|
||||
|
||||
public PageParam() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public PageParam(U where) {
|
||||
this(where, true);
|
||||
}
|
||||
|
||||
public PageParam(U where, boolean isToUnderlineCase) {
|
||||
super();
|
||||
this.where = where;
|
||||
this.isToUnderlineCase = isToUnderlineCase;
|
||||
if (where != null) {
|
||||
// 获取分页页码
|
||||
if (where.getPage() != null) {
|
||||
setCurrent(where.getPage());
|
||||
}
|
||||
// 获取分页每页数量
|
||||
if (where.getLimit() != null) {
|
||||
setSize(where.getLimit());
|
||||
}
|
||||
// 获取排序方式
|
||||
if (where.getSort() != null) {
|
||||
if (sortIsSQL(where.getSort())) {
|
||||
setOrders(parseOrderSQL(where.getSort()));
|
||||
} else {
|
||||
List<OrderItem> orderItems = new ArrayList<>();
|
||||
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(where.getSort()) : where.getSort();
|
||||
boolean asc = !Constants.ORDER_DESC_VALUE.equals(where.getOrder());
|
||||
orderItems.add(new OrderItem(column, asc));
|
||||
setOrders(orderItems);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 排序字段是否是sql
|
||||
*/
|
||||
private boolean sortIsSQL(String sort) {
|
||||
return sort != null && (sort.contains(",") || sort.trim().contains(" "));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析排序sql
|
||||
*/
|
||||
private List<OrderItem> parseOrderSQL(String orderSQL) {
|
||||
List<OrderItem> orders = new ArrayList<>();
|
||||
if (StrUtil.isNotBlank(orderSQL)) {
|
||||
for (String item : orderSQL.split(",")) {
|
||||
String[] temp = item.trim().split(" ");
|
||||
if (!temp[0].isEmpty()) {
|
||||
String column = this.isToUnderlineCase ? StrUtil.toUnderlineCase(temp[0]) : temp[0];
|
||||
boolean asc = temp.length == 1 || !temp[temp.length - 1].equals(Constants.ORDER_DESC_VALUE);
|
||||
orders.add(new OrderItem(column, asc));
|
||||
}
|
||||
}
|
||||
}
|
||||
return orders;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置默认排序方式
|
||||
*
|
||||
* @param orderItems 排序方式
|
||||
* @return PageParam
|
||||
*/
|
||||
public PageParam<T, U> setDefaultOrder(List<OrderItem> orderItems) {
|
||||
if (orders() == null || orders().size() == 0) {
|
||||
setOrders(orderItems);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置默认排序方式
|
||||
*
|
||||
* @param orderSQL 排序方式
|
||||
* @return PageParam
|
||||
*/
|
||||
public PageParam<T, U> setDefaultOrder(String orderSQL) {
|
||||
setDefaultOrder(parseOrderSQL(orderSQL));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取查询条件
|
||||
*
|
||||
* @param excludes 不包含的字段
|
||||
* @return QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getWrapper(String... excludes) {
|
||||
return buildWrapper(null, Arrays.asList(excludes));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取查询条件
|
||||
*
|
||||
* @param columns 只包含的字段
|
||||
* @return QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getWrapperWith(String... columns) {
|
||||
return buildWrapper(Arrays.asList(columns), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建QueryWrapper
|
||||
*
|
||||
* @param columns 包含的字段
|
||||
* @param excludes 排除的字段
|
||||
* @return QueryWrapper
|
||||
*/
|
||||
private QueryWrapper<T> buildWrapper(List<String> columns, List<String> excludes) {
|
||||
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
|
||||
Map<String, Object> map = BeanUtil.beanToMap(where, false, true);
|
||||
for (String fieldName : map.keySet()) {
|
||||
Object fieldValue = map.get(fieldName);
|
||||
Field field = ReflectUtil.getField(where.getClass(), fieldName);
|
||||
|
||||
// 过滤不包含的字段
|
||||
if (columns != null && !columns.contains(fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤排除的字段
|
||||
if (excludes != null && excludes.contains(fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤逻辑删除字段
|
||||
if (field.getAnnotation(TableLogic.class) != null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤租户id字段
|
||||
if (fieldName.equals(TENANT_ID_FIELD)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 获取注解指定的查询字段及查询方式
|
||||
QueryType queryType = QueryType.LIKE;
|
||||
QueryField queryField = field.getAnnotation(QueryField.class);
|
||||
if (queryField != null) {
|
||||
if (StrUtil.isNotEmpty(queryField.value())) {
|
||||
fieldName = queryField.value();
|
||||
}
|
||||
if (queryField.type() != null) {
|
||||
queryType = queryField.type();
|
||||
}
|
||||
} else {
|
||||
// 过滤非本表的字段
|
||||
TableField tableField = field.getAnnotation(TableField.class);
|
||||
if (tableField != null && !tableField.exist()) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 字段名驼峰转下划线
|
||||
if (this.isToUnderlineCase) {
|
||||
fieldName = StrUtil.toUnderlineCase(fieldName);
|
||||
}
|
||||
|
||||
//
|
||||
switch (queryType) {
|
||||
case EQ:
|
||||
queryWrapper.eq(fieldName, fieldValue);
|
||||
break;
|
||||
case NE:
|
||||
queryWrapper.ne(fieldName, fieldValue);
|
||||
break;
|
||||
case GT:
|
||||
queryWrapper.gt(fieldName, fieldValue);
|
||||
break;
|
||||
case GE:
|
||||
queryWrapper.ge(fieldName, fieldValue);
|
||||
break;
|
||||
case LT:
|
||||
queryWrapper.lt(fieldName, fieldValue);
|
||||
break;
|
||||
case LE:
|
||||
queryWrapper.le(fieldName, fieldValue);
|
||||
break;
|
||||
case LIKE:
|
||||
queryWrapper.like(fieldName, fieldValue);
|
||||
break;
|
||||
case NOT_LIKE:
|
||||
queryWrapper.notLike(fieldName, fieldValue);
|
||||
break;
|
||||
case LIKE_LEFT:
|
||||
queryWrapper.likeLeft(fieldName, fieldValue);
|
||||
break;
|
||||
case LIKE_RIGHT:
|
||||
queryWrapper.likeRight(fieldName, fieldValue);
|
||||
break;
|
||||
case IS_NULL:
|
||||
queryWrapper.isNull(fieldName);
|
||||
break;
|
||||
case IS_NOT_NULL:
|
||||
queryWrapper.isNotNull(fieldName);
|
||||
break;
|
||||
case IN:
|
||||
queryWrapper.in(fieldName, fieldValue);
|
||||
break;
|
||||
case NOT_IN:
|
||||
queryWrapper.notIn(fieldName, fieldValue);
|
||||
break;
|
||||
case IN_STR:
|
||||
if (fieldValue instanceof String) {
|
||||
queryWrapper.in(fieldName, Arrays.asList(((String) fieldValue).split(",")));
|
||||
}
|
||||
break;
|
||||
case NOT_IN_STR:
|
||||
if (fieldValue instanceof String) {
|
||||
queryWrapper.notIn(fieldName, Arrays.asList(((String) fieldValue).split(",")));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取包含排序的查询条件
|
||||
*
|
||||
* @return 包含排序的QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getOrderWrapper() {
|
||||
return getOrderWrapper(getWrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取包含排序的查询条件
|
||||
*
|
||||
* @param queryWrapper 不含排序的QueryWrapper
|
||||
* @return 包含排序的QueryWrapper
|
||||
*/
|
||||
public QueryWrapper<T> getOrderWrapper(QueryWrapper<T> queryWrapper) {
|
||||
if (queryWrapper == null) {
|
||||
queryWrapper = new QueryWrapper<>();
|
||||
}
|
||||
for (OrderItem orderItem : orders()) {
|
||||
if (orderItem.isAsc()) {
|
||||
queryWrapper.orderByAsc(orderItem.getColumn());
|
||||
} else {
|
||||
queryWrapper.orderByDesc(orderItem.getColumn());
|
||||
}
|
||||
}
|
||||
return queryWrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取集合中的第一条数据
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 第一条数据
|
||||
*/
|
||||
public T getOne(List<T> records) {
|
||||
return CommonUtil.listGetOne(records);
|
||||
}
|
||||
|
||||
/**
|
||||
* 代码排序集合
|
||||
*
|
||||
* @param records 集合
|
||||
* @return 排序后的集合
|
||||
*/
|
||||
public List<T> sortRecords(List<T> records) {
|
||||
List<OrderItem> orderItems = orders();
|
||||
if (records == null || records.size() < 2 || orderItems == null || orderItems.size() == 0) {
|
||||
return records;
|
||||
}
|
||||
Comparator<T> comparator = null;
|
||||
for (OrderItem item : orderItems) {
|
||||
if (item.getColumn() == null) {
|
||||
continue;
|
||||
}
|
||||
String field = this.isToUnderlineCase ? StrUtil.toCamelCase(item.getColumn()) : item.getColumn();
|
||||
Function keyExtractor = t -> ReflectUtil.getFieldValue(t, field);
|
||||
if (comparator == null) {
|
||||
if (item.isAsc()) {
|
||||
comparator = Comparator.comparing(keyExtractor);
|
||||
} else {
|
||||
comparator = Comparator.comparing(keyExtractor, Comparator.reverseOrder());
|
||||
}
|
||||
} else {
|
||||
if (item.isAsc()) {
|
||||
comparator.thenComparing(keyExtractor);
|
||||
} else {
|
||||
comparator.thenComparing(keyExtractor, Comparator.reverseOrder());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (comparator != null) {
|
||||
return records.stream().sorted(comparator).collect(Collectors.toList());
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.gxwebsoft.common.core.web;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 分页查询返回结果
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2017-06-10 10:10:02
|
||||
*/
|
||||
public class PageResult<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@ApiModelProperty(value = "当前页数据")
|
||||
private List<T> list;
|
||||
|
||||
@ApiModelProperty(value = "总数量")
|
||||
private Long count;
|
||||
|
||||
public PageResult() {
|
||||
}
|
||||
|
||||
public PageResult(List<T> list) {
|
||||
this(list, null);
|
||||
}
|
||||
|
||||
public PageResult(List<T> list, Long count) {
|
||||
setList(list);
|
||||
setCount(count);
|
||||
}
|
||||
|
||||
public List<T> getList() {
|
||||
return this.list;
|
||||
}
|
||||
|
||||
public void setList(List<T> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Long getCount() {
|
||||
return this.count;
|
||||
}
|
||||
|
||||
public void setCount(Long count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user