lyh
2025-01-13 137d008bd9b7d932160436a3a560b24512f6d1db
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
package org.jeecg.modules.dnc.service.impl;
 
import cn.hutool.crypto.SmUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.dnc.dto.SysLogTypeObjectDto;
import org.jeecg.modules.dnc.entity.DncPassLog;
import org.jeecg.modules.dnc.mapper.DncPassLogMapper;
import org.jeecg.modules.dnc.response.SysLogMessageDto;
import org.jeecg.modules.dnc.utils.FileClient;
import org.jeecg.modules.dnc.utils.SyslogClient;
import org.jeecg.modules.dnc.utils.TelnetUtil;
import org.jeecg.modules.dnc.utils.ValidateUtil;
import org.jeecg.modules.dnc.utils.date.DateUtil;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.dnc.service.IDncPassLogService;
import org.jeecg.modules.dnc.utils.file.FileUtilS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
 
/**
 * @author clown
 * * @date 2023/11/29
 */
@Service
public class DncPassLogServiceImpl extends ServiceImpl<DncPassLogMapper, DncPassLog> implements IDncPassLogService {
 
    @Value("${securedoc.serverIp}")
    private String serverIp;
    @Value("${securedoc.serverPort}")
    private String serverPort;
    @Value("${securedoc.username}")
    private String usernameService;
    @Value("${securedoc.pwd}")
    private String pwdService;
    @Value("${securedoc.addressToken}")
    private String addressToken;
    @Value("${securedoc.addressUploadFile}")
    private String addressUploadFile;
    @Value("${securedoc.localFilePath}")
    private String localFilePathC;
    @Value("${securedoc.servicePath}")
    private String servicePathS;
    @Value("${securedoc.copyFilePath}")
    private String newFilePathC;
    @Value("${securedoc.logIp}")
    private String logIp;
    @Value("${securedoc.logPort}")
    private String logPort;
    @Autowired
    private ISysDictService iSysDictService;
    @Autowired
    private ISysDictItemService iSysDictItemService;
 
    @Override
    public DncPassLog findDayTime(String dateDay) {
        if (!ValidateUtil.validateString(dateDay)) {
            return null;
        }
        return super.baseMapper.findDateTimeDay(dateDay);
    }
 
    @Override
    @Scheduled(cron = "${fileCron}")
    public void fileClientTxtOrNc() {
        SysLogMessageDto message = new SysLogMessageDto();
        String host = "127.0.0.1";
        if (StringUtils.isNotBlank(serverIp)) {
            host = serverIp;
        }
        String port = "8299";
        if (StringUtils.isNotBlank(serverPort)) {
            port = serverPort;
        }
        String username = "admin";
        if (StringUtils.isNotBlank(usernameService)) {
            username = usernameService;
        }
        String pwd = "123";
        if (StringUtils.isNotBlank(pwdService)) {
            pwd = pwdService;
        }
        //文件本地地址,根据地址找到文件,将文件解析成文件流
        String localFilePath = "/jar/test/a/";
//        String localFilePath = "E:\\test\\a\\";
        if (StringUtils.isNotBlank(localFilePathC)) {
            localFilePath = localFilePathC;
        }
        //文件上传目的地址,将文件上传到该地址
        String servicePath = "/jar/test/b/";
//        String servicePath = "E:\\test\\b\\";
        if (StringUtils.isNotBlank(servicePathS)) {
            servicePath = servicePathS;
        }
        boolean btelnetPort =  TelnetUtil.telnetPort(serverIp,Integer.valueOf(serverPort),10);
        if (!btelnetPort) {
            System.out.println("服务器连接: " + serverIp + ":" + serverPort + " 异常!" );
            return;
        }
        //第一步,获取token
        String token = null;
        try {
            token = FileClient.getToken(host,port,username,pwd,addressToken);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
 
        //若获取token成功,再进行上传文件接口调用
        if (token !=null && !token.equals("")){
            try {
                File f3 = new File(localFilePath);
                File[] files = f3.listFiles();
                for (File fi : files){
                    if (fi.isFile()){
                        SysLogTypeObjectDto objectName = new SysLogTypeObjectDto();
                        objectName.setDateTime(DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_SMALL));
                        objectName.setFileName(fi.getName());
                        objectName.setFileSize(FileUtilS.changeFileFormatKb(String.valueOf(new File(localFilePath).length())));
                        objectName.setSourceAddress(localFilePath);
                        objectName.setDestination(serverIp);//服务端IP
                        //顺序号
                        DncPassLog passLog = getById("num0001");
                        if (passLog == null) {
                            passLog = new DncPassLog();
                            passLog.setId("num0001");
                            passLog.setSequenceNumber(1);
                            objectName.setFileNum(Integer.toString(1));
                            save(passLog);
                        } else {
                            Integer number = passLog.getSequenceNumber()+1;
                            removeById("num0001");
                            objectName.setFileNum(Integer.toString(number));
 
                            passLog = new DncPassLog();
                            passLog.setId("num0001");
                            passLog.setSequenceNumber(number);
                            save(passLog);
                        }
 
                        InetAddress address = null;
                        try {
                            address = InetAddress.getLocalHost();
                            String ip = address.getHostAddress();
                            objectName.setSourceAddress("20.10.17.11");//客户端IP
                            objectName.setAddress(ip);
                        } catch (UnknownHostException e) {
                            objectName.setSourceAddress("127.0.0.1");
                            objectName.setAddress("127.0.0.1");
                        }
                        objectName.setDestination(host);
                        objectName.setResult("失败");
                        //获取某个文件下的所有文件
                        String loFilePath = localFilePath + fi.getName();
                        String servicePathName =servicePath + fi.getName();
//                        String loFilePath = localFilePath + "\\" + fi.getName();
//                        String servicePathName =servicePath + "\\" + fi.getName();
                        File file = new File(loFilePath);
                        if (file == null || !file.exists()){
                            objectName.setAbstract1("sm3");
                        } else {
                            String sm3 = SmUtil.sm3(file);
                            objectName.setAbstract1(sm3);
                        }
 
                        String b  = FileClient.uploadFile(host,port,token,fi.getName(),servicePathName,loFilePath,addressUploadFile);
                        //文件备份删除
                        if (b == null) {
                            try {
                                objectName.setResult("失败");
                                objectName.setTypes("error");
                                SyslogClient.sendClient(logIp,Integer.valueOf(logPort),objectName.toString());
                            }catch (Exception e) {
                                return;
                            }
                        }
                        else if ( b.equals("成功")) {
                            //备份数据
                            boolean fCopy = FileUtilS.copyNcFile(loFilePath,newFilePathC + "/" + DateUtil.format(DateUtil.getNow(),
                                    DateUtil.STR_YEARMONTHDAY) + "/" +fi.getName());
                            if (fCopy) {
                                FileUtilS.deleteNcFile(loFilePath);
                            } else {
                                FileUtilS.copyNcFile(loFilePath,newFilePathC + "/" + DateUtil.format(DateUtil.getNow(),
                                        DateUtil.STR_YEARMONTHDAY) + "/" +fi.getName());
                                FileUtilS.deleteNcFile(loFilePath);
                            }
                            try {
                                objectName.setTypes("Info");
                                objectName.setResult("成功");
                                SyslogClient.sendClient(logIp,Integer.valueOf(logPort),objectName.toString());
                            }catch (Exception e) {
                                return;
                            }
                        } else {
                            try {
                                objectName.setResult("失败");
                                objectName.setTypes("error");
                                SyslogClient.sendClient(logIp,Integer.valueOf(logPort),objectName.toString());
                            }catch (Exception e) {
                                return;
                            }
                        }
                    }
                }
 
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }
 
    /**
     * 定时任务执行器参数  每天凌晨1.30执行
     */
    @Override
//    @Scheduled(cron = "0 30 1 * * ?")
    public void deleteNcSendFile() {
        Integer day;
        //取字典时间
        List<DictModel> singleDictionaries=iSysDictService.queryDictItemsByCode("DEL_TIME_SEND");
        if (singleDictionaries.size()!=1){
            return;
        }else {
            day= Integer.valueOf(singleDictionaries.get(0).getValue());
        }
        Path ncDirectory = Paths.get("jar/NC");
        //天转秒
        long dayToSecond = day * 24 * 60 * 60;
        if (Files.exists(ncDirectory) && Files.isDirectory(ncDirectory)) {
            // 递归查找NC目录下所有名为send的文件夹
            try (Stream<Path> sendFolders = Files.walk(ncDirectory)
                    .filter(Files::isDirectory)
                    .filter(path -> path.getFileName().toString().equalsIgnoreCase("send"))) {
                sendFolders.forEach(sendFolder -> {
                    try {
                        // 获取当前时间
                        Instant now = Instant.now();
                        // 遍历SEND文件夹内的所有文件
                        Files.walk(sendFolder)
                                .filter(Files::isRegularFile)
                                .forEach(file -> {
                                    try {
                                        // 获取文件的最后修改时间
                                        Instant lastModified = Files.getLastModifiedTime(file).toInstant();
                                        // 计算时间差
                                        Duration duration = Duration.between(lastModified, now);
                                        // 判断是否超时(时间存在字典中,base_single_dictionary)
                                        if (duration.getSeconds() > dayToSecond) {
                                            try {
                                                Files.delete(file);
                                                System.out.println("已删除文件: " + file);
                                            } catch (IOException e) {
                                                System.err.println("删除文件 " + file + " 时出现错误: " + e.getMessage());
                                            }
                                        }
                                    } catch (IOException e) {
                                        System.err.println("获取文件 " + file + " 的最后修改时间时出现错误: " + e.getMessage());
                                    }
                                });
                    } catch (IOException e) {
                        System.err.println("遍历 " + sendFolder + " 文件夹时出现错误: " + e.getMessage());
                    }
                });
            } catch (IOException e) {
                System.err.println("查找send文件夹时出现错误: " + e.getMessage());
            }
        } else {
            System.err.println("jar的NC目录不存在或不是有效的目录");
        }
    }
 
}