沙钢智慧能源系统后端代码
dongyukun
5 天以前 a3bb1815c3eb6b0f0cfe9d9d2ba5ee48279e26ed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package com.iailab.module.shasteel.job.task;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iailab.framework.common.util.http.HttpUtils;
import com.iailab.module.model.api.mcs.McsApi;
import com.iailab.module.model.api.mcs.dto.ElectricityPriceSegmentedDTO;
import com.iailab.module.shasteel.job.vo.RequestAccessTokenVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
 
/**
 * 同步分段数据定时任务
 * @author Jay
 */
@Component("syncSegmentedDataTask")
public class SyncSegmentedDataTask implements ITask {
    private Logger logger = LoggerFactory.getLogger(getClass());
 
    @Autowired
    private McsApi mcsApi;
 
    @Autowired
    private RabbitTemplate rabbitTemplate;
 
    private static final String PUBLIC_KEY_URL = "http://10.88.7.107:8081/api/api/services/Runtime/Authentication/GetLoginRSAPublicKeyAsync";
 
    private static final String ACCESS_TOKEN_URL = "http://10.88.7.107:8081/EP.Web/account/ajaxLogin";
 
    private static final String QUERY_SEGMENTED_DATA_URL = "http://10.88.7.107:8081/SG.Web/api/services/nYJK/DiagnosticsSg/QuerySegmentedDataAsync";
 
    private static final String USERNAME = "Mx001@sgis";
 
    private static final String PASSWORD = "123456";
 
    @Override
    public void run(String params) {
        logger.info("syncSegmentedDataTask定时任务正在执行,参数为:{}", params);
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            //获取 公钥
            String publicKeyKey = getPublicKey();
            // 组合密码
            Instant instant = Instant.now(); // 获取当前时间的UTC时间
            ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("Z"));
            DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
            String isoString = zonedDateTime.format(formatter);
            String password = isoString + "|" + PASSWORD;
            RequestAccessTokenVO requestAccessToken = new RequestAccessTokenVO();
            requestAccessToken.setUserName(USERNAME);
            // 使用公钥和组合后的密码进行密码加密
            String realPassword = encryptWithPublicKey(publicKeyKey, password);
            logger.info("公钥和组合后的密码进行密码加密:" + realPassword);
            requestAccessToken.setPassword(realPassword);
            requestAccessToken.setSource(1);
            //获取 token
            String accessToken = "Bearer " + getAccessToken(requestAccessToken);
            //获取保存后的数据
            List<ElectricityPriceSegmentedDTO> list = getElectricityPriceSegmentedList(accessToken);
            logger.info("开始保存数据:" + JSON.toJSONString(list));
            mcsApi.createElectricityPrice(list);
            logger.info("保存数据完成");
        } catch (Exception ex) {
            logger.error("syncSegmentedDataTask运行异常:" + ex.getMessage());
            ex.printStackTrace();
        }
        logger.info("syncSegmentedDataTask运行完成");
    }
 
    public String getPublicKey() {
        String publicKeyString = "";
        String resp =  HttpUtils.sendGet(PUBLIC_KEY_URL,null,"");
        logger.info("获取公钥的返回值:" + resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        if (jsonObject.get("status").equals(200)) {
            publicKeyString = jsonObject.getJSONObject("data").getString("pemPublicKey");
        }
        return publicKeyString.replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", "");
    }
 
    public String getAccessToken(RequestAccessTokenVO requestAccessToken) {
        String accessToken = "";
        logger.info("请求参数:" + JSON.toJSONString(requestAccessToken));
        String resp = HttpUtils.sendPost(ACCESS_TOKEN_URL, JSON.toJSONString(requestAccessToken));
        logger.info("获取token的返回值:" + resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        if (jsonObject.get("status").equals(200)) {
            String token = jsonObject.getJSONObject("data").getString("token");
            JSONObject tokenObject = JSON.parseObject(token);
            accessToken = tokenObject.getString("accessToken");
            logger.info("获取到accessToken:" + accessToken);
        }
        return accessToken;
    }
 
    public List<ElectricityPriceSegmentedDTO> getElectricityPriceSegmentedList(String accessToken){
        logger.info("accessToken: " + accessToken);
        Map<String, String> paramsMap = new HashMap<>();
        LocalDate date = LocalDate.now();  // 获取当前日期的LocalDate实例
        String year = String.valueOf(date.getYear());
        paramsMap.put("clock", year);
        logger.info("请求参数:" + JSON.toJSONString(paramsMap));
        String resp = HttpUtils.sendPostToken(QUERY_SEGMENTED_DATA_URL, JSON.toJSONString(paramsMap), accessToken);
        logger.info("获取分段数据的返回值:" + resp);
        JSONObject jsonObject = JSON.parseObject(resp);
        List<ElectricityPriceSegmentedDTO> list = jsonObject.getJSONArray("data").toJavaList(ElectricityPriceSegmentedDTO.class);
        list.forEach(item -> item.setYear(year));
        return list;
    }
 
    public static String encryptWithPublicKey(String publicKeyString, String data) throws Exception {
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString)));
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
    }
 
}