shichongfu
2023-04-25 ce0b49552668d3331055e2b1a1447a743dc54939
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package com.product.admin.service;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldMetaEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.SQLEntity;
import com.product.core.exception.BaseException;
 
import java.io.IOException;
import java.util.*;
 
import com.product.core.spring.context.SpringMVCContextHolder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.product.core.service.support.AbstractBaseService;
import com.product.util.BaseUtil;
import com.product.admin.config.CmnConst;
import com.product.admin.config.SystemCode;
 
/**
 * Copyright © 2020 LX-BASE
 *
 * @Title: LX-BASE-SERVER
 * @Project: base-server-admin
 * @Date: 2020年11月20日
 * @Author: Mr.Xu
 * @Description:公共汇率
 */
@Component
public class SystemExchangeRateService extends AbstractBaseService {
 
    @Autowired
    private BaseDao dao;
 
 
    /**
     * 更新所有汇率
     *
     * @return
     * @throws BaseException
     */
    public boolean updateCurrencyRate() throws BaseException {
        List<String> currencyCodes = getCurrencyCodes();
        return dao.add(getCurrencyRates(currencyCodes));
    }
 
    /**
     * 获取所有启用货币code
     *
     * @throws BaseException
     */
    public List<String> getCurrencyCodes() throws BaseException {
        SQLEntity sqlEntity = new SQLEntity();
        sqlEntity.setTableNames(CmnConst.PRODUCT_COMMON_CURRENCY);
        sqlEntity.setFilter("is_used=1");
        DataTableEntity dt = dao.listTable(sqlEntity);
        if (!BaseUtil.dataTableIsEmpty(dt)) {
            List<String> currencyCodes = new ArrayList<>();
            for (int i = 0; i < dt.getRows(); i++) {
                currencyCodes.add(dt.getString(i, "currency_code"));
            }
            return currencyCodes;
        }
        return Collections.emptyList();
    }
 
    /**
     * 获取指定货币汇率
     *
     * @param originalCurrency 原货币
     * @param foreignCurrencys 兑换后货币 集合多个用逗号分隔
     * @return
     * @throws BaseException
     */
    public DataTableEntity getAssignCurrencyRate(String originalCurrency, String foreignCurrencys)
            throws BaseException {
        Map<String, Object> map = new HashMap<>();
        map.put("base", originalCurrency);
        map.put("symbols", foreignCurrencys);
        String url = BaseUtil.urlParamsJoin(CmnConst.RATE_API_URL, map);
        if (BaseUtil.strIsNull(url)) {
            return null;
        }
        JSONObject sendRequest = sendRequest(url, null, 0, 0);
        String errorKey = "error";
        String saveRateKey = "getAssignCurrencyRate(String originalCurrency, String foreignCurrencys)";
        if (sendRequest == null || sendRequest.isEmpty()) {
            throw new BaseException(SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getValue(),
                    SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getText() , this.getClass(),
                    saveRateKey);
        }
        if (!BaseUtil.strIsNull(sendRequest.getString(errorKey))) {
            throw new BaseException(SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getValue(),
                    SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getText() + "," + sendRequest.getString(errorKey), this.getClass(),
                    saveRateKey);
        }
        return paramsJoinToDataTable(sendRequest);
    }
 
