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
package com.mes.connect.IndustrialInterface;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.connect.entity.ApiConfig;
import com.mes.connect.entity.LogicItem;
import com.mes.connect.entity.PlcParameters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
 
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
@Slf4j
@Service
public class Api implements ApiService {
 
 
 
    private final RestTemplate restTemplate;
 
    private final JdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
 
    // 使用构造函数注入
    @Autowired
    public Api(RestTemplate restTemplate, JdbcTemplate jdbcTemplate) {
        this.restTemplate = restTemplate;
        this.jdbcTemplate = jdbcTemplate;
    }
 
    /**
     * 发送调用接口请求 ,根据逻辑配置调用
     *
     * @param apiConfig 逻辑配置参数
     * @param plcParameters plc参数
     * @return 响应内容按行分割的数组
     */
    public List<String> callApi(ApiConfig apiConfig, PlcParameters plcParameters){
        try{
            List<String> result=new ArrayList<>();
            String connectType=apiConfig.getType();
            String connectAddress=apiConfig.getAddress();
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("apiConfig",apiConfig);
            map.put("plcParameter",plcParameters);
            switch (connectType) {
                case "Http":
                    result= this.httpApi(connectAddress,map);
                    break;
                case "View": // 视图/表
                    result= this.viewApi(connectAddress,map);
                    break;
                case "Procedure": // 存储过程
                    result= this.procedureAPI(connectAddress,map);
                    break;
                default:
                    log.warn("不支持的连接类型: {}", connectType);
                    return null; // 不支持的方式
            }
            return result;
        }catch (Exception e){
            log.error("调用接口失败: {}", e.getMessage(), e);
        }
        return null;
    }
 
 
 
 
 
    /**
     * 发送HTTP请求,支持GET和POST方法
     *
     * @param url 请求URL
     * @param data 请求参数或请求体
     * @return 响应内容按行分割的数组
     */
    @DS("mes_machine")
    @Override
    public List<String> httpApi(String url,Map<String, Object> data) {
        try {
            // 构建URL
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
            // 处理响应
            String responseBody;
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> apiConfig= mapper.convertValue(data.get("apiConfig"), Map.class);
            Map<String, Object> parameters= mapper.convertValue(apiConfig.get("parameters"), Map.class);
            String method=parameters.get("method").toString();
            data.remove("parameters");
            if ("GET".equals(method)) {
                // GET请求:将参数添加到URL查询参数中
                if (data != null) {
                    data.forEach(builder::queryParam);
                }
                // 发送GET请求
                ResponseEntity<String> response = restTemplate.exchange(
                        builder.toUriString(),
                        HttpMethod.GET,
                        null,
                        String.class
                );
                responseBody = response.getBody();
            } else if ("POST".equals(method)) {
                // POST请求:将参数作为请求体
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<?> entity = new HttpEntity<>(data, headers);
                // 发送POST请求
                ResponseEntity<String> response = restTemplate.exchange(
                        builder.toUriString(),
                        HttpMethod.POST,
                        entity,
                        String.class
                );
                responseBody = response.getBody();
            } else {
                throw new IllegalArgumentException("不支持的HTTP方法: " + method);
            }
            // 直接提取data数组
            List<String> dataList = JSON.parseObject(responseBody)
                    .getJSONArray("data")
                    .toJavaList(String.class);
            return dataList;
            //return responseBody != null ? responseBody.split("\n") : new String[0];
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            return null;
        }
    }
    @DS("mes_machine")
    @Override
    public List<String> viewApi(String viewName, Map<String, Object> parameters) {
        // 验证视图名是否合法,防止SQL注入
        if (!isValidViewName(viewName)) {
            throw new IllegalArgumentException("无效的视图名称");
        }
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> apiConfig= mapper.convertValue(parameters.get("apiConfig"), Map.class);
        Map<String, Object> params= mapper.convertValue(apiConfig.get("parameters"), Map.class);
        // 使用预编译语句构建查询
        StringBuilder sql = new StringBuilder("SELECT * FROM " + viewName);
        MapSqlParameterSource paramSource = new MapSqlParameterSource();
 
        if (params != null && !params.isEmpty()) {
            sql.append(" WHERE ");
            boolean first = true;
 
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (!first) {
                    sql.append(" AND ");
                }
                sql.append(entry.getKey()).append(" = :").append(entry.getKey());
                paramSource.addValue(entry.getKey(), entry.getValue());
                first = false;
            }
        }
        // 使用Map参数执行查询并转换结果
        List<Map<String, Object>> resultList = namedParameterJdbcTemplate.queryForList(
                sql.toString(),
                paramSource.getValues()
        );
 
        return convertResultToList(resultList);
    }
    @DS("jiumumes")
    @Override
    public List<String> procedureAPI(String procedureName, Map<String, Object> params) {
        try {
            if (!isValidProcedureName(procedureName)) {
                throw new IllegalArgumentException("无效的存储过程名称");
            }
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> apiConfig= mapper.convertValue(params.get("apiConfig"), Map.class);
            Map<String, Object> parameters=mapper.convertValue(apiConfig.get("parameters"), Map.class);
            Map<String, Object> inParams= mapper.convertValue(parameters.get("inParams"), Map.class);
            Map<String, Object> outParams= mapper.convertValue(parameters.get("outParams"), Map.class);
            // 创建新的 Map 并合并
            Map<String, Object> mergedMap = new HashMap<>(inParams);
            mergedMap.putAll(outParams);
            SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
                    .withProcedureName(procedureName)
                    .withoutProcedureColumnMetaDataAccess();
            for (Map.Entry<String, Object> entry : inParams.entrySet()) {
                int sqlType = getSqlType(entry.getValue());
                // 作为输入参数
                jdbcCall.declareParameters(
                        new SqlParameter(entry.getKey(), sqlType)
                );
            }
            for (Map.Entry<String, Object> entry : outParams.entrySet()) {
                int outSqlType=12;
//                int sqlType = getSqlType(entry.getValue());
//                Object outParamInfo = outParams.get(entry.getKey());
//                // 从输出参数信息中获取SQL类型
//                if (outParamInfo instanceof Integer) {
//                    outSqlType = (Integer) outParamInfo;
//                } else if (outParamInfo instanceof Map) {
//                    // 假设Map中包含"sqlType"键
//                    Map<String, Object> outParamMap = (Map<String, Object>) outParamInfo;
//                    outSqlType = (Integer) outParamMap.getOrDefault("sqlType", sqlType);
//                } else {
//                    // 默认使用输入参数的SQL类型
//                    outSqlType = sqlType;
//                }
 
                // 使用指定的SQL类型作为输出参数
                jdbcCall.declareParameters(
                        new SqlOutParameter(entry.getKey(), outSqlType)
                );
            }
            // 执行存储过程并获取结果
            Map<String, Object> result = jdbcCall.execute(mergedMap);
 
            // 处理输出参数
            if (outParams != null) {
                for (String paramName : outParams.keySet()) {
                    if (result.containsKey(paramName)) {
                        // 将输出参数的值放回原参数Map中
                        outParams.put(paramName, result.get(paramName));
                    }
                }
            }
            List<String> outParamsValues = outParams.values().stream()
                    .map(value -> value != null ? value.toString() : "null")
                    .collect(Collectors.toList());
            // 返回结果信息
            return outParamsValues;
        } catch (Exception e) {
            return null;
        }
    }
 
    // 将查询结果转换为字符串数组
    private List<String> convertResultToList(List<Map<String, Object>> resultList) {
        List<String> resultStrings = new ArrayList<>();
        for (Map<String, Object> row : resultList) {
            for (String key : row.keySet()) {
                resultStrings.add(row.get(key).toString());
            }
            return resultStrings;
        }
        //return resultStrings.toArray(new String[0]);
        return resultStrings;
    }
 
    // 类型映射方法
    private int getSqlType(Object value) {
        if (value instanceof String) return Types.VARCHAR;
        if (value instanceof Integer) return Types.INTEGER;
        if (value instanceof Double) return Types.DOUBLE;
        if (value instanceof java.util.Date) return Types.TIMESTAMP;
        if (value instanceof Boolean) return Types.BOOLEAN;
        return Types.VARCHAR;
    }
 
    // 验证视图名称(防止SQL注入)
    private boolean isValidViewName(String viewName) {
        // 简单验证:只允许字母、数字和下划线,且长度不超过50
        return viewName.matches("^[a-zA-Z0-9_]{1,50}$");
    }
 
    // 验证存储过程名称
    private boolean isValidProcedureName(String procedureName) {
        return procedureName.matches("^[a-zA-Z0-9_]{1,50}$");
    }
 
}