zouyu
8 天以前 09394848ce262aff81897503d32ec334fd3f2b6f
src/main/java/com/ruoyi/tide/utils/TideUtils.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,191 @@
package com.ruoyi.tide.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.HMac;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
@Data
@Component
@Slf4j
public class TideUtils {
    public static String APP_ID;
    public static String APP_SECRET;
    @Value("${inspur.appId}")
    private String appId;
    @Value("${inspur.appSecret}")
    private String appSecret;
    @Value("${inspur.appId}")
    public void setAppId(String appId) {
        TideUtils.APP_ID = appId;
    }
    @Value("${inspur.appSecret}")
    public void setAppSecret(String appSecret) {
        TideUtils.APP_SECRET = appSecret;
    }
    // å†…网地址
    private final static String ip = "http://10.136.0.8:8083";
    // MD5加密并转换为16进制
    public static String md5Encryption(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    // get请求
    public static HashMap<String, String> getGetHeader(String parameter) {
        // æ—¶é—´æˆ³
        String xTime = String.valueOf(DateUtil.current());
        // èŽ·å–éšæœº16位字符串
        String xRandom = RandomUtil.randomString(16);
        String xSignSplicingTogether;
        // æœ‰å‚æ•°
        if (ObjectUtils.isNotEmpty(parameter)) {
            // åŠ å¯†å¾—å‡ºx-body
            String xBody = md5Encryption(parameter);
            // ä¸ºx-sign加密做拼接
            xSignSplicingTogether = "x-body=" + xBody + "&x-random=" + xRandom + "&x-time=" + xTime;
        // æ— å‚æ•°
        } else {
            xSignSplicingTogether = "x-random=" + xRandom + "&x-time=" + xTime;
        }
        // é…ç½®åŠ å¯†æ–¹å¼ä¸Žå¯†é’¥
        HMac hMac = new HMac(HmacAlgorithm.HmacSHA256, APP_SECRET.getBytes());
        // å¾—出x-sign
        String xSign = hMac.digestHex(xSignSplicingTogether);
        HashMap<String, String> result = new HashMap<>();
        result.put("x-time", xTime);
        result.put("x-random", xRandom);
        result.put("x-sign", xSign);
        result.put("appKey", APP_ID);
        return result;
    }
    // post请求
    public static HashMap<String, String> getPostHeader(String parameter) {
        // æ—¶é—´æˆ³
        String xTime = String.valueOf(DateUtil.current());
        // èŽ·å–éšæœº16位字符串
        String xRandom = RandomUtil.randomString(16);
        String xSignSplicingTogether;
        // æœ‰å‚æ•°
        if (ObjectUtils.isNotEmpty(parameter)) {
            // åŠ å¯†å¾—å‡ºx-body
            String xBody = md5Encryption(parameter);
            // ä¸ºx-sign加密做拼接
            xSignSplicingTogether = "x-body=" + xBody + "&x-random=" + xRandom + "&x-time=" + xTime;
            // æ— å‚æ•°
        } else {
            xSignSplicingTogether = "x-random=" + xRandom + "&x-time=" + xTime;
        }
        // x-sign åР坆
        HMac hMac = new HMac(HmacAlgorithm.HmacSHA256, APP_SECRET.getBytes());
        String xSign = hMac.digestHex(xSignSplicingTogether);
        HashMap<String, String> result = new HashMap<>();
        result.put("x-time", xTime);
        result.put("x-random", xRandom);
        result.put("x-sign", xSign);
        result.put("appKey", APP_ID);
        return result;
    }
    /**
     * äº”分钟一次的心跳
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public static void heartbeat(){
        HashMap<String, String> header = getGetHeader(null);
        String url = ip + "/cpn/api/extra/v1/application/heartbeat";
        String body = HttpRequest.get(url).headerMap(header, false).execute().body();
        System.out.println(body + "应用心跳执行成功!");
    }
    // èŽ·å–token
    public static String getToken(String code) {
        String url = ip + "/cpn/extral/applicationCode/appAuthCheck";
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("appID", APP_ID);
        json.put("appSecret", APP_SECRET);
        HashMap<String, String> header = getPostHeader(json.toString());
        String body = HttpRequest.post(url)
                .headerMap(header, false)
                .body(json.toString())
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        return jsonObject.get("data").toString();
    }
    // èŽ·å–ç”¨æˆ·ä¿¡æ¯
    public static JSONObject getUserInfo(String token) {
        String url = ip + "/cpn/api/extral/applicationCode/getUserInfoByToken";
        JSONObject json = new JSONObject();
        json.put("appID", APP_ID);
        HashMap<String, String> header = getPostHeader(json.toString());
        header.put("Authorization", token);
        String body = HttpRequest.post(url)
                .headerMap(header, false)
                .body(json.toString())
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        return JSONObject.parseObject(jsonObject.get("data").toString());
    }
    public static JSONObject getResult(Integer code, String msg, Object data) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        json.put("data", data);
        String xRandom = RandomUtil.randomString(16);
        json.put("traceId", xRandom);
        return json;
    }
    public static String getRandomString(int length) {
        SecureRandom random = new SecureRandom();
        String uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String specialCharacters = "!@$%^&*()_+-=.";
        String characterSet = uppercaseLetters + lowercaseLetters + numbers + specialCharacters;
        StringBuilder passwordBuilder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(characterSet.length());
            char randomChar = characterSet.charAt(randomIndex);
            passwordBuilder.append(randomChar);
        }
        return passwordBuilder.toString();
    }
}