    /**
     * 获取汇率
     *
     * @param currencyCodes 汇率code 集合
     * @return
     * @throws BaseException
     */
    public DataTableEntity getCurrencyRates(List<String> currencyCodes) throws BaseException {
 
        if (currencyCodes == null) {
            return null;
        }
        DataTableEntity result = null;
        for (int i = 0; i < currencyCodes.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            List<String> currencyCodes2 = new ArrayList<>();
            currencyCodes2.addAll(currencyCodes);
            currencyCodes2.remove(currencyCodes2.get(i));
            map.put("base", currencyCodes.get(i));
            map.put("symbols", Joiner.on(",").join(currencyCodes2));
            String url = BaseUtil.urlParamsJoin(CmnConst.RATE_API_URL, map);
            if (BaseUtil.strIsNull(url)) {
                continue;
            }
            JSONObject sendRequest = sendRequest(url, null, 0, 0);
            String error = null;
            if (sendRequest != null) {
                sendRequest.getString("error");
            }
            if (sendRequest == null || !BaseUtil.strIsNull(error)) {
                throw new BaseException(SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getValue(),
                        SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getText() + "," + error, this.getClass(),
                        "getCurrencyRates(List<String> currencyCodes) throws BaseException");
            }
            sendRequest.put("url", url);
            DataTableEntity saveRate = paramsJoinToDataTable(sendRequest);
            if (result == null) {
                result = saveRate;
            } else {
                result = BaseUtil.dataTableMerge(result, saveRate);
            }
        }
        return result;
    }
 
    /**
     * 第三方参数拼接成dataTable
     *
     * @param json
     * @return
     */
 
    public DataTableEntity paramsJoinToDataTable(JSONArray array) throws BaseException {
        if (array == null) { // 第三方接口返回信息为空
            throw new BaseException(SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getValue(),
                    SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getText(), this.getClass(), "saveRate");
        }
        DataTableEntity result = null;
        for (int i = 0; i < array.size(); i++) {
            DataTableEntity saveRate = paramsJoinToDataTable(array.getJSONObject(i));
            if (result == null) {
                result = saveRate;
            } else {
                result = BaseUtil.dataTableMerge(result, saveRate);
            }
        }
        return result;
    }
 
    /**
     * 第三方参数拼接成dataTable
     *
     * @param json
     * @return
     */
 
    public DataTableEntity paramsJoinToDataTable(JSONObject json) throws BaseException {
        if (json == null || json.getJSONObject("rates") == null) { // 第三方接口返回信息为空
            throw new BaseException(SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getValue(),
                    SystemCode.SYSTEM_GAIN_CURRENCY_RATE_PARAM_EMPTY_FIAL.getText(), this.getClass(), "saveRate");
        }
        DataTableEntity dt = new DataTableEntity();
        String base = json.getString("base");
 
        String date = json.getString("date");
        JSONObject resultJson = json.getJSONObject("rates");
        for (String currencyCode : resultJson.keySet()) {
            FieldSetEntity fs = new FieldSetEntity();
            FieldMetaEntity metaEntity = new FieldMetaEntity();
            metaEntity.setTableName(new Object[]{CmnConst.PRODUCT_COMMON_FOREIGN_EXCHANGE_RATE});
            fs.setMeta(metaEntity);
            fs.setValue("foreign_currency_uuid", currencyCode);
            fs.setValue("exchanged_utc_datetime", date);
            fs.setValue("exchange_time_zone", 0);
            fs.setValue("original_currency_uuid", base);
            fs.setValue("exchange_rate", resultJson.getString(currencyCode));
            BaseUtil.createCreatorAndCreationTime(null, fs);
            fs.setValue(CmnConst.CREATED_BY, "1");
            dt.addFieldSetEntity(fs);
        }
        return dt;
    }
 
    /**
     * 发送http 请求获取数据
     *
     * @param url
     * @param token
     * @param socketTimeout
     * @param connectTimeout
     * @return
     */
    private JSONObject sendRequest(String url, String token, int socketTimeout, int connectTimeout) {
        if (token == null) {
            token = "";
        }
        HttpGet request = new HttpGet(url);
        if (socketTimeout <= 0) {
            socketTimeout = 6000;
        }
        if (connectTimeout <= 0) {
            connectTimeout = 6000;
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                .setConnectTimeout(connectTimeout).build();
        request.setConfig(requestConfig);
        request.setHeader("Authorization", token);
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            CloseableHttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                return JSON.parseObject(strResult);
            }
        } catch (IOException e) {
            throw new BaseException(e);
        } finally {
            request.releaseConnection();
        }
        return null;
    }
 
}