张世豪
2 天以前 913a3b7409e08fd239a65ff7afabefe95b51865a
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
328
329
330
331
332
333
334
335
336
package sendMQTT.HTTPUtils;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
 
/**
 * Properties文件上传工具类
 * 将Properties文件转换为JSON并上传到服务器
 */
public class PropertiesFileUploader {
    
    private static final String DEFAULT_UPLOAD_URL = "http://39.99.43.227:8866/api/file/upload";
    private static final String DEFAULT_FILENAME = "dikuai";
    private static final int CONNECT_TIMEOUT = 30000; // 30秒连接超时
    private static final int READ_TIMEOUT = 60000;    // 60秒读取超时
 
 
    /**
     * 将Properties文件转换为JSON字符串
     * @param filePath Properties文件路径
     * @return JSON字符串
     * @throws Exception 如果读取或转换失败
     */
    public static String propertiesFileToJson(String filePath) throws Exception {
        Properties props = new Properties();
        InputStream inputStream = null;
 
        try {
            File file = new File(filePath);
            if (!file.exists() || !file.isFile()) {
                throw new Exception("文件不存在或不是有效文件: " + filePath);
            }
 
            inputStream = new FileInputStream(file);
            props.load(inputStream);
 
            // 使用Jackson将Properties转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            // Properties本质上是一个Map<String, String>,可以直接序列化为JSON
            String json = objectMapper.writeValueAsString(props);
 
            return json;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
 
    /**
     * 生成毫秒级时间戳
     * @return 当前时间的毫秒级时间戳(自1970年1月1日UTC以来的毫秒数)
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }
 
    /**
     * 移动路径发送方法
     *
     * @param mes_id 消息唯一标识
     * @param user_id 用户ID
     * @param device_id 设备编号
     * @param propertiesFilePath Properties文件路径
     * @return JSON字符串
     * @throws Exception 当上传或转换失败时抛出
     */
    public static String movePathSend(String mes_id,  String user_id, String device_id, String propertiesFilePath)  {
        // 上传Properties文件
        FileUploadResponse fileUploadResponse = PropertiesFileUploader.uploadPropertiesFile(propertiesFilePath);
        if (fileUploadResponse == null) {
            return null;
        }
 
/*        // 打印上传响应信息
        System.out.println("文件上传响应信息:");
        System.out.println("├─ 消息内容: " + fileUploadResponse.getMessage());
        System.out.println("├─ 原始文件名: " + fileUploadResponse.getFilename());
        System.out.println("├─ 保存文件名: " + fileUploadResponse.getSavedFilename());
        System.out.println("├─ 文件类型: " + fileUploadResponse.getFileType());
        System.out.println("├─ 文件大小: " + fileUploadResponse.getSize());
        System.out.println("├─ 下载地址: " + fileUploadResponse.getDownloadUrl());
        System.out.println("├─ 文件UUID: " + fileUploadResponse.getUuid());
        System.out.println("└─ 文件哈希: " + (fileUploadResponse.getHexString() != null ? fileUploadResponse.getHexString() : "N/A"));*/
 
        // 构建数据对象
        MovePathCommand.MovePathData pathData = new MovePathCommand.MovePathData(
                fileUploadResponse.getSavedFilename(),  // filename
                fileUploadResponse.getSize(),           // filesize
                fileUploadResponse.getDownloadUrl()     // url
        );
        long timestamp = PropertiesFileUploader.getCurrentTimestamp();
        // 构建命令对象
        MovePathCommand command = new MovePathCommand(
                mes_id,
                timestamp,
                user_id,
                device_id,
                pathData
        );
 
        // 转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(command);
        } catch (JsonProcessingException e) {
            return null;
        }
 
        return jsonString;
    }
 
 
 
 
    /**
     * 上传Properties文件到服务器
     * 
     * @param filePath Properties文件路径
     * @param filename 文件名(用于URL参数,默认为"dikuai")
     * @param uploadUrl 上传接口URL(可选,默认使用文档中的URL)
     * @return FileUploadResponse 上传响应结果
     * @throws Exception 当上传失败时抛出
     */
    public static FileUploadResponse uploadPropertiesFile(String filePath, String filename, String uploadUrl) throws Exception {
        // 参数校验
        if (filePath == null || filePath.trim().isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }
        
        // 使用默认值
        if (filename == null || filename.trim().isEmpty()) {
            filename = DEFAULT_FILENAME;
        }
        if (uploadUrl == null || uploadUrl.trim().isEmpty()) {
            uploadUrl = DEFAULT_UPLOAD_URL;
        }
        
        // 调用Server.propertiesFileToJson方法生成JSON字符串
        String jsonData = propertiesFileToJson(filePath);
        System.out.println("已成功将Properties文件转换为JSON: " + filePath);
        
        // 构建完整的URL(包含filename参数,进行URL编码)
        String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        String fullUrl = uploadUrl + "?filename=" + encodedFilename;
        
        // 发送HTTP POST请求
        HttpURLConnection connection = createConnection(fullUrl);
        
        try {
            // 发送JSON数据
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] jsonBytes = jsonData.getBytes(StandardCharsets.UTF_8);
                outputStream.write(jsonBytes);
                outputStream.flush();
            }
            
            // 获取响应
            String responseJson = getResponse(connection);
            
            // 解析响应JSON
            ObjectMapper objectMapper = new ObjectMapper();
            FileUploadResponse response = objectMapper.readValue(responseJson, FileUploadResponse.class);
            
            System.out.println("文件上传成功: " + response.getSavedFilename());
            return response;
            
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    
    /**
     * 上传Properties文件到服务器(使用默认参数)
     * 
     * @param filePath Properties文件路径
     * @return FileUploadResponse 上传响应结果
     * @throws Exception 当上传失败时抛出
     */
    public static FileUploadResponse uploadPropertiesFile(String filePath)  {
        try {
            return uploadPropertiesFile(filePath, DEFAULT_FILENAME, DEFAULT_UPLOAD_URL);
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 上传Properties文件到服务器(指定文件名)
     * 
     * @param filePath Properties文件路径
     * @param filename 文件名(用于URL参数)
     * @return FileUploadResponse 上传响应结果
     * @throws Exception 当上传失败时抛出
     */
    public static FileUploadResponse uploadPropertiesFile(String filePath, String filename) throws Exception {
        return uploadPropertiesFile(filePath, filename, DEFAULT_UPLOAD_URL);
    }
    
    /**
     * 创建HTTP连接
     */
    private static HttpURLConnection createConnection(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        // 设置连接属性
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        
        // 设置请求头
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("User-Agent", "PropertiesFileUploader/1.0");
        
        return connection;
    }
    
    /**
     * 获取服务器响应
     */
    private static String getResponse(HttpURLConnection connection) throws Exception {
        // 检查HTTP响应码
        int status = connection.getResponseCode();
        InputStream inputStream;
        
        if (status >= 200 && status < 300) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }
        
        // 读取响应内容
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        // 如果请求失败,抛出异常
        if (status >= 400) {
            throw new Exception("HTTP请求失败,状态码: " + status + ",响应: " + response.toString());
        }
        
        return response.toString();
    }
    
    /**
     * 安全上传方法(不抛出异常,返回结果对象)
     *
     * @param filePath Properties文件路径
     * @param filename 文件名(用于URL参数,可选)
     * @param uploadUrl 上传接口URL(可选)
     * @return UploadResult 包含上传结果的封装对象
     */
    public static UploadResult uploadPropertiesFileSafe(String filePath, String filename, String uploadUrl) {
        try {
            FileUploadResponse response = uploadPropertiesFile(filePath, filename, uploadUrl);
            ObjectMapper objectMapper = new ObjectMapper();
            String responseJson = objectMapper.writeValueAsString(response);
            return new UploadResult(true, response.getMessage(), responseJson, 200);
        } catch (Exception e) {
            return new UploadResult(false, "上传失败: " + e.getMessage(), null, 500);
        }
    }
    
    /**
     * 安全上传方法(使用默认参数)
     *
     * @param filePath Properties文件路径
     * @return UploadResult 包含上传结果的封装对象
     */
    public static UploadResult uploadPropertiesFileSafe(String filePath) {
        return uploadPropertiesFileSafe(filePath, DEFAULT_FILENAME, DEFAULT_UPLOAD_URL);
    }
    
    /**
     * 上传结果封装类
     */
    public static class UploadResult {
        private boolean success;
        private String message;
        private String data;
        private int statusCode;
        
        public UploadResult(boolean success, String message, String data, int statusCode) {
            this.success = success;
            this.message = message;
            this.data = data;
            this.statusCode = statusCode;
        }
        
        public boolean isSuccess() {
            return success;
        }
        
        public String getMessage() {
            return message;
        }
        
        public String getData() {
            return data;
        }
        
        public int getStatusCode() {
            return statusCode;
        }
        
        @Override
        public String toString() {
            return "UploadResult{" +
                    "success=" + success +
                    ", message='" + message + '\'' +
                    ", data='" + data + '\'' +
                    ", statusCode=" + statusCode +
                    '}';
        }
    }
}