文旅相关逻辑集成
This commit is contained in:
+2
-1
@@ -22,5 +22,6 @@
|
||||
<module>zlt-elasticsearch-spring-boot-starter</module>
|
||||
<module>zlt-oss-spring-boot-starter</module>
|
||||
<module>zlt-zookeeper-spring-boot-starter</module>
|
||||
<module>zlt-iot-spring-boot-starter</module>
|
||||
</modules>
|
||||
</project>
|
||||
</project>
|
||||
|
||||
@@ -102,5 +102,16 @@
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
<version>2.6</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
</project>
|
||||
|
||||
+4
@@ -16,4 +16,8 @@ public interface ServiceNameConstants {
|
||||
* 搜索中心服务
|
||||
*/
|
||||
String SEARCH_SERVICE = "search-center";
|
||||
|
||||
String UAA_SERVICE = "uaa-center";
|
||||
|
||||
String DEVICE_SERVICE = "device-center";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.security.*;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* RSA加解密、创建与校验签名的工具类
|
||||
*/
|
||||
@Slf4j
|
||||
public class RSAUtil {
|
||||
public static final String PUBLIC_KEY = "PUBLIC_KEY";
|
||||
public static final String PRIVATE_KEY = "PRIVATE_KEY";
|
||||
|
||||
private static final Base64.Encoder base64Encoder = Base64.getEncoder();
|
||||
private static final Base64.Decoder base64Decoder = Base64.getDecoder();
|
||||
|
||||
private static final String ALGORITHM = "RSA/ECB/PKCS1Padding";
|
||||
/**
|
||||
* 签名算法
|
||||
*/
|
||||
private static final String SIGN_TYPE = "SHA1withRSA";
|
||||
/**
|
||||
* 密钥长度
|
||||
*/
|
||||
private static final Integer KEY_LENGTH = 1024;
|
||||
|
||||
/**
|
||||
* RSA最大加密明文大小
|
||||
*/
|
||||
private static final int MAX_ENCRYPT_BLOCK = 117;
|
||||
/**
|
||||
* RSA最大解密密文大小
|
||||
*/
|
||||
private static final int MAX_DECRYPT_BLOCK = 128;
|
||||
public static PublicKey publicKey;
|
||||
public static PrivateKey privateKey;
|
||||
|
||||
static {
|
||||
Map<String, Key> map = null;
|
||||
try {
|
||||
map = genKeyPair();
|
||||
publicKey = (PublicKey) map.get(PUBLIC_KEY);
|
||||
privateKey = (PrivateKey) map.get(PRIVATE_KEY);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 生成秘钥对,公钥和私钥
|
||||
*
|
||||
* @return 秘钥键值对
|
||||
* @throws Exception 创建秘钥对异常
|
||||
*/
|
||||
public static Map<String, Key> genKeyPair() throws Exception {
|
||||
Map<String, Key> keyMap = new HashMap<>();
|
||||
String pubKey =
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy" +
|
||||
"pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm" +
|
||||
"tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK" +
|
||||
"N/iJDXFFXdEOmfdqhwIDAQAB";
|
||||
Base64.Decoder decoder = Base64.getDecoder();
|
||||
byte[] keyBytes = decoder.decode(pubKey);
|
||||
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
|
||||
KeyFactory kf = KeyFactory.getInstance("RSA");
|
||||
PublicKey publicKey = kf.generatePublic(spec);
|
||||
String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIa7uVgZ8S0wgI7y" +
|
||||
"REQms5u7QfKkXtH2IQh5/LECmYHrAn/LdGD94E7qQsMKjXyFhndk3EqnkIzKZm9c" +
|
||||
"OHmP6x3sgea1SHqwRnOlcTFAkjNPyADVJQt36Jd7hX3O3YBxtE4iL3i8DqU5+a04" +
|
||||
"3bwTH64CUso3+IkNcUVd0Q6Z92qHAgMBAAECgYAogZGkahA3DMjpsO5TKut+m1ql" +
|
||||
"T0Nujje6K6qLsQNjqrrSnuE7M7hXIVi2+Jo24JHfnUQZca0klskbG7ei3GDL6eEb" +
|
||||
"Qm3NlJ84bxDQUOy6SSiqZHYKP0Yvwgk3uR8OM6hjnv6c7b5HPlvp00DuMlwkw+ST" +
|
||||
"Ng5ErJrgx6g7Dte1KQJBAN2Bp1HQ804cnqZyEfQLjx/uf1+BKGXsEjf25u5WZCZ5" +
|
||||
"slxIbtkhtG61L4z7uOLxBKyixR37YvM94HNxLQ2+7E0CQQCbttyVTpnXRXrzhUT7" +
|
||||
"W8ML8BE5jiCqbU/Y1VAm7Sp5D3SOLDbMZKG8lV6duUYSdoYY7ZrqO8qU6XWXbWxj" +
|
||||
"r4wjAkA9lMobqOe7k6FXzObI3l3QFtI6jwHYNCVsgav6HvKA79xyY4DNxN0Q2jZ6" +
|
||||
"D5F7Jl6SUD5U84qy7UT1U0WfSLERAkB3zv3v33dc/De60SqfYB41vDP0ndeiadMK" +
|
||||
"2i3+lXKdjPe4QGq1XyRWjnMrVheFMy7AVWlhmjmn0+1HYskH9lUTAkBRlC0bbsMh" +
|
||||
"ttwtWnWvTjgCynymlKYKmzakBllknkokCE3cjefS5BoG0yAavZUJ4bozaTBVRcs5" +
|
||||
"JN1IsgxqgsOq";
|
||||
byte[] decoded = decoder.decode(privateKey);
|
||||
|
||||
RSAPrivateKey rsaPrivateKey =
|
||||
(RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
|
||||
keyMap.put(PUBLIC_KEY, publicKey);
|
||||
keyMap.put(PRIVATE_KEY, rsaPrivateKey);
|
||||
return keyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥加密
|
||||
*
|
||||
* @param data 加密前数据
|
||||
* @param publicKey 公钥
|
||||
* @return 加密后数据
|
||||
* @throws Exception 加密异常
|
||||
*/
|
||||
public static byte[] encryptByPublicKey(byte[] data, PublicKey publicKey) throws Exception {
|
||||
// 加密数据,分段加密
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
|
||||
int inputLength = data.length;
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int offset = 0;
|
||||
byte[] cache;
|
||||
int i = 0;
|
||||
while (inputLength - offset > 0) {
|
||||
if (inputLength - offset > MAX_ENCRYPT_BLOCK) {
|
||||
cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
|
||||
} else {
|
||||
cache = cipher.doFinal(data, offset, inputLength - offset);
|
||||
}
|
||||
out.write(cache, 0, cache.length);
|
||||
i++;
|
||||
offset = i * MAX_ENCRYPT_BLOCK;
|
||||
}
|
||||
byte[] encryptedData = out.toByteArray();
|
||||
out.close();
|
||||
return encryptedData;
|
||||
}
|
||||
|
||||
public static byte[] encryptByPublicKey(byte[] data, String publicKeyBase64Encoded) throws Exception {
|
||||
return encryptByPublicKey(data, parseString2PublicKey(publicKeyBase64Encoded));
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥解密
|
||||
*
|
||||
* @param data 解密前数据
|
||||
* @param privateKey 私钥
|
||||
* @return 解密后数据
|
||||
* @throws Exception 解密异常
|
||||
*/
|
||||
public static byte[] decryptByPrivateKey(byte[] data, PrivateKey privateKey) {
|
||||
// 解密数据,分段解密
|
||||
try{
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
int inputLength = data.length;
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
int offset = 0;
|
||||
byte[] cache;
|
||||
int i = 0;
|
||||
while (inputLength - offset > 0) {
|
||||
if (inputLength - offset > MAX_DECRYPT_BLOCK) {
|
||||
cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
|
||||
} else {
|
||||
cache = cipher.doFinal(data, offset, inputLength - offset);
|
||||
}
|
||||
out.write(cache);
|
||||
i++;
|
||||
offset = i * MAX_DECRYPT_BLOCK;
|
||||
}
|
||||
byte[] decryptedData = out.toByteArray();
|
||||
out.close();
|
||||
return decryptedData;
|
||||
}catch (Exception e){
|
||||
log.info("解密异常:{}",e.getMessage());
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static byte[] decryptByPrivateKey(byte[] data, String privateKeyBase64Encoded) throws Exception {
|
||||
return decryptByPrivateKey(data, parseString2PrivateKey(privateKeyBase64Encoded));
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建签名
|
||||
*
|
||||
* @param source 要签名的信息
|
||||
* @param privateKey 私钥
|
||||
* @return 签名
|
||||
* @throws Exception 签名异常
|
||||
*/
|
||||
public static byte[] createSign(String source, PrivateKey privateKey) throws Exception {
|
||||
Signature signet = Signature.getInstance(SIGN_TYPE);
|
||||
signet.initSign(privateKey);
|
||||
signet.update(source.getBytes());
|
||||
return signet.sign();
|
||||
}
|
||||
|
||||
public static byte[] createSign(String source, String privateKeyBase64Encoded) throws Exception {
|
||||
return createSign(source, parseString2PrivateKey(privateKeyBase64Encoded));
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验签名
|
||||
*
|
||||
* @param expected 期望信息
|
||||
* @param sign 签名
|
||||
* @param publicKey 公钥
|
||||
* @return 结果
|
||||
* @throws Exception 校验异常
|
||||
*/
|
||||
public static boolean checkSign(String expected, byte[] sign, PublicKey publicKey) throws Exception {
|
||||
Signature signetCheck = Signature.getInstance(SIGN_TYPE);
|
||||
signetCheck.initVerify(publicKey);
|
||||
signetCheck.update(expected.getBytes());
|
||||
return signetCheck.verify(sign);
|
||||
}
|
||||
|
||||
public static boolean checkSign(String expected, byte[] sign, String publicKeyBase64Encoded) throws Exception {
|
||||
return checkSign(expected, sign, parseString2PublicKey(publicKeyBase64Encoded));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将base64格式的公钥转换为对象
|
||||
*
|
||||
* @param publicKeyBase64Encoded base64的公钥
|
||||
* @return 公钥
|
||||
* @throws Exception 转换异常
|
||||
*/
|
||||
public static PublicKey parseString2PublicKey(String publicKeyBase64Encoded) throws Exception {
|
||||
return KeyFactory.getInstance(ALGORITHM).generatePublic(
|
||||
new X509EncodedKeySpec(base64Decoder.decode(publicKeyBase64Encoded)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 将base64格式的私钥转换为对象
|
||||
*
|
||||
* @param privateKeyBase64Encoded base64的私钥
|
||||
* @return 私钥
|
||||
* @throws Exception 转换异常
|
||||
*/
|
||||
public static PrivateKey parseString2PrivateKey(String privateKeyBase64Encoded) throws Exception {
|
||||
return KeyFactory.getInstance(ALGORITHM).generatePrivate(
|
||||
new PKCS8EncodedKeySpec(base64Decoder.decode(privateKeyBase64Encoded)));
|
||||
}
|
||||
public static String getEncData(String data) throws Exception {
|
||||
String enc = Base64.getEncoder().encodeToString(RSAUtil.encryptByPublicKey(data.getBytes(),
|
||||
publicKey));
|
||||
return StringUtils.replace(enc, "/", "%2F");
|
||||
}
|
||||
// 单个解密 私钥
|
||||
public static String decryptOne(String des) {
|
||||
String _imageName = StringUtils.replace(des, "%2F", "/");
|
||||
try {
|
||||
return new String(RSAUtil.decryptByPrivateKey(Base64.getDecoder().decode(_imageName), (PrivateKey) RSAUtil.genKeyPair().get(RSAUtil.PRIVATE_KEY)));
|
||||
} catch (Exception e) {
|
||||
log.info("解密异常:{}",e.getMessage());
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// 单个加密 公钥加密
|
||||
public static String encryptOne(String des) {
|
||||
try {
|
||||
return StringUtils.replace(Base64.getEncoder().encodeToString(RSAUtil.encryptByPublicKey(des.getBytes(), (PublicKey) RSAUtil.genKeyPair().get(RSAUtil.PUBLIC_KEY)))
|
||||
, "/", "%2F");
|
||||
} catch (Exception e) {
|
||||
log.info("加密异常:{}",e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getDecData(String data) throws Exception {
|
||||
String replace = StringUtils.replace(data, "%2F", "/");
|
||||
return new String(decryptByPrivateKey(Base64.getDecoder().decode(replace), privateKey));
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("公钥加密>>>>>>:" + encryptOne("慧谷测试"));
|
||||
System.out.println("私钥解密>>>>>>:" + decryptOne("LBS9qzlDcBQeb+WLhGRKm5+zoQkPokrEdwejn1VZSmYPaLrAS2LUCbSHViZOfUcvql5j57dvMEXw5jhOu7775exptY%2FyHNTxld2PjmgTPg6If4EOFpD4z+YSuQQyTz4lWmKCQ7egP35qYvAyHUkG%2FyNEOSJUClQbrEfnj1OcL1s="));
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package com.central.common.utils;
|
||||
|
||||
import org.apache.commons.lang.StringEscapeUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class StringUtils extends org.apache.commons.lang.StringUtils {
|
||||
static final String HEX_FORMAT = "%02x";
|
||||
private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
|
||||
private static final char SEPARATOR = '_';
|
||||
private static final String CHARSET_NAME = "UTF-8";
|
||||
|
||||
public StringUtils() {
|
||||
}
|
||||
|
||||
public static byte[] getBytes(String str) {
|
||||
if (str != null) {
|
||||
try {
|
||||
return str.getBytes("UTF-8");
|
||||
} catch (UnsupportedEncodingException var2) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String toString(byte[] bytes) {
|
||||
try {
|
||||
return new String(bytes, "UTF-8");
|
||||
} catch (UnsupportedEncodingException var2) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean inString(String str, String... strs) {
|
||||
if (str != null) {
|
||||
String[] var2 = strs;
|
||||
int var3 = strs.length;
|
||||
|
||||
for(int var4 = 0; var4 < var3; ++var4) {
|
||||
String s = var2[var4];
|
||||
if (str.equals(trim(s))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String replaceHtml(String html) {
|
||||
if (isBlank(html)) {
|
||||
return "";
|
||||
} else {
|
||||
String regEx = "<.+?>";
|
||||
Pattern p = Pattern.compile(regEx);
|
||||
Matcher m = p.matcher(html);
|
||||
String s = m.replaceAll("");
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
public static String replaceMobileHtml(String html) {
|
||||
return html == null ? "" : html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
|
||||
}
|
||||
|
||||
public static String toHtml(String txt) {
|
||||
return txt == null ? "" : "";
|
||||
}
|
||||
|
||||
public static String abbr(String str, int length) {
|
||||
if (str == null) {
|
||||
return "";
|
||||
} else {
|
||||
try {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int currentLength = 0;
|
||||
char[] var4 = replaceHtml(StringEscapeUtils.unescapeHtml(str)).toCharArray();
|
||||
int var5 = var4.length;
|
||||
|
||||
for(int var6 = 0; var6 < var5; ++var6) {
|
||||
char c = var4[var6];
|
||||
currentLength += String.valueOf(c).getBytes("GBK").length;
|
||||
if (currentLength > length - 3) {
|
||||
sb.append("...");
|
||||
break;
|
||||
}
|
||||
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
} catch (UnsupportedEncodingException var8) {
|
||||
logger.error("出现异常", var8);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String abbr2(String param, int length) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
} else {
|
||||
StringBuffer result = new StringBuffer();
|
||||
int n = 0;
|
||||
boolean isCode = false;
|
||||
boolean isHTML = false;
|
||||
|
||||
for(int i = 0; i < param.length(); ++i) {
|
||||
char temp = param.charAt(i);
|
||||
if (temp == '<') {
|
||||
isCode = true;
|
||||
} else if (temp == '&') {
|
||||
isHTML = true;
|
||||
} else if (temp == '>' && isCode) {
|
||||
--n;
|
||||
isCode = false;
|
||||
} else if (temp == ';' && isHTML) {
|
||||
isHTML = false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!isCode && !isHTML) {
|
||||
n += String.valueOf(temp).getBytes("GBK").length;
|
||||
}
|
||||
} catch (UnsupportedEncodingException var12) {
|
||||
logger.error("出现异常", var12);
|
||||
}
|
||||
|
||||
if (n > length - 3) {
|
||||
result.append("...");
|
||||
break;
|
||||
}
|
||||
|
||||
result.append(temp);
|
||||
}
|
||||
|
||||
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
|
||||
temp_result = temp_result.replaceAll("</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", "");
|
||||
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
|
||||
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
|
||||
Matcher m = p.matcher(temp_result);
|
||||
ArrayList endHTML = new ArrayList();
|
||||
|
||||
while(m.find()) {
|
||||
endHTML.add(m.group(1));
|
||||
}
|
||||
|
||||
for(int i = endHTML.size() - 1; i >= 0; --i) {
|
||||
result.append("</");
|
||||
result.append((String)endHTML.get(i));
|
||||
result.append(">");
|
||||
}
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static Double toDouble(Object val) {
|
||||
if (val == null) {
|
||||
return 0.0D;
|
||||
} else {
|
||||
try {
|
||||
return Double.valueOf(trim(val.toString()));
|
||||
} catch (Exception var2) {
|
||||
return 0.0D;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Float toFloat(Object val) {
|
||||
return toDouble(val).floatValue();
|
||||
}
|
||||
|
||||
public static Long toLong(Object val) {
|
||||
return toDouble(val).longValue();
|
||||
}
|
||||
|
||||
public static Integer toInteger(Object val) {
|
||||
return toLong(val).intValue();
|
||||
}
|
||||
|
||||
public static boolean toBoolean(String val) {
|
||||
return Boolean.parseBoolean(val);
|
||||
}
|
||||
|
||||
public static String getMessage(String code, Object[] args) {
|
||||
return "";
|
||||
}
|
||||
|
||||
public static BigDecimal toBigDecimal(String str){
|
||||
return new BigDecimal(str).setScale(7, BigDecimal.ROUND_HALF_UP);
|
||||
}
|
||||
|
||||
public static String getRemoteAddr(HttpServletRequest request) {
|
||||
String remoteAddr = request.getHeader("X-Real-IP");
|
||||
if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("X-Forwarded-For");
|
||||
} else if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("Proxy-Client-IP");
|
||||
} else if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
|
||||
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
|
||||
}
|
||||
|
||||
public static String toCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
} else {
|
||||
s = s.toLowerCase();
|
||||
StringBuilder sb = new StringBuilder(s.length());
|
||||
boolean upperCase = false;
|
||||
|
||||
for(int i = 0; i < s.length(); ++i) {
|
||||
char c = s.charAt(i);
|
||||
if (c == '_') {
|
||||
upperCase = true;
|
||||
} else if (upperCase) {
|
||||
sb.append(Character.toUpperCase(c));
|
||||
upperCase = false;
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static String toCapitalizeCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
} else {
|
||||
s = toCamelCase(s);
|
||||
return s.substring(0, 1).toUpperCase() + s.substring(1);
|
||||
}
|
||||
}
|
||||
|
||||
public static String toUnderScoreCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
} else {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean upperCase = false;
|
||||
|
||||
for(int i = 0; i < s.length(); ++i) {
|
||||
char c = s.charAt(i);
|
||||
boolean nextUpperCase = true;
|
||||
if (i < s.length() - 1) {
|
||||
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
|
||||
}
|
||||
|
||||
if (i > 0 && Character.isUpperCase(c)) {
|
||||
if (!upperCase || !nextUpperCase) {
|
||||
sb.append('_');
|
||||
}
|
||||
|
||||
upperCase = true;
|
||||
} else {
|
||||
upperCase = false;
|
||||
}
|
||||
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static String jsGetVal(String objectString) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
StringBuilder val = new StringBuilder();
|
||||
String[] vals = split(objectString, ".");
|
||||
|
||||
for(int i = 0; i < vals.length; ++i) {
|
||||
val.append("." + vals[i]);
|
||||
result.append("!" + val.substring(1) + "?'':");
|
||||
}
|
||||
|
||||
result.append(val.substring(1));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static String string2Unicode(String string) {
|
||||
StringBuffer unicode = new StringBuffer();
|
||||
|
||||
for(int i = 0; i < string.length(); ++i) {
|
||||
char c = string.charAt(i);
|
||||
unicode.append("\\u" + Integer.toHexString(c));
|
||||
}
|
||||
|
||||
return unicode.toString();
|
||||
}
|
||||
|
||||
public static String unicode2String(String unicode) {
|
||||
StringBuffer string = new StringBuffer();
|
||||
String[] hex = unicode.split("\\\\u");
|
||||
|
||||
for(int i = 1; i < hex.length; ++i) {
|
||||
int data = Integer.parseInt(hex[i], 16);
|
||||
string.append((char)data);
|
||||
}
|
||||
|
||||
return string.toString();
|
||||
}
|
||||
|
||||
public static String lengthFix(String text, int length, char ch, boolean end) {
|
||||
if (text == null) {
|
||||
text = "";
|
||||
}
|
||||
|
||||
int tempLength = text.getBytes().length;
|
||||
if (length == tempLength) {
|
||||
return text;
|
||||
} else if (length <= tempLength) {
|
||||
return end ? new String(text.getBytes(), 0, length) : new String(text.getBytes(), tempLength - length, length);
|
||||
} else {
|
||||
char[] fix = new char[length - tempLength];
|
||||
|
||||
for(int i = 0; i < fix.length; ++i) {
|
||||
fix[i] = ch;
|
||||
}
|
||||
|
||||
StringBuffer buffer = new StringBuffer(text);
|
||||
if (end) {
|
||||
buffer = buffer.append(fix);
|
||||
} else {
|
||||
buffer = buffer.insert(0, fix);
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static String lengthFix(String text, int length, String ch, boolean end) {
|
||||
return lengthFix(text, length, ch.charAt(0), end);
|
||||
}
|
||||
|
||||
public static String bytesToHexStr(byte[] b) {
|
||||
return bytesToHexStr(b, 0, b.length);
|
||||
}
|
||||
|
||||
public static String bytesToHexStr(byte[] b, int start, int len) {
|
||||
if (start < b.length && b != null && b.length != 0) {
|
||||
StringBuffer str = new StringBuffer();
|
||||
|
||||
for(int i = start; i < start + len; ++i) {
|
||||
str.append(String.format("%02x", b[i]));
|
||||
}
|
||||
|
||||
return str.toString();
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] hexStrToBytes(String str) {
|
||||
if (str.length() % 2 != 0) {
|
||||
str = "0" + str;
|
||||
}
|
||||
|
||||
byte[] temp = new byte[str.length() / 2];
|
||||
|
||||
for(int i = 0; i < str.length(); i += 2) {
|
||||
temp[i / 2] = (byte)(Byte.parseByte(str.substring(i, i + 1), 16) * 16 + Byte.parseByte(str.substring(i + 1, i + 2), 16));
|
||||
}
|
||||
|
||||
return temp;
|
||||
}
|
||||
|
||||
public static void hexStrToBytes(String str, byte[] b, int from) {
|
||||
if (str.length() % 2 != 0) {
|
||||
str = "0" + str;
|
||||
}
|
||||
|
||||
hexStrToBytes(str, b, from, str.length() / 2);
|
||||
}
|
||||
|
||||
public static void hexStrToBytes(String str, byte[] b, int from, int length) {
|
||||
if (str.length() % 2 != 0) {
|
||||
str = "0" + str;
|
||||
}
|
||||
|
||||
for(int i = 0; i < Math.min(str.length(), length * 2) && from + i / 2 < b.length; i += 2) {
|
||||
b[from + i / 2] = (byte)(Byte.parseByte(str.substring(i, i + 1), 16) * 16 + Byte.parseByte(str.substring(i + 1, i + 2), 16));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
|
||||
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
|
||||
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
|
||||
}
|
||||
}
|
||||
@@ -32,5 +32,12 @@
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.yulichang</groupId>
|
||||
<artifactId>mybatis-plus-join</artifactId>
|
||||
<version>1.2.4</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</project>
|
||||
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.central.db.utils;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import lombok.Data;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 分页工具类
|
||||
*
|
||||
* @author lishilin
|
||||
* @date 2020/03/02
|
||||
*/
|
||||
@ToString
|
||||
@Data
|
||||
public class PageUtils implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
/**
|
||||
* 总记录数
|
||||
*/
|
||||
private int totalCount;
|
||||
/**
|
||||
* 每页记录数
|
||||
*/
|
||||
private int pageSize;
|
||||
/**
|
||||
* 总页数
|
||||
*/
|
||||
private int totalPage;
|
||||
/**
|
||||
* 当前页数
|
||||
*/
|
||||
private int currPage;
|
||||
/**
|
||||
* 列表数据
|
||||
*/
|
||||
private List<?> list;
|
||||
|
||||
/**
|
||||
* 分页
|
||||
* @param list 列表数据
|
||||
* @param totalCount 总记录数
|
||||
* @param pageSize 每页记录数
|
||||
* @param currPage 当前页数
|
||||
*/
|
||||
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
|
||||
this.list = list;
|
||||
this.totalCount = totalCount;
|
||||
this.pageSize = pageSize;
|
||||
this.currPage = currPage;
|
||||
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
|
||||
}
|
||||
|
||||
public PageUtils(){
|
||||
|
||||
}
|
||||
|
||||
public <T> PageUtils(List<T> records, int total, int size, int current, boolean format) {
|
||||
}
|
||||
|
||||
public List<?> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List<?> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页
|
||||
*/
|
||||
public PageUtils(IPage<?> page) {
|
||||
this.list = page.getRecords();
|
||||
this.totalCount = (int)page.getTotal();
|
||||
this.pageSize = (int) page.getSize();
|
||||
this.currPage = (int) page.getCurrent();
|
||||
this.totalPage = (int)page.getPages();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-commons</artifactId>
|
||||
<version>6.0.0</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>jar</packaging>
|
||||
<artifactId>zlt-iot-spring-boot-starter</artifactId>
|
||||
<description>iot通用组件</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.java-websocket</groupId>
|
||||
<artifactId>Java-WebSocket</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.hutool</groupId>
|
||||
<artifactId>hutool-all</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.zlt</groupId>
|
||||
<artifactId>zlt-common-spring-boot-starter</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.central.common.iot;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* iot 自动配置
|
||||
*
|
||||
* @author wangpeijie
|
||||
* @date 2024/11/19
|
||||
*/
|
||||
@Configuration
|
||||
class IoTConfiguration {
|
||||
|
||||
/**
|
||||
* iot v1版本配置
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Bean("iotProperties")
|
||||
@ConditionalOnProperty(name = "jetlinks.version", havingValue = "1.0")
|
||||
@ConfigurationProperties(prefix = "jetlinks.server.v1")
|
||||
public IoTProperties iotPropertiesV1() {
|
||||
return new IoTProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* iot v2版本配置
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Bean("iotProperties")
|
||||
@ConditionalOnProperty(name = "jetlinks.version", havingValue = "2.0")
|
||||
@ConfigurationProperties(prefix = "jetlinks.server.v2")
|
||||
public IoTProperties iotPropertiesV2() {
|
||||
return new IoTProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* iot 模板
|
||||
*
|
||||
* @param iotProperties
|
||||
* @return
|
||||
*/
|
||||
@Bean
|
||||
public IoTTemplate iotTemplate(@Qualifier("iotProperties") IoTProperties iotProperties) {
|
||||
return new IoTTemplate(iotProperties);
|
||||
}
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.central.common.iot;
|
||||
|
||||
/**
|
||||
* iot 异常
|
||||
*
|
||||
* @author wangpeijie
|
||||
* @date 2024/11/28
|
||||
*/
|
||||
public class IoTException extends RuntimeException {
|
||||
|
||||
public IoTException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package com.central.common.iot;
|
||||
|
||||
import lombok.Setter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
/**
|
||||
* iot 配置
|
||||
*
|
||||
* @author wangpeijie
|
||||
* @date 2024/11/19
|
||||
*/
|
||||
@Setter
|
||||
public class IoTProperties {
|
||||
|
||||
@Value("${jetlinks.version}")
|
||||
private String version;
|
||||
|
||||
@Value("${jetlinks.clientId}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${jetlinks.secureKey}")
|
||||
private String secureKey;
|
||||
|
||||
@Value("${jetlinks.dockProductIds:}")
|
||||
private String dockProductIds;
|
||||
|
||||
@Value("${jetlinks.droneProductIds:}")
|
||||
private String droneProductIds;
|
||||
|
||||
private String deviceInfoQueryUrl = "/device-instance/_query";
|
||||
|
||||
private String url;
|
||||
|
||||
private String ws;
|
||||
|
||||
private String mqtt;
|
||||
|
||||
/**
|
||||
* 获取iot平台token
|
||||
*/
|
||||
private String queryToken;
|
||||
|
||||
/**
|
||||
* hushi->iot执行任务指令
|
||||
*/
|
||||
private String execMissionUrl;
|
||||
|
||||
/**
|
||||
* mgnt -> iot 添加设备
|
||||
*/
|
||||
private String saveDeviceUrl;
|
||||
|
||||
/**
|
||||
* mgnt -> iot 激活设备
|
||||
*/
|
||||
private String activeDeviceUrl;
|
||||
|
||||
/**
|
||||
* hushi查询产品
|
||||
*/
|
||||
private String productQueryUrl;
|
||||
|
||||
/**
|
||||
* hushi查询固件历史
|
||||
*/
|
||||
private String upgradeHistoryUrl;
|
||||
|
||||
/**
|
||||
* 查询固件
|
||||
*/
|
||||
private String firmwareQueryUrl;
|
||||
|
||||
/**
|
||||
* 固件升级任务
|
||||
*/
|
||||
private String firmwareUpgradeTaskStartUrl;
|
||||
|
||||
/**
|
||||
* 查询设备日志
|
||||
*/
|
||||
private String deviceLogUrl;
|
||||
|
||||
/**
|
||||
* 查询设备所有属性
|
||||
*/
|
||||
private String propertiesQueryUrl;
|
||||
|
||||
/**
|
||||
* 查询设备所有属性
|
||||
*/
|
||||
private String propertyQueryUrl;
|
||||
|
||||
/**
|
||||
* 查询单个设备最新的全部属性
|
||||
*/
|
||||
private String propertyLatest;
|
||||
|
||||
public String getDockProductIds() {
|
||||
return dockProductIds;
|
||||
}
|
||||
|
||||
public String getDroneProductIds() {
|
||||
return droneProductIds;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return this.version;
|
||||
}
|
||||
|
||||
public String getClientId() {
|
||||
return this.clientId;
|
||||
}
|
||||
|
||||
public String getSecureKey() {
|
||||
return this.secureKey;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return this.url;
|
||||
}
|
||||
|
||||
public String getWsUrl() {
|
||||
return this.ws;
|
||||
}
|
||||
|
||||
public String getMqttUrl() {
|
||||
return this.mqtt;
|
||||
}
|
||||
|
||||
public String getQueryTokenUrl() {
|
||||
return this.url + this.queryToken;
|
||||
}
|
||||
|
||||
public String getExecMissionUrl() {
|
||||
return this.url + this.execMissionUrl;
|
||||
}
|
||||
|
||||
public String getSaveDeviceUrl() {
|
||||
return this.url + this.saveDeviceUrl;
|
||||
}
|
||||
|
||||
public String getActiveDeviceUrl() {
|
||||
return this.url + this.activeDeviceUrl;
|
||||
}
|
||||
|
||||
public String getProductQueryUrl() {
|
||||
return this.url + this.productQueryUrl;
|
||||
}
|
||||
|
||||
public String getUpgradeHistoryUrl() {
|
||||
return this.url + this.upgradeHistoryUrl;
|
||||
}
|
||||
|
||||
public String getFirmwareQueryUrl() {
|
||||
return this.url + this.firmwareQueryUrl;
|
||||
}
|
||||
|
||||
public String getFirmwareUpgradeTaskStartUrl() {
|
||||
return this.url + this.firmwareUpgradeTaskStartUrl;
|
||||
}
|
||||
|
||||
public String getDeviceLogUrl() {
|
||||
return this.url + this.deviceLogUrl;
|
||||
}
|
||||
|
||||
public String getPropertiesQueryUrl() {
|
||||
return this.url + this.propertiesQueryUrl;
|
||||
}
|
||||
|
||||
public String getPropertyQueryUrl() {
|
||||
return this.url + this.propertyQueryUrl;
|
||||
}
|
||||
|
||||
public String getPropertyLatestUrl() {
|
||||
return this.url + this.propertyLatest;
|
||||
}
|
||||
|
||||
public String getDeviceInfoQueryUrl() {
|
||||
return this.url + this.deviceInfoQueryUrl;
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package com.central.common.iot;
|
||||
|
||||
import cn.hutool.core.util.HexUtil;
|
||||
import cn.hutool.crypto.digest.DigestAlgorithm;
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import cn.hutool.http.HttpRequest;
|
||||
import cn.hutool.http.HttpResponse;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* IoT Template
|
||||
*
|
||||
* @author wangpeijie
|
||||
* @date 2024/11/20
|
||||
*/
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class IoTTemplate {
|
||||
|
||||
private final IoTProperties iotProperties;
|
||||
|
||||
/**
|
||||
* 查询token
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String queryToken() {
|
||||
String queryTokenUrl = iotProperties.getQueryTokenUrl();
|
||||
Map<String, Object> param = new HashMap<>(2);
|
||||
param.put("expires", 7200 * 24);
|
||||
return this.execute(queryTokenUrl, param);
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回报文结构
|
||||
* {
|
||||
* "total": 865,
|
||||
* "data": [
|
||||
* {
|
||||
* "formatValue": "DNS1MINIPT23160061",
|
||||
* "propertyName": "设备ID",
|
||||
* "createTime": 1735095082942,
|
||||
* "property": "deviceId",
|
||||
* "id": "eZP7ud--Szm9VElG6y3BvT76MNySv3ZC",
|
||||
* "type": "string",
|
||||
* "deviceId": "DNS1MINIPT23160061",
|
||||
* "value": "DNS1MINIPT23160061",
|
||||
* "originValue": "DNS1MINIPT23160061",
|
||||
* "timestamp": 1735095082940
|
||||
* }
|
||||
* ],
|
||||
* "pageIndex": 0,
|
||||
* "pageSize": 1
|
||||
* }
|
||||
* 单个属性查询
|
||||
*
|
||||
* @param deviceSn 设备SN
|
||||
* @param property 属性
|
||||
* @return
|
||||
*/
|
||||
public String queryProperty(String deviceSn, String property) {
|
||||
String url = iotProperties.getPropertyQueryUrl();
|
||||
url = url.replace("{deviceId}", deviceSn).replace("{property}", property);
|
||||
Map<String, Object> params = new HashMap<>(5);
|
||||
params.put("pageSize", 1);
|
||||
params.put("pageIndex", 0);
|
||||
List<Map<String, Object>> list = new ArrayList<>();
|
||||
Map<String, Object> termParam = new HashMap<>(5);
|
||||
termParam.put("column", "property");
|
||||
termParam.put("value", property);
|
||||
list.add(termParam);
|
||||
params.put("terms", list);
|
||||
return this.execute(url, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单个属性值查询
|
||||
*
|
||||
* @param deviceSn 设备SN
|
||||
* @param property 属性
|
||||
* @return
|
||||
*/
|
||||
public String queryPropertyValue(String deviceSn, String property) {
|
||||
String result = this.queryProperty(deviceSn, property);
|
||||
JSONObject resultObject = JSON.parseObject(result);
|
||||
JSONArray dataArray = resultObject.getJSONArray("data");
|
||||
if (dataArray != null && !dataArray.isEmpty()) {
|
||||
JSONObject jsonObject = dataArray.getJSONObject(0);
|
||||
return jsonObject.getString("value");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* iot 核心请求方法,JSON报文体
|
||||
*
|
||||
* @param url 请求地址
|
||||
* @param param 报文参数
|
||||
* @return
|
||||
*/
|
||||
public String execute(String url, Map<String, Object> param) {
|
||||
String body = JSON.toJSONString(param);
|
||||
return this.execute(url, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* iot 核心请求方法,字符串报文体
|
||||
*
|
||||
* @param url 请求地址
|
||||
* @param body 报文体
|
||||
* @return
|
||||
*/
|
||||
public String execute(String url, String body) {
|
||||
//时间戳
|
||||
String xTimestamp = String.valueOf(System.currentTimeMillis());
|
||||
//param+X-Timestamp+SecureKey通过MD5加密
|
||||
MessageDigest digest = DigestUtil.digester(DigestAlgorithm.MD5).getDigest();
|
||||
digest.update(body.getBytes());
|
||||
digest.update(xTimestamp.getBytes());
|
||||
digest.update(iotProperties.getSecureKey().getBytes());
|
||||
|
||||
Map<String, String> headers = new HashMap<>(5);
|
||||
headers.put("X-Sign", HexUtil.encodeHexStr(digest.digest()));
|
||||
headers.put("X-Client-Id", iotProperties.getClientId());
|
||||
headers.put("X-Timestamp", xTimestamp);
|
||||
|
||||
HttpRequest httpRequest = HttpUtil.createPost(url);
|
||||
httpRequest.addHeaders(headers);
|
||||
httpRequest.body(body);
|
||||
String result = null;
|
||||
try (HttpResponse httpResponse = httpRequest.execute()) {
|
||||
result = new String(httpResponse.bodyBytes(), StandardCharsets.UTF_8);
|
||||
log.info("IoTTemplate请求地址:{},请求头:{}, 请求参数:{},响应结果:{}", url, headers, body, result);
|
||||
} catch (Exception e) {
|
||||
log.error("IoTTemplate请求地址:{},请求头:{}, 请求参数:{}", url, headers, body, e);
|
||||
}
|
||||
JSONObject jsonObject = JSON.parseObject(result);
|
||||
if (jsonObject != null && Objects.equals(jsonObject.getInteger("status"), 200)) {
|
||||
return jsonObject.getString("result");
|
||||
}
|
||||
throw new IoTException(StringUtils.defaultIfBlank(jsonObject.getString("message"), "IoTTemplate请求异常"));
|
||||
}
|
||||
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
package com.central.common.iot;
|
||||
|
||||
import cn.hutool.core.thread.ThreadUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.java_websocket.client.WebSocketClient;
|
||||
import org.java_websocket.handshake.ServerHandshake;
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* iot websocket 客户端
|
||||
*
|
||||
* @author wangpeijie
|
||||
* @date 2024/11/20
|
||||
*/
|
||||
@Slf4j
|
||||
public class IoTWebSocketClient implements BeanNameAware, InitializingBean, DisposableBean {
|
||||
|
||||
private String beanName;
|
||||
|
||||
/**
|
||||
* 尝试重连标识
|
||||
*/
|
||||
private final AtomicBoolean tryReconnect = new AtomicBoolean(false);
|
||||
|
||||
/**
|
||||
* 需要ping标识
|
||||
*/
|
||||
private final AtomicBoolean needPing = new AtomicBoolean(true);
|
||||
|
||||
/**
|
||||
* 连接结束标识
|
||||
*/
|
||||
private final AtomicBoolean end = new AtomicBoolean(false);
|
||||
|
||||
/**
|
||||
* 重连次数
|
||||
*/
|
||||
private AtomicInteger reConnectTimes = new AtomicInteger(0);
|
||||
|
||||
/**
|
||||
* iot 消息处理器
|
||||
*/
|
||||
private final IoTWebSocketHandler iotWebSocketHandler;
|
||||
|
||||
private WebSocketClient webSocketClient;
|
||||
|
||||
@Autowired
|
||||
private IoTProperties iotProperties;
|
||||
|
||||
@Autowired
|
||||
private IoTTemplate iotTemplate;
|
||||
|
||||
public IoTWebSocketClient(IoTWebSocketHandler iotWebSocketHandler) {
|
||||
this.iotWebSocketHandler = iotWebSocketHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置bean名称
|
||||
*
|
||||
* @param beanName
|
||||
*/
|
||||
@Override
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
connect();
|
||||
circlePing();
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接
|
||||
*/
|
||||
private void connect() throws Exception {
|
||||
String token = null;
|
||||
for (int i = 0; i < 3; i++) {
|
||||
token = iotTemplate.queryToken();
|
||||
if (StrUtil.isNotBlank(token)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (StringUtils.isBlank(token)) {
|
||||
log.warn("iot token 获取失败...");
|
||||
return;
|
||||
}
|
||||
String url = iotProperties.getWsUrl() + token;
|
||||
webSocketClient = new WebSocketClient(new URI(url)) {
|
||||
@Override
|
||||
public void onOpen(ServerHandshake serverHandshake) {
|
||||
log.info("[{}]IoTWebSocketClient [onOpen]连接成功{}", beanName, getRemoteSocketAddress());
|
||||
tryReconnect.set(false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(String message) {
|
||||
if (StringUtils.isEmpty(message)) {
|
||||
return;
|
||||
}
|
||||
if (message.contains("{\"type\":\"pong\"}")) {
|
||||
return;
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("[{}]IoTWebSocketClient [onMessage]接收到消息{}", beanName, message);
|
||||
}
|
||||
JSONObject jsonObject = JSON.parseObject(message);
|
||||
if (jsonObject == null || StringUtils.isBlank(jsonObject.getString("topic"))) {
|
||||
return;
|
||||
}
|
||||
JSONObject payload = jsonObject.getJSONObject("payload");
|
||||
try {
|
||||
iotWebSocketHandler.onMessage(payload);
|
||||
} catch (Exception e) {
|
||||
log.error("[{}]IoTWebSocketClient [onMessage]处理消息异常", beanName, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason, boolean remote) {
|
||||
log.info("[{}]IoTWebSocketClient [onClose]关闭,code={},reason={},remote={}", beanName, code, reason, remote);
|
||||
if (StrUtil.hasBlank(reason) || reason.contains("https")) {
|
||||
if (end.get()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
IoTWebSocketClient.this.reconnect();
|
||||
} catch (Exception e) {
|
||||
log.error("[{}]IoTWebSocketClient [onClose]重连失败", beanName, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception e) {
|
||||
log.info("[{}]IoTWebSocketClient [onError]异常", beanName, e);
|
||||
try {
|
||||
IoTWebSocketClient.this.reconnect();
|
||||
} catch (Exception exception) {
|
||||
log.info("[{}]IoTWebSocketClient [onError]重连失败", beanName, exception);
|
||||
}
|
||||
}
|
||||
};
|
||||
webSocketClient.connectBlocking(10, TimeUnit.SECONDS);
|
||||
iotWebSocketHandler.onConnect(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重连
|
||||
*/
|
||||
private void reconnect() throws Exception {
|
||||
ThreadUtil.sleep(10, TimeUnit.SECONDS);
|
||||
int cul = reConnectTimes.incrementAndGet();
|
||||
if (end.get()) {
|
||||
log.info("已确认关闭连接");
|
||||
return;
|
||||
}
|
||||
log.warn("[{}]第[{}]次断开重连", beanName, cul);
|
||||
if (tryReconnect.get()) {
|
||||
log.error("[{}]第[{}]次断开重连结果 -> 连接正在重连,本次重连请求放弃", beanName, cul);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
tryReconnect.set(true);
|
||||
if (webSocketClient.isOpen()) {
|
||||
log.warn("[{}]第[{}]次断开重连,关闭旧连接", beanName, cul);
|
||||
webSocketClient.closeConnection(2, "reconnect stop");
|
||||
}
|
||||
webSocketClient = null;
|
||||
connect();
|
||||
reConnectTimes = new AtomicInteger(0);
|
||||
} catch (Exception e) {
|
||||
log.error("[{}]第[{}]次断开重连结果 -> 连接正在重连", beanName, cul, e);
|
||||
reconnect();
|
||||
} finally {
|
||||
tryReconnect.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 心跳
|
||||
*/
|
||||
public void circlePing() {
|
||||
new Thread(
|
||||
() -> {
|
||||
while (needPing.get()) {
|
||||
if (webSocketClient.isOpen()) {
|
||||
String ping = "{\"type\":\"ping\"}";
|
||||
webSocketClient.send(ping);
|
||||
}
|
||||
ThreadUtil.sleep(5, TimeUnit.SECONDS);
|
||||
}
|
||||
log.warn("[{}]Ping循环关闭", beanName);
|
||||
})
|
||||
.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁
|
||||
*/
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
needPing.set(false);
|
||||
end.set(true);
|
||||
if (webSocketClient != null) {
|
||||
try {
|
||||
webSocketClient.closeConnection(3, "real stop");
|
||||
} catch (Exception e) {
|
||||
log.error("[{}]IoTWebSocketClient 关闭失败", beanName, e);
|
||||
}
|
||||
try {
|
||||
webSocketClient.close();
|
||||
} catch (Exception e) {
|
||||
log.error("[{}]IoTWebSocketClient 关闭失败", beanName, e);
|
||||
}
|
||||
reConnectTimes = new AtomicInteger(0);
|
||||
webSocketClient = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
public void send(String message) {
|
||||
if (webSocketClient.isOpen()) {
|
||||
webSocketClient.send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.central.common.iot;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
/**
|
||||
* IoT WebSocket 处理器
|
||||
*
|
||||
* @author wangpeijie
|
||||
* @date 2024/11/20
|
||||
*/
|
||||
public interface IoTWebSocketHandler {
|
||||
|
||||
/**
|
||||
* 连接成功
|
||||
*
|
||||
* @param webSocketClient
|
||||
*/
|
||||
default void onConnect(IoTWebSocketClient webSocketClient) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理消息
|
||||
*
|
||||
* @param message
|
||||
*/
|
||||
void onMessage(JSONObject message);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.central.common.iot.IoTConfiguration
|
||||
Reference in New Issue
Block a user