wuxw
2024-01-09 5c0f842e318250eb1ad6d1a6905c7377cbf0e24a
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package com.java110.core.factory;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.context.Environment;
import com.java110.core.context.IPageData;
import com.java110.core.context.PageData;
import com.java110.core.log.LoggerFactory;
import com.java110.dto.app.AppDto;
import com.java110.utils.constant.CommonConstant;
import com.java110.utils.exception.SMOException;
import com.java110.utils.factory.ApplicationContextFactory;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.DateUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
 
import java.util.List;
import java.util.Map;
 
public class CallApiServiceFactory {
 
    private static final String URL_API = "http://api-service/api/";
    private static final String URL_BOOT_API = "http://127.0.0.1:8008/api/";
    //日志
    private static Logger logger = LoggerFactory.getLogger(CallApiServiceFactory.class);
 
    @Autowired
    private RestTemplate restTemplate;
 
 
    /**
     * 查询
     *
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    public static <T> T getForApi(String appId, T param, String serviceCode, Class<T> t) {
 
        IPageData pd = PageData.newInstance().builder("-1", "未知", "", "", "", "", "", "", appId);
 
        List<T> list = getForApis(pd, param, serviceCode, t);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
 
    /**
     * 查询
     *
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    public static <T> T getForApi(String appId, T param, String serviceCode, Class<T> t,String userId) {
 
        IPageData pd = PageData.newInstance().builder(userId, "未知", "", "", "", "", "", "", appId);
 
        List<T> list = getForApis(pd, param, serviceCode, t);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
 
    /**
     * 查询
     *
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    public static <T> T postForApi(String appId, T param, String serviceCode, Class<T> t, String userId) {
 
        IPageData pd = PageData.newInstance().builder(userId, "未知", "", "", "", "", "", "", appId);
 
        List<T> ts = postForApis(pd, param, serviceCode, t);
 
        if (ts == null || ts.size() < 1) {
            return null;
        }
 
        return ts.get(0);
    }
 
 
    /**
     * 查询
     *
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    public static <T> T postForApi(String appId, T param, String serviceCode, Class<T> t) {
 
        return postForApi(appId, param, serviceCode, t, "-1");
    }
 
 
    /**
     * 查询
     *
     * @param pd          页面对象
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    public static <T> T getForApi(IPageData pd, T param, String serviceCode, Class<T> t) {
 
        List<T> list = getForApis(pd, param, serviceCode, t);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
 
    /**
     * 查询
     *
     * @param pd          页面对象
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    protected <T> T postForApi(IPageData pd, T param, String serviceCode, Class<T> t) {
        List<T> ts = postForApis(pd, param, serviceCode, t);
 
        if (ts == null || ts.size() < 1) {
            return null;
        }
 
        return ts.get(0);
    }
 
    /**
     * 查询
     *
     * @param pd          页面对象
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    protected static <T> List<T> postForApis(IPageData pd, T param, String serviceCode, Class<T> t) {
 
        String url = URL_API + serviceCode;
        RestTemplate restTemplate = ApplicationContextFactory.getBean("restTemplate", RestTemplate.class);
        if (Environment.isStartBootWay()) {
            url = URL_BOOT_API + serviceCode;
            restTemplate = ApplicationContextFactory.getBean("outRestTemplate", RestTemplate.class);
        }
 
 
        ResponseEntity<String> responseEntity = callCenterService(restTemplate, pd, JSONObject.toJSONString(param), url, HttpMethod.POST);
 
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new SMOException("调用" + serviceCode + "失败," + responseEntity.getBody());
        }
 
        JSONObject resultVo = JSONObject.parseObject(responseEntity.getBody());
        Object bObj = null;
        if(resultVo.containsKey("code")){
            if (ResultVo.CODE_MACHINE_OK != resultVo.getInteger("code")) {
                throw new SMOException(resultVo.getString("msg"));
            }
            bObj = resultVo.get("data");
        }else{
            bObj = resultVo;
        }
 
 
        JSONArray datas = null;
        if (bObj instanceof JSONObject) {
            datas = new JSONArray();
            datas.add(bObj);
        } else {
            datas = (JSONArray) bObj;
        }
        String jsonStr = JSONObject.toJSONString(datas);
 
        List<T> list = JSONObject.parseArray(jsonStr, t);
        return list;
    }
 
    /**
     * 查询
     *
     * @param pd          页面对象
     * @param param       传入对象
     * @param serviceCode 服务编码
     * @param t           返回类
     * @param <T>
     * @return
     */
    public static <T> List<T> getForApis(IPageData pd, T param, String serviceCode, Class<T> t) {
 
        String url = URL_API + serviceCode;
        RestTemplate restTemplate = ApplicationContextFactory.getBean("restTemplate", RestTemplate.class);
 
        if (Environment.isStartBootWay()) {
            url = URL_BOOT_API + serviceCode;
            restTemplate = ApplicationContextFactory.getBean("outRestTemplate", RestTemplate.class);
        }
 
        if (param != null) {
            url += mapToUrlParam(BeanConvertUtil.beanCovertMap(param));
        }
 
        ResponseEntity<String> responseEntity = callCenterService(restTemplate, pd, "", url, HttpMethod.GET);
 
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new SMOException("调用" + serviceCode + "失败," + responseEntity.getBody());
        }
 
        JSONObject resultVo = JSONObject.parseObject(responseEntity.getBody());
 
        Object bObj = null;
        if(resultVo.containsKey("code")){
            if (ResultVo.CODE_MACHINE_OK != resultVo.getInteger("code")) {
                throw new SMOException(resultVo.getString("msg"));
            }
            bObj = resultVo.get("data");
        }else{
            bObj = resultVo;
        }
        JSONArray datas = null;
        if (bObj instanceof JSONObject) {
            datas = new JSONArray();
            datas.add(bObj);
        } else {
            datas = (JSONArray) bObj;
        }
        String jsonStr = JSONObject.toJSONString(datas);
 
        List<T> list = JSONObject.parseArray(jsonStr, t);
        return list;
    }
 
 
    public static ResponseEntity<String> callCenterService(RestTemplate restTemplate, IPageData pd, String param, String url, HttpMethod httpMethod) {
        ResponseEntity<String> responseEntity = null;
        long startTime = DateUtil.getCurrentDate().getTime();
        logger.debug(url + "调用api开始:" + (startTime));
        HttpHeaders header = new HttpHeaders();
        if (pd.getHeaders() != null) {
            for (String key : pd.getHeaders().keySet()
            ) {
                if (CommonConstant.USER_ID.equals(key.toLowerCase())) {
                    continue;
                }
                header.add(key, pd.getHeaders().get(key).toString());
            }
        }
        header.add(CommonConstant.HTTP_APP_ID.toLowerCase(), StringUtil.isEmpty(pd.getAppId()) ? AppDto.WEB_APP_ID : pd.getAppId());
        header.add(CommonConstant.HTTP_USER_ID.toLowerCase(), StringUtil.isEmpty(pd.getUserId()) ? CommonConstant.ORDER_DEFAULT_USER_ID : pd.getUserId());
 
        header.add(CommonConstant.USER_ID.toLowerCase(), StringUtil.isEmpty(pd.getUserId()) ? CommonConstant.ORDER_DEFAULT_USER_ID : pd.getUserId());
        header.add(CommonConstant.HTTP_TRANSACTION_ID.toLowerCase(), StringUtil.isEmpty(pd.getTransactionId()) ? GenerateCodeFactory.getUUID() : pd.getTransactionId());
        header.add(CommonConstant.HTTP_REQ_TIME.toLowerCase(), StringUtil.isEmpty(pd.getRequestTime()) ? DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_DEFAULT) : pd.getRequestTime());
        //header.add(CommonConstant.HTTP_SIGN.toLowerCase(), "");
        AuthenticationFactory.createSign(header,httpMethod,url,param);
 
        HttpEntity<String> httpEntity = new HttpEntity<String>(param, header);
        //logger.debug("请求中心服务信息,{}", httpEntity);
 
        try {
            responseEntity = restTemplate.exchange(url, httpMethod, httpEntity, String.class);
        } catch (HttpStatusCodeException e) { //这里spring 框架 在4XX 或 5XX 时抛出 HttpServerErrorException 异常,需要重新封装一下
            logger.error("调用中心服务失败", e);
            responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
        } catch (Exception e) {
            logger.error("调用中心服务失败", e);
            responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            logger.debug("请求地址为,{} 请求中心服务信息,{},中心服务返回信息,{}", url, httpEntity, responseEntity);
            logger.debug(url + "调用api耗时:" + (DateUtil.getCurrentDate().getTime() - startTime));
        }
        return responseEntity;
    }
 
    /**
     * map 参数转 url get 参数 非空值转为get参数 空值忽略
     *
     * @param info map数据
     * @return url get 参数 带?
     */
    public static String mapToUrlParam(Map info) {
        String urlParam = "";
        if (info == null || info.isEmpty()) {
            return urlParam;
        }
 
        urlParam += "?";
 
        for (Object key : info.keySet()) {
            if (StringUtil.isNullOrNone(info.get(key))) {
                continue;
            }
 
            urlParam += (key + "=" + info.get(key) + "&");
        }
 
        urlParam = urlParam.endsWith("&") ? urlParam.substring(0, urlParam.length() - 1) : urlParam;
 
        return urlParam;
    }
}