严智鑫
2025-06-13 d14cdaf28222bfef468185e34de7c823f1436b19
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
package com.mes.connect.IndustrialInterface;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
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;
 
@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;
    }
    /**
     * 发送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;
            String method=data.get("method").toString();
            data.remove("method");
            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> params) {
        // 验证视图名是否合法,防止SQL注入
        if (!isValidViewName(viewName)) {
            throw new IllegalArgumentException("无效的视图名称");
        }
 
        // 使用预编译语句构建查询
        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,Map<String, Object> outParams) {
        try {
            if (!isValidProcedureName(procedureName)) {
                throw new IllegalArgumentException("无效的存储过程名称");
            }
 
            SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
                    .withProcedureName(procedureName)
                    .withoutProcedureColumnMetaDataAccess();
 
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    // 确定参数类型
                    int sqlType = getSqlType(entry.getValue());
 
                    // 检查是否为输出参数
                    if (outParams != null && outParams.containsKey(entry.getKey())) {
                        Object outParamInfo = outParams.get(entry.getKey());
                        int outSqlType;
 
                        // 从输出参数信息中获取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)
                        );
                    } else {
                        // 作为输入参数
                        jdbcCall.declareParameters(
                                new SqlParameter(entry.getKey(), sqlType)
                        );
                    }
                }
            }
 
            // 执行存储过程并获取结果
            Map<String, Object> result = jdbcCall.execute(params);
 
            // 处理输出参数
            if (outParams != null) {
                for (String paramName : outParams.keySet()) {
                    if (result.containsKey(paramName)) {
                        // 将输出参数的值放回原参数Map中
                        params.put(paramName, result.get(paramName));
                    }
                }
            }
 
            // 返回结果信息
            return null;
        } 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}$");
    }
 
}