15 changed files with 887 additions and 7 deletions
@ -0,0 +1,97 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import com.google.common.collect.Maps; |
|||
import io.jsonwebtoken.Jwts; |
|||
import io.jsonwebtoken.SignatureAlgorithm; |
|||
|
|||
import java.security.Key; |
|||
import java.security.KeyFactory; |
|||
import java.security.NoSuchAlgorithmException; |
|||
import java.security.interfaces.RSAPrivateKey; |
|||
import java.security.interfaces.RSAPublicKey; |
|||
import java.security.spec.InvalidKeySpecException; |
|||
import java.security.spec.PKCS8EncodedKeySpec; |
|||
import java.security.spec.X509EncodedKeySpec; |
|||
import java.util.Date; |
|||
import java.util.Map; |
|||
|
|||
/** |
|||
* 描述: |
|||
* |
|||
* @outhor dong.jun |
|||
* @create 2022-06-13 16:23 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
public class ApiTokenUtils { |
|||
/** |
|||
* cloudhub_token生成测试 |
|||
* |
|||
* @param args |
|||
* @throws Exception |
|||
*/ |
|||
public static void main(String[] args) throws Exception { |
|||
String issuer = "test"; |
|||
Map<String, String> stringStringMap = Maps.newHashMap(); |
|||
String cloudhub_token = getToken( |
|||
issuer, //从天朗获取
|
|||
stringStringMap.get("private_key"), //从天朗获取
|
|||
5 * 60 * 1000L |
|||
); |
|||
System.out.printf( |
|||
"issuer: %s\n" + |
|||
"pri_key: %s\n" + |
|||
"cloudhub_token: %s\n" + |
|||
"check: %b\n", |
|||
issuer, |
|||
stringStringMap.get("private_key"), |
|||
cloudhub_token, |
|||
Jwts.parser().setSigningKey(stringToPublickKey(stringStringMap.get("public_key"))).parseClaimsJws(cloudhub_token) != null |
|||
); |
|||
} |
|||
|
|||
/** |
|||
* @param iss 从天朗获取 |
|||
* @param pri 从天朗获取 |
|||
* @param exp token有效期 |
|||
* @return |
|||
* @throws Exception |
|||
*/ |
|||
public static String getToken(String iss, String pri, Long exp) throws Exception { |
|||
Date date = new Date(System.currentTimeMillis()); |
|||
return Jwts |
|||
.builder() |
|||
.signWith(SignatureAlgorithm.RS256, getPrivateKey(pri)) |
|||
.setIssuer(iss) |
|||
.setExpiration(new Date(date.getTime() + exp)) |
|||
.setIssuedAt(date) |
|||
.compact(); |
|||
} |
|||
|
|||
public static String getToken(String iss, String pri, Long exp, Map<String, Object> claims) throws Exception { |
|||
Date date = new Date(System.currentTimeMillis()); |
|||
return Jwts |
|||
.builder() |
|||
.setClaims(claims) |
|||
.signWith(SignatureAlgorithm.RS256, getPrivateKey(pri)) |
|||
.setIssuer(iss) |
|||
.setExpiration(new Date(date.getTime() + exp)) |
|||
.setIssuedAt(date) |
|||
.compact(); |
|||
} |
|||
|
|||
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { |
|||
return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(publicKey.getBytes()))); |
|||
} |
|||
|
|||
public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception { |
|||
return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(privateKey.getBytes()))); |
|||
} |
|||
|
|||
public static Key stringToPublickKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { |
|||
return getPublicKey(key); |
|||
} |
|||
|
|||
public static Key stringToPrivateKey(String key) throws Exception { |
|||
return getPrivateKey(key); |
|||
} |
|||
} |
|||
@ -0,0 +1,93 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import cn.pelerin.wh.transaction.model.exception.ServiceException; |
|||
import org.apache.commons.collections4.CollectionUtils; |
|||
import org.apache.commons.lang3.ArrayUtils; |
|||
import org.apache.commons.lang3.StringUtils; |
|||
import org.springframework.stereotype.Component; |
|||
import org.springframework.util.ReflectionUtils; |
|||
|
|||
import java.lang.reflect.Field; |
|||
import java.util.Collection; |
|||
import java.util.List; |
|||
|
|||
/** |
|||
* 断言 - 中断往下操作, 直接返回到前端 |
|||
* |
|||
* @author xie.xinquan |
|||
* @create 2021/5/13 11:21 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
@Component |
|||
public class AssertUtil { |
|||
|
|||
private static final String defaultNullMsg = "参数为空"; |
|||
|
|||
public static void haveLength(String str, String msg) { |
|||
if (StringUtils.isEmpty(str)) { |
|||
throw new ServiceException(msg); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* 校验前端传过来的数据 |
|||
* |
|||
* @param t |
|||
* @param list |
|||
* @param msg |
|||
* @param <T> |
|||
*/ |
|||
public static <T> void dataNotNull(T t, List<T> list, String msg) { |
|||
if (t instanceof String && StringUtils.isEmpty((String) t) && CollectionUtils.isEmpty(list)) { |
|||
throw new ServiceException(msg); |
|||
} |
|||
if (t == null && CollectionUtils.isEmpty(list)) { |
|||
throw new ServiceException(msg); |
|||
} |
|||
} |
|||
|
|||
public static void collectionNotNull(Collection collection, String msg) { |
|||
if (CollectionUtils.isEmpty(collection)) { |
|||
throw new ServiceException(msg); |
|||
} |
|||
} |
|||
|
|||
public static void notNull(Object obj) { |
|||
notNull(obj, defaultNullMsg); |
|||
} |
|||
|
|||
public static void notNull(Object obj, String msg) { |
|||
if (obj == null) { |
|||
throw new ServiceException(msg); |
|||
} |
|||
} |
|||
|
|||
public static void notNull(Object obj, String... fieldNames) { |
|||
notNull(defaultNullMsg, obj, fieldNames); |
|||
} |
|||
|
|||
/** |
|||
* 校验字段是否为空 |
|||
* |
|||
* @param msg |
|||
* @param obj |
|||
* @param fieldNames |
|||
*/ |
|||
public static void notNull(String msg, Object obj, String... fieldNames) { |
|||
notNull(obj, msg); |
|||
if (ArrayUtils.isEmpty(fieldNames)) { |
|||
throw new ServiceException(msg); |
|||
} |
|||
for (String fieldName : fieldNames) { |
|||
Field field = ReflectionUtils.findField(obj.getClass(), fieldName); |
|||
notNull(field, msg); |
|||
field.setAccessible(true); |
|||
Object value = ReflectionUtils.getField(field, obj); |
|||
if (field.getType().isAssignableFrom(String.class)) { |
|||
haveLength((String) value, msg); |
|||
} else { |
|||
notNull(value, msg); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,59 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import org.springframework.data.redis.core.StringRedisTemplate; |
|||
import org.springframework.stereotype.Component; |
|||
import org.springframework.util.ObjectUtils; |
|||
|
|||
import javax.annotation.PostConstruct; |
|||
import javax.annotation.Resource; |
|||
import java.text.SimpleDateFormat; |
|||
import java.util.Date; |
|||
|
|||
/** |
|||
* 生成订单号 |
|||
**/ |
|||
@Component |
|||
public class CreateOrderNo { |
|||
private static StringRedisTemplate redisTemplate; |
|||
|
|||
@Resource |
|||
private StringRedisTemplate stringRedisTemplate; |
|||
|
|||
@PostConstruct |
|||
public void beforeInit() { |
|||
redisTemplate = stringRedisTemplate; |
|||
} |
|||
|
|||
private final static String ORDER_NO = "orderNo:"; |
|||
private final static String ORDER_DATE = "orderDate:"; |
|||
private static String PREX = "RB"; |
|||
|
|||
//生成充值订单编号
|
|||
public static String createOrderNo() { |
|||
Date date = new Date(); |
|||
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); |
|||
|
|||
String curDate = sdf.format(date); |
|||
|
|||
String orderDate = redisTemplate.opsForValue().get(ORDER_DATE); |
|||
if (ObjectUtils.isEmpty(orderDate)) { |
|||
redisTemplate.opsForValue().set(ORDER_DATE, curDate); |
|||
} else { |
|||
if (!orderDate.equals(curDate)) { |
|||
//线程安全,在并发的情况下保证只有一个线程清零订单号
|
|||
synchronized (CreateOrderNo.class) { |
|||
if (!redisTemplate.opsForValue().get(ORDER_DATE).equals(curDate)) { |
|||
redisTemplate.opsForValue().set(ORDER_NO, "0"); |
|||
redisTemplate.opsForValue().set(ORDER_DATE, curDate); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
Long orderNo = redisTemplate.opsForValue().increment(ORDER_NO); |
|||
String no = String.format("%0" + 6 + "d", orderNo); |
|||
StringBuilder sb = new StringBuilder(PREX); |
|||
sb.append(curDate).append(no); |
|||
return sb.toString(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,46 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import com.google.common.collect.Lists; |
|||
import org.springframework.util.ObjectUtils; |
|||
|
|||
import java.util.List; |
|||
|
|||
/** |
|||
* @author xie.xinquan |
|||
* @create 2021/1/11 14:17 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
public class DataUtil { |
|||
|
|||
|
|||
/** |
|||
* 将大集合分批成多个子集 -- 设置默认值 |
|||
*/ |
|||
public static <E> List<List<E>> bigSetSplit(List<E> list){ |
|||
return bigSetSplit(list, null); |
|||
} |
|||
|
|||
/** |
|||
* 将大集合分批成多个子集 |
|||
*/ |
|||
public static <E> List<List<E>> bigSetSplit(List<E> list, Integer batchCount){ |
|||
if (ObjectUtils.isEmpty(list)){ |
|||
return Lists.newArrayList(); |
|||
} |
|||
List<List<E>> result = Lists.newArrayList(); |
|||
|
|||
// 每批commit的个数
|
|||
batchCount = batchCount == null || batchCount <= 0 ? 100 : batchCount; |
|||
//循环次数
|
|||
int cycleTimes = list.size() % batchCount == 0 ? list.size() / batchCount : list.size() / batchCount + 1; |
|||
|
|||
for (int i = 0; i < cycleTimes; i++){ |
|||
int startIndex = i * batchCount; |
|||
int endIndex = (i+1) * batchCount; |
|||
endIndex = endIndex > list.size() ? list.size() : endIndex; |
|||
|
|||
result.add(list.subList(startIndex, endIndex)); |
|||
} |
|||
return result; |
|||
} |
|||
} |
|||
@ -0,0 +1,29 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import org.apache.http.client.utils.DateUtils; |
|||
import org.springframework.util.CollectionUtils; |
|||
import org.springframework.util.StringUtils; |
|||
|
|||
import java.util.Date; |
|||
import java.util.List; |
|||
|
|||
/** |
|||
* @author xie.xinquan |
|||
* @create 2022/6/13 13:54 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
public class DateUtil { |
|||
|
|||
private static final String dateFormat = "yyyy-MM-dd"; |
|||
private static final String dateTimeFormat = "yyyy-MM-dd HH:mm:ss"; |
|||
|
|||
public static Date[] dateRangeConvert(List<String> list) { |
|||
Date[] result = new Date[2]; |
|||
if (!CollectionUtils.isEmpty(list) && list.size() == 2 && list.stream().filter(s -> StringUtils.isEmpty(s)).count() == 0) { |
|||
String start = list.get(0); |
|||
result[0] = DateUtils.parseDate(start + " 00:00:00", new String[]{dateTimeFormat}); |
|||
result[1] = DateUtils.parseDate(list.get(1) + " 23:59:59", new String[]{dateTimeFormat}); |
|||
} |
|||
return result; |
|||
} |
|||
} |
|||
@ -0,0 +1,84 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import lombok.Cleanup; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.apache.commons.io.FileUtils; |
|||
import org.apache.commons.lang3.StringUtils; |
|||
|
|||
import java.io.*; |
|||
import java.net.HttpURLConnection; |
|||
import java.net.URL; |
|||
import java.net.URLConnection; |
|||
|
|||
/** |
|||
* @author xie.xinquan |
|||
* @create 2022/6/13 14:57 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
@Slf4j |
|||
public class DownloadZip { |
|||
|
|||
public static boolean download(String urlString, String filename) { |
|||
try { |
|||
// 构造URL
|
|||
URL url = new URL(urlString); |
|||
// 打开连接
|
|||
URLConnection con = url.openConnection(); |
|||
// 输入流
|
|||
@Cleanup InputStream is = con.getInputStream(); |
|||
// 1K的数据缓冲
|
|||
byte[] bs = new byte[1024]; |
|||
// 读取到的数据长度
|
|||
int len; |
|||
// 输出的文件流
|
|||
@Cleanup OutputStream os = new FileOutputStream(filename); |
|||
// 开始读取
|
|||
while ((len = is.read(bs)) != -1) { |
|||
os.write(bs, 0, len); |
|||
} |
|||
} catch (Exception e) { |
|||
return false; |
|||
} |
|||
return true; |
|||
} |
|||
|
|||
/** |
|||
* 判断是否存在远程文件, 了解:php的get_headers函数 |
|||
* @param urlString |
|||
* @return |
|||
*/ |
|||
public static boolean remoteFileIsExists(String urlString) { |
|||
|
|||
boolean isExist = false; |
|||
try{ |
|||
URL url = new URL(urlString);// 注:urlStr中需将空格替换为%20,否则报505
|
|||
HttpURLConnection conn = (HttpURLConnection ) url.openConnection(); |
|||
int state = conn.getResponseCode(); |
|||
if(state == 200){ |
|||
isExist = true; |
|||
}else{ |
|||
isExist = false; |
|||
} |
|||
}catch(Exception e){ |
|||
isExist = false; |
|||
} |
|||
return isExist; |
|||
} |
|||
|
|||
/** |
|||
* 会忽略文件:example: D:\\test\\test.txt 创建 D:\\test |
|||
* @param filePath |
|||
*/ |
|||
public static void createParentDirectory(String filePath) { |
|||
if (StringUtils.isEmpty(filePath)) { |
|||
return; |
|||
} |
|||
|
|||
String directory = filePath.replace("\\", "/").substring(0, filePath.lastIndexOf("/")); |
|||
try { |
|||
FileUtils.forceMkdir(new File(directory)); |
|||
}catch (IOException e) { |
|||
log.error("创建文件夹错误", e); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,146 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import com.alibaba.druid.DbType; |
|||
import com.alibaba.druid.sql.SQLUtils; |
|||
import com.google.common.collect.Lists; |
|||
import org.apache.commons.collections4.MapUtils; |
|||
import org.apache.commons.io.FileUtils; |
|||
import org.apache.commons.lang3.StringUtils; |
|||
|
|||
import java.io.File; |
|||
import java.io.IOException; |
|||
import java.io.InputStream; |
|||
import java.sql.*; |
|||
import java.util.*; |
|||
import java.util.concurrent.TimeUnit; |
|||
import java.util.stream.Stream; |
|||
|
|||
/** |
|||
* @author xie.xinquan |
|||
* @create 2022/6/15 10:15 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
public class FormatLogSqlUtil { |
|||
|
|||
private static final String phpLogFilePath = "D:\\project\\wh_php\\runtime\\admin\\log\\202206\\"; |
|||
|
|||
|
|||
public static void main(String[] args) throws IOException, InterruptedException { |
|||
|
|||
File file = new File(phpLogFilePath); |
|||
File[] files = file.listFiles(); |
|||
File lastFile = Stream.of(files).max(Comparator.comparing(o -> o.lastModified())).get(); |
|||
long l = lastFile.lastModified(); |
|||
List<String> list = FileUtils.readLines(lastFile, "utf-8"); |
|||
int size = list.size(); |
|||
while (true) { |
|||
TimeUnit.SECONDS.sleep(1); |
|||
if (lastFile.lastModified() > l) { |
|||
l = lastFile.lastModified(); |
|||
list = FileUtils.readLines(lastFile, "utf-8"); |
|||
List<String> data = list.subList(size, list.size()); |
|||
size = list.size(); |
|||
for (String str : data) { |
|||
str = StringUtils.substringAfter(str, " "); |
|||
str = StringUtils.substringBeforeLast(str, "["); |
|||
try { |
|||
String format = SQLUtils.format(str, DbType.mysql); |
|||
if (StringUtils.isNotEmpty(format)) { |
|||
System.out.println("...........start..............."); |
|||
System.out.println(format); |
|||
// 执行SQL
|
|||
execSql(str); |
|||
System.out.println("............end................"); |
|||
} |
|||
}catch (Exception e) { |
|||
System.out.println("格式化出错:" + e.getMessage()); |
|||
} |
|||
} |
|||
} |
|||
} |
|||
} |
|||
private static Connection connection ; |
|||
private static void setConnection() throws IOException, ClassNotFoundException, SQLException { |
|||
Properties properties = new Properties(); |
|||
{ |
|||
InputStream resourceAsStream = FormatLogSqlUtil.class.getClassLoader().getResourceAsStream("application.properties"); |
|||
properties.load(resourceAsStream); |
|||
resourceAsStream.close(); |
|||
} |
|||
String dev = MapUtils.getString(properties, "spring.profiles.active", "dev"); |
|||
{ |
|||
Properties prop = new Properties(); |
|||
InputStream resourceAsStream = FormatLogSqlUtil.class.getClassLoader().getResourceAsStream(String.format("application-%s.properties", dev)); |
|||
prop.load(resourceAsStream); |
|||
resourceAsStream.close(); |
|||
for (Map.Entry<Object, Object> entry : prop.entrySet()) { |
|||
properties.put(entry.getKey(), entry.getValue()); |
|||
} |
|||
} |
|||
Class.forName(properties.getProperty("spring.datasource.driverClassName")); |
|||
|
|||
connection = DriverManager.getConnection(properties.getProperty("spring.datasource.url"), properties.getProperty("spring.datasource.username"), properties.getProperty("spring.datasource.password")); |
|||
|
|||
} |
|||
private static void execSql(String sql) throws SQLException, IOException, ClassNotFoundException { |
|||
|
|||
if (connection == null) { |
|||
setConnection(); |
|||
} |
|||
PreparedStatement preparedStatement = connection.prepareStatement(sql); |
|||
ResultSet resultSet = preparedStatement.executeQuery(); |
|||
|
|||
System.out.println("...执行sql start..."); |
|||
ResultSetMetaData metaData = resultSet.getMetaData(); |
|||
List<List<String>> execdata = new ArrayList<>(); |
|||
int columnCount = metaData.getColumnCount(); |
|||
{ |
|||
int i = 0; |
|||
List<String> data = new ArrayList<>(); |
|||
while (++i <= columnCount) { |
|||
data.add(metaData.getColumnName(i)); |
|||
} |
|||
execdata.add(data); |
|||
} |
|||
while (resultSet.next()) { |
|||
int i = 0; |
|||
List<String> data = new ArrayList<>(); |
|||
while (++i <= columnCount) { |
|||
data.add(resultSet.getString(i)); |
|||
} |
|||
execdata.add(data); |
|||
} |
|||
int[] max = new int[execdata.get(0).size()]; |
|||
for (List<String> list : execdata) { |
|||
for (int i = 0; i < list.size(); i++) { |
|||
String s = list.get(i) == null ? "null" : list.get(i); |
|||
max[i] = Math.max(max[i], charLen(s)); |
|||
} |
|||
} |
|||
for (List<String> list : execdata) { |
|||
for (int i = 0; i < list.size(); i++) { |
|||
String s = list.get(i) == null ? "null" : list.get(i); |
|||
while (s.length() < max[i]) s += ' '; |
|||
list.set(i, s); |
|||
} |
|||
System.out.println(StringUtils.join(list, " ")); |
|||
} |
|||
|
|||
System.out.println("...执行sql end..."); |
|||
|
|||
} |
|||
private static int charLen(String str) { |
|||
double len = 0; |
|||
for (char c : str.toCharArray()) { |
|||
if (isChineseChar(c)) { |
|||
len += 1.66; |
|||
}else { |
|||
len += 1; |
|||
} |
|||
} |
|||
return (int) len; |
|||
} |
|||
public static boolean isChineseChar(char c) { |
|||
return String.valueOf(c).matches("[\u4e00-\u9fa5]"); |
|||
} |
|||
} |
|||
@ -0,0 +1,78 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.apache.commons.lang3.StringUtils; |
|||
|
|||
import javax.servlet.http.HttpServletRequest; |
|||
import java.net.InetAddress; |
|||
import java.net.UnknownHostException; |
|||
|
|||
/** |
|||
* 描述: |
|||
* |
|||
* @author dong.jun |
|||
* @create 2022-03-11 18:31 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
@Slf4j |
|||
public class IPUtil { |
|||
private static final String IP_UTILS_FLAG = ","; |
|||
private static final String UNKNOWN = "unknown"; |
|||
private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1"; |
|||
private static final String LOCALHOST_IP1 = "127.0.0.1"; |
|||
|
|||
/** |
|||
* 获取IP地址 |
|||
* <p> |
|||
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 |
|||
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 |
|||
*/ |
|||
public static String getIpAddr(HttpServletRequest request) { |
|||
String ip = null; |
|||
try { |
|||
//以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
|
|||
ip = request.getHeader("X-Original-Forwarded-For"); |
|||
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getHeader("X-Forwarded-For"); |
|||
} |
|||
//获取nginx等代理的ip
|
|||
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getHeader("x-forwarded-for"); |
|||
} |
|||
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getHeader("Proxy-Client-IP"); |
|||
} |
|||
if (StringUtils.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getHeader("WL-Proxy-Client-IP"); |
|||
} |
|||
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getHeader("HTTP_CLIENT_IP"); |
|||
} |
|||
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getHeader("HTTP_X_FORWARDED_FOR"); |
|||
} |
|||
//兼容k8s集群获取ip
|
|||
if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) { |
|||
ip = request.getRemoteAddr(); |
|||
if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) { |
|||
//根据网卡取本机配置的IP
|
|||
InetAddress iNet = null; |
|||
try { |
|||
iNet = InetAddress.getLocalHost(); |
|||
} catch (UnknownHostException e) { |
|||
log.error("getClientIp error: {}", e); |
|||
} |
|||
ip = iNet.getHostAddress(); |
|||
} |
|||
} |
|||
} catch (Exception e) { |
|||
log.error("IPUtils ERROR ", e); |
|||
} |
|||
//使用代理,则获取第一个IP地址
|
|||
if (!StringUtils.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) { |
|||
ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG)); |
|||
} |
|||
|
|||
return ip; |
|||
} |
|||
} |
|||
@ -0,0 +1,123 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import cn.pelerin.wh.transaction.auth.entity.Cert; |
|||
import cn.pelerin.wh.transaction.auth.mapper.CertMapper; |
|||
import cn.pelerin.wh.transaction.constant.CertTypeConst; |
|||
import cn.pelerin.wh.transaction.model.base.SysLogin; |
|||
import com.auth0.jwt.JWT; |
|||
import com.auth0.jwt.interfaces.DecodedJWT; |
|||
import com.google.common.collect.Maps; |
|||
import io.jsonwebtoken.Claims; |
|||
import io.jsonwebtoken.Jwts; |
|||
import io.jsonwebtoken.SignatureAlgorithm; |
|||
import io.jsonwebtoken.impl.TextCodec; |
|||
import lombok.SneakyThrows; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.apache.commons.io.FileUtils; |
|||
import org.apache.tomcat.util.codec.binary.Base64; |
|||
import org.springframework.stereotype.Component; |
|||
import org.springframework.util.ObjectUtils; |
|||
|
|||
import javax.annotation.PostConstruct; |
|||
import javax.annotation.Resource; |
|||
import javax.crypto.SecretKey; |
|||
import javax.crypto.spec.SecretKeySpec; |
|||
import java.io.File; |
|||
import java.util.Map; |
|||
import java.util.Objects; |
|||
|
|||
/** |
|||
* @author :luo.laiyong |
|||
* @date :Created in 2019/6/5 11:20 |
|||
* @company: 深圳亿起融网络科技有限公司 |
|||
* @modified By: |
|||
*/ |
|||
@Slf4j |
|||
@Component |
|||
public class JwtRsaUtil { |
|||
@Resource |
|||
private CertMapper certMapper; |
|||
private static CertMapper initCertMapper; |
|||
|
|||
@PostConstruct |
|||
public void beforeInit() { |
|||
initCertMapper = certMapper; |
|||
} |
|||
|
|||
private static Claims parseJWT(String token, String signKey) { |
|||
SecretKey key = generalKey(signKey); //签名秘钥,和生成的签名的秘钥一模一样
|
|||
Claims claims = Jwts.parser() //得到DefaultJwtParser
|
|||
.setSigningKey(key) //设置签名的秘钥
|
|||
.parseClaimsJws(token).getBody();//设置需要解析的jwt
|
|||
return claims; |
|||
} |
|||
|
|||
public static SysLogin getUserFromToken(String token) { |
|||
try { |
|||
DecodedJWT decodedJWT = JWT.decode(token); |
|||
if (!ObjectUtils.isEmpty(decodedJWT.getClaims())) { |
|||
SysLogin sysLoginInfo = new SysLogin(); |
|||
sysLoginInfo.setIat(decodedJWT.getClaim("iat").asInt()); |
|||
sysLoginInfo.setMenuPermission(decodedJWT.getClaim("menuPermission").asList(String.class)); |
|||
sysLoginInfo.setAccountId(decodedJWT.getClaim("accountId").asString()); |
|||
sysLoginInfo.setAccountName(decodedJWT.getClaim("accountName").asString()); |
|||
sysLoginInfo.setAud(decodedJWT.getClaim("aud").asString()); |
|||
sysLoginInfo.setJti(decodedJWT.getClaim("jti").asString()); |
|||
return sysLoginInfo; |
|||
} |
|||
} catch (Exception e) { |
|||
log.error("DecodedJWT error", e); |
|||
} |
|||
return null; |
|||
} |
|||
|
|||
public static SecretKey generalKey(String signKey) { |
|||
byte[] encodedKey = Base64.decodeBase64(signKey);//本地的密码解码
|
|||
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, SignatureAlgorithm.HS256.getValue());// 根据给定的字节数组使用AES加密算法构造一个密钥,使用 encodedKey中的始于且包含 0 到前 leng 个字节这是当然是所有。(后面的文章中马上回推出讲解Java加密和解密的一些算法)
|
|||
return key; |
|||
} |
|||
|
|||
@SneakyThrows |
|||
public static void main(String[] args) { |
|||
//String signKey = "KHXT0V7NVLOFPS9BZ88R5VLIH5COPULV";
|
|||
String token = "eyJhbGciOiJIUzUxMiJ9.eyJhdWQiOiJCRDg0REQ0MkE3MjM0QjA1QjBDNUQxMTYxNjEzMkFDNCIsImp0aSI6IjcyMDgyMWZiMjNiNTQ4YjZhMmMxNGNlYjYxMjEzYWI0IiwiYWNjb3VudElkIjoiYWRtaW4iLCJhY2NvdW50TmFtZSI6Iui2hee6p-euoeeQhuWRmCIsIm1lbnVQZXJtaXNzaW9uIjpbIm1fMDAyIiwibV8wMDMiLCJtXzAwNCIsIm1fMDA1IiwibV8wMDYiXSwiaWF0IjoxNjU1MDk5NjU2fQ.pmXSrvjSJjTFB22QyTp3q7ZlzFwcqlHVYI-qCPlc1zfeQa6Spn_AJdAT-VkLyXPbaKUaovroUvZ_ay5vug5Aow"; |
|||
getUserFromToken(token); |
|||
////Claims claims = parseJWT(token, signKey);
|
|||
//String str = Base64Util.encode(signKey);
|
|||
//Claims claims = Jwts.parser() //得到DefaultJwtParser
|
|||
// .setSigningKey(str) //设置签名的秘钥
|
|||
// .parseClaimsJws(token).getBody();
|
|||
//System.out.println(claims);
|
|||
DecodedJWT decodedJWT = JWT.decode(token); |
|||
String json = TextCodec.BASE64URL.decodeToString("eyJhdWQiOiJCRDg0REQ0MkE3MjM0QjA1QjBDNUQxMTYxNjEzMkFDNCIsImp0aSI6IjcyMDgyMWZiMjNiNTQ4YjZhMmMxNGNlYjYxMjEzYWI0IiwiYWNjb3VudElkIjoiYWRtaW4iLCJhY2NvdW50TmFtZSI6Iui2hee6p-euoeeQhuWRmCIsIm1lbnVQZXJtaXNzaW9uIjpbIm1fMDAyIiwibV8wMDMiLCJtXzAwNCIsIm1fMDA1IiwibV8wMDYiXSwiaWF0IjoxNjU1MDk5NjU2fQ"); |
|||
System.out.println(json); |
|||
} |
|||
|
|||
/** |
|||
* 调用其他系统时,需要生成token写入header |
|||
* |
|||
* @param type |
|||
* @return |
|||
*/ |
|||
public static String createSign(String type) { |
|||
Cert cert = initCertMapper.selectOneByStatusAndType(0, type); |
|||
//读取私钥
|
|||
String privateFilePath = System.getProperty("user.dir") + cert.getPrivateKey(); |
|||
String token = ""; |
|||
try { |
|||
String privateKey = FileUtils.readFileToString(new File(privateFilePath)); |
|||
privateKey = privateKey.replaceAll("\\-*BEGIN.*KEY\\-*", "").replaceAll("\\-*END.*KEY\\-*", ""); |
|||
if (Objects.equals(CertTypeConst.USER_REAL, type)) { |
|||
Map<String, Object> claims = Maps.newHashMap(); |
|||
claims.put("aud", "BD84DD42A7234B05B0C5D11616132AC4"); |
|||
token = ApiTokenUtils.getToken(cert.getToken(), privateKey, 5 * 60 * 1000L, claims); |
|||
} else { |
|||
token = ApiTokenUtils.getToken(cert.getToken(), privateKey, 5 * 60 * 1000L); |
|||
} |
|||
} catch (Exception e) { |
|||
log.error("createSign error", e); |
|||
} |
|||
return token; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,30 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import java.net.HttpURLConnection; |
|||
import java.net.URL; |
|||
|
|||
/** |
|||
* 描述: |
|||
* |
|||
* @author xu.jin.feng |
|||
* @create 2022/6/16 11:44 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
public class NetUtil { |
|||
|
|||
/** |
|||
* 判断网络图片是否存在 |
|||
* imgUrl 图片地址链接 |
|||
*/ |
|||
public static Boolean checkUrlValidity(String imgUrl) { |
|||
int RESPONSE_CODE = 0; |
|||
try { |
|||
URL url = new URL(imgUrl); |
|||
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
|||
RESPONSE_CODE = connection.getResponseCode(); |
|||
} catch (Exception e) { |
|||
} |
|||
return RESPONSE_CODE == HttpURLConnection.HTTP_OK; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,75 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import com.github.pagehelper.PageInfo; |
|||
import org.springframework.util.ObjectUtils; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.Arrays; |
|||
import java.util.List; |
|||
|
|||
public class PageUtil { |
|||
|
|||
private PageUtil() { |
|||
} |
|||
|
|||
/** |
|||
* 分页 |
|||
* |
|||
* @param pageSize 每页记录数 |
|||
* @param pageNum 起始页 从1开始 |
|||
* @param list 原集合数据 |
|||
* @return |
|||
*/ |
|||
public static <T> List<T> getPageList(Integer pageNum, Integer pageSize, List<T> list) { |
|||
List<T> result = new ArrayList<>(); |
|||
Integer fromIndex = 0; |
|||
if (pageNum > 0 && !ObjectUtils.isEmpty(list)) { |
|||
fromIndex = (pageNum * pageSize) - pageSize; |
|||
Integer toIndex = pageSize * pageNum; |
|||
if (list.size() < fromIndex) { |
|||
return result; |
|||
} |
|||
if (list.size() < toIndex) { |
|||
toIndex = list.size(); |
|||
} |
|||
result = list.subList(fromIndex, toIndex); |
|||
} |
|||
return result; |
|||
} |
|||
|
|||
/** |
|||
* 分页 封装 |
|||
* @param pageNum |
|||
* @param pageSize |
|||
* @param list |
|||
* @param <T> |
|||
* @return |
|||
*/ |
|||
public static <T> PageInfo<T> getPageInfo(Integer pageNum, Integer pageSize, List<T> list){ |
|||
List<T> result = getPageList(pageNum, pageSize, list); |
|||
PageInfo<T> pageInfo = new PageInfo<>(result); |
|||
pageInfo.setTotal(list.size()); |
|||
pageInfo.setPageNum(pageNum); |
|||
pageInfo.setPageSize(pageSize); |
|||
if (ObjectUtils.isEmpty(result)){ |
|||
pageInfo.setNextPage(0); |
|||
}else { |
|||
Integer left = list.size() - pageNum * pageSize; |
|||
if (left <= 0){ |
|||
pageInfo.setNextPage(0); |
|||
}else { |
|||
pageInfo.setNextPage(pageNum + 1);//还有数据
|
|||
} |
|||
} |
|||
return pageInfo; |
|||
} |
|||
|
|||
public static void main(String[] args) { |
|||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); |
|||
List<Integer> result = getPageList(2, 3, list); |
|||
|
|||
PageInfo pageInfo = getPageInfo(4, 3, list); |
|||
|
|||
System.out.println(pageInfo); |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
package cn.chjyj.szwh.utils; |
|||
|
|||
import org.springframework.util.ObjectUtils; |
|||
|
|||
/** |
|||
* @author xie.xinquan |
|||
* @create 2022/6/13 17:28 |
|||
* @company 深圳亿起融网络科技有限公司 |
|||
*/ |
|||
public class ReplaceUtil { |
|||
|
|||
public static <T> T nullReplace(T data, T target) { |
|||
return ObjectUtils.isEmpty(data) ? target : data; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue