拆分think模块包

This commit is contained in:
2024-08-13 17:51:18 +08:00
parent 9dc17cd63e
commit 09a752e12a
1547 changed files with 88305 additions and 10329 deletions
@@ -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;
}
}
+263
View File
@@ -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());
}
}
+235
View File
@@ -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();
}
}
}
+32
View File
@@ -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;
}
}
+311
View File
@@ -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);
}
}
}
+62
View File
@@ -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
+69
View File
@@ -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;
}
}
+96
View File
@@ -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;
}
}
+281
View File
@@ -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;
}
}
+155
View File
@@ -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);
}
}
+134
View File
@@ -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");
}
}
+134
View File
@@ -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");
}
}