Selaa lähdekoodia

修正upload模块打包不成功,清理console里报错的地方

xusl 1 vuosi sitten
vanhempi
commit
db2303cac0
76 muutettua tiedostoa jossa 274 lisäystä ja 8064 poistoa
  1. 2 2
      ipfcst-common/ipfcst-common-core/src/main/resources/banner.txt
  2. 0 2
      ipfcst-console/pom.xml
  3. 1 1
      ipfcst-console/src/main/java/com/jiayue/ipfcst/console/controller/ConsoleOpenInterfaceController.java
  4. 1 1
      ipfcst-console/src/main/java/com/jiayue/ipfcst/console/controller/WindTowerInfoController.java
  5. 0 29
      ipfcst-console/src/main/java/com/jiayue/ipfcst/console/service/TestRedisReceiver.java
  6. 17 0
      ipfcst-console/src/main/java/com/jiayue/ipfcst/console/util/FileConstant.java
  7. 0 354
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/Base102Service.java
  8. 0 12
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/NettyParent.java
  9. 0 135
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102Decoder.java
  10. 0 22
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102Encoder.java
  11. 0 37
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102InitChannel.java
  12. 0 420
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102NMService.java
  13. 0 396
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102StandardService.java
  14. 0 362
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102TransitHandler.java
  15. 0 78
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/UploadFileNettyServer.java
  16. 0 320
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiBase102Service.java
  17. 0 130
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiClient.java
  18. 0 182
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiClientHandler.java
  19. 0 90
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiDecoder.java
  20. 0 27
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiEncoder.java
  21. 0 395
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiHandlerService.java
  22. 0 312
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/SdBase102Service.java
  23. 0 144
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongClient.java
  24. 0 257
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongClientHandler.java
  25. 0 139
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongDecoder.java
  26. 0 28
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongEncoder.java
  27. 0 467
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongHandlerService.java
  28. 0 75
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongServer.java
  29. 0 178
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongServerHandler.java
  30. 0 129
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangClient.java
  31. 0 157
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangClientHandler.java
  32. 0 209
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangDecoder.java
  33. 0 27
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangEncoder.java
  34. 0 241
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangHandlerService.java
  35. 0 121
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/config/AppenderFactory.java
  36. 0 118
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/config/FileUploadConfig.java
  37. 1 1
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/controller/UploadFileLogController.java
  38. 1 4
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/controller/UploadFileOpenInterfaceController.java
  39. 0 17
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/dto/UploadFileTypeDto.java
  40. 0 17
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/dto/Validate102Dto.java
  41. 0 30
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/FtpClientUploadJob.java
  42. 0 106
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/ListenUploadJob.java
  43. 0 85
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/MengXiClientJob.java
  44. 0 76
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/ZheJiang102ClientJob.java
  45. 1 5
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/AnalyticFeedback/AnalysisFeedbackFileService.java
  46. 0 11
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/BaseUploadFileService.java
  47. 1 1
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E37/E37UploadFileService.java
  48. 1 1
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E43/E43UploadFileService.java
  49. 0 3
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E46/E46UploadFileService.java
  50. 0 290
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/FtpUploadService.java
  51. 0 321
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/FtpUploadTransactionService.java
  52. 4 199
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/UploadFileChannelService.java
  53. 0 31
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/UploadFileLogService.java
  54. 0 1
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/UploadURLService.java
  55. 0 72
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/util/FileConstant.java
  56. 0 39
      ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/util/FileUploadMonitor.java
  57. 0 41
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongClientTest.java
  58. 0 43
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/TestUploadFileType.java
  59. 0 20
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/job/UploadFileShortTermTypeJobTest.java
  60. 0 73
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/E42/E42UploadFileServiceTest.java
  61. 0 257
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/E65/TestE65UploadFileService.java
  62. 0 12
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseCreateFile.java
  63. 0 66
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseMxCreateFile.java
  64. 0 56
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseNMCreateFile.java
  65. 0 12
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseSDCreateFile.java
  66. 0 16
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/Test.java
  67. 0 147
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/UploadFileChannelServiceTest.java
  68. 0 68
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiang102.java
  69. 0 180
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiangFor102Decoder.java
  70. 0 21
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiangFor102Encoder.java
  71. 0 103
      ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiangHandler.java
  72. 182 40
      ipfcst-upload/pom.xml
  73. 1 1
      ipfcst-upload/src/main/java/com/jiayue/ipfcst/upload/util/IEC102Uitl.java
  74. 11 1
      ipfcst-upload/src/main/resources/application.yml
  75. 18 0
      ipfcst-upload/src/main/resources/assembly_base.xml
  76. 32 0
      ipfcst-upload/src/main/resources/start-upload.vm

+ 2 - 2
ipfcst-common/ipfcst-common-core/src/main/resources/banner.txt

@@ -2,5 +2,5 @@
 ************************************
 ******沈阳嘉越电力科技有限公司******
 ************************************
-    启动【智能功率预测系统V3.0
-====================================
+    启动【智能功率预测系统V3.3
+====================================

+ 0 - 2
ipfcst-console/pom.xml

@@ -487,8 +487,6 @@
         <artifactId>maven-jar-plugin</artifactId>
         <version>2.6</version>
         <configuration>
-
-
           <excludes>
             <exclude>application.yml</exclude>
             <exclude>logback-console.xml</exclude>

+ 1 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/console/controller/ConsoleOpenInterfaceController.java

@@ -1,8 +1,8 @@
 package com.jiayue.ipfcst.console.controller;
 
+import com.jiayue.ipfcst.console.util.FileConstant;
 import com.jiayue.ipfcst.dataexchange.container.ProtocolTunnelContainer;
 import com.jiayue.ipfcst.dataexchange.service.FileParseTunnelService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;

+ 1 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/console/controller/WindTowerInfoController.java

@@ -65,7 +65,7 @@ import java.util.List;
     /**
      * 删除测风塔
      *
-     * @param windTowerInfo 参数
+     * @param id 参数
      * @return 执行结果
      */
     @SneakyThrows

+ 0 - 29
ipfcst-console/src/main/java/com/jiayue/ipfcst/console/service/TestRedisReceiver.java

@@ -1,29 +0,0 @@
-package com.jiayue.ipfcst.console.service;
-
-//import com.alibaba.fastjson.JSONObject;
-//import com.jiayue.ipfcst.core.entity.ElectricField;
-//import org.springframework.stereotype.Service;
-//
-///**
-// * TODO
-// *
-// * @author zzy
-// * @version 1.0
-// * @since 2019/8/23 14:24
-// */
-//@Service
-//public class TestRedisReceiver {
-//
-//
-//    public void receiveMessage(String message) {
-//        System.out.println("收到消息:" + message);
-//        ElectricField electricField  =  JSONObject.parseObject(message, ElectricField.class);
-//        System.out.println("收到消息:" + electricField.getName());
-//    }
-//
-//    public void receiveMessage2(String message) {
-//        System.out.println("收到消息2:" + message);
-//        ElectricField electricField  =  JSONObject.parseObject(message, ElectricField.class);
-//        System.out.println("收到消息2:" + electricField.getName());
-//    }
-//}

+ 17 - 0
ipfcst-console/src/main/java/com/jiayue/ipfcst/console/util/FileConstant.java

@@ -0,0 +1,17 @@
+package com.jiayue.ipfcst.console.util;
+
+import lombok.extern.slf4j.Slf4j;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+
+/**
+ * 上报文件公用变量
+ *
+ * @author xsl
+ * @version 3.0
+ */
+@Slf4j
+public class FileConstant {
+  public static ConcurrentMap<String,String> channelStatusMap = new ConcurrentHashMap<String,String>();
+}

+ 0 - 354
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/Base102Service.java

@@ -1,354 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import cn.hutool.core.convert.Convert;
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.*;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogDetailRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.console.service.SysParameterService;
-import com.jiayue.ipfcst.fileupload.service.E63.E63UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileCodeService;
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.apache.poi.ss.usermodel.Row;
-import org.apache.poi.ss.usermodel.Sheet;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.WorkbookFactory;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.io.*;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 102业务处理基础类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class Base102Service {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  @Autowired
-  UploadFileLogDetailRepository uploadFileLogDetailRepository;
-  @Autowired
-  SysParameterService sysParameterService;
-  @Autowired
-  UploadFileCodeService uploadFileCodeService;
-  @Autowired
-  ElectricFieldService electricFieldService;
-
-
-  /**
-   * 统计文件上报成功或者失败并移动文件
-   *
-   * @param uploadFileChannel 通道信息
-   * @param faileReason       失败原因
-   */
-
-  public void totalFileUploadNums(UploadObject uploadObject, UploadFileChannel uploadFileChannel, String faileReason, Logger log) {
-    // 上报文件次数缓存加1
-//    Map<String, FileMutableInteger> filterMap = FileConstant.uploadCountMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))))
-//      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-//        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-
-    // 上报文件名
-    String fileNameKey = "";
-    Iterator<Map.Entry<String, FileMutableInteger>> filterMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (filterMap.hasNext()) {
-      Map.Entry<String, FileMutableInteger> entry = filterMap.next();
-      String key = entry.getKey();
-      if (key.substring(0, key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-        fileNameKey = key;
-        break;
-      }
-    }
-    if ("".equals(fileNameKey)) {
-      log.info("输出当前filterMap里内容");
-      log.info(Convert.toStr(FileConstant.uploadCountMap));
-      Iterator<Map.Entry<String, FileMutableInteger>> refilterMap = FileConstant.uploadCountMap.entrySet().iterator();
-      while (refilterMap.hasNext()) {
-        Map.Entry<String, FileMutableInteger> entry = refilterMap.next();
-        String key = entry.getKey();
-        if (key.substring(0, key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-          fileNameKey = key;
-          break;
-        }
-      }
-    }
-    if (!"".equals(fileNameKey)) {
-      String[] keys = new String[3];
-      String tempFileName = fileNameKey;
-      log.info("UploadNums操作文件:" + tempFileName);
-      keys[0] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-      tempFileName = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-      keys[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-      keys[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-
-      // 找到文件日志记录
-      //今日凌晨
-//    Long st = DateTimeUtil.getMillisecondsSubDay();
-      //明日凌晨
-//    Long et = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24-1;
-
-//    Date fileCreateTime = FileConstant.fileShouldMomentMap.get(fileNameKey);
-      Integer id = FileConstant.fileShouldMomentMap.get(fileNameKey);
-      UploadFileLog uploadFileLog = null;
-      Optional<UploadFileLog> fileLogOptional = uploadFileLogRepository.findById(id);
-      if (fileLogOptional.isPresent()) {
-        uploadFileLog = fileLogOptional.get();
-      }
-
-      // 先判断是否查出日志,如果没有则认为文件是本地拷贝进去的
-      if (uploadFileLog == null) {
-        UploadFileLog newUploadFileLog = new UploadFileLog();
-        newUploadFileLog.setUploadObjectId(uploadObject.getId());
-        newUploadFileLog.setFileStatusEnum(FileStatusEnum.E1);
-        newUploadFileLog.setUploadProtocolEnum(uploadObject.getUploadProtocolEnum());
-        newUploadFileLog.setFileName(keys[2]);
-        newUploadFileLog.setFileTypeEnum(FileTypeEnum.valueOf(keys[1]));
-        newUploadFileLog.setUploadObjectName(uploadObject.getUploadObjectName());
-        newUploadFileLog.setUploadObjectNo(uploadObject.getObjectNo());
-        newUploadFileLog.setUploadCounter(0);
-        newUploadFileLog.setFileRemarks("当日没找到日志记录,系统插入一条");
-        uploadFileLog = uploadFileLogRepository.save(newUploadFileLog);
-      }
-
-      if ("".equals(faileReason)) {
-        UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-        uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-        uploadFileLogDetail.setUploadFileLogId(uploadFileLog.getId());
-        uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-        uploadFileLogDetail.setFileName(keys[2]);
-        uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-        uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-        uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E2);
-//      fileMutableInteger.getUploadFileLogDetail().add(uploadFileLogDetail);
-        // 上报成功保存数据库,更新上报表,上报明细
-//      uploadFileLogRepository.updateFileUploadCount(FileStatusEnum.E2, fileMutableInteger.getValue(), uploadObject.getId(), keys[2]);
-//        uploadFileLog.setFileStatusEnum(FileStatusEnum.E2);
-//        uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter()+1);
-//        uploadFileLogRepository.save(uploadFileLog);
-        uploadFileLogRepository.uploadFileUpdate(FileStatusEnum.E2, uploadFileLog.getUploadCounter() + 1, uploadFileLog.getId());
-        uploadFileLogDetailRepository.save(uploadFileLogDetail);
-        // 将文件移动到成功目录
-        String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-        String targetPath = FileUtil.getFileUploadPath() + File.separator + "backups" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-
-        try {
-          FileUtil.move(srcPath, targetPath);
-        } catch (Exception e) {
-          log.error("上报成功移动文件失败", e);
-        }
-        // 清理缓存
-        FileConstant.uploadCountMap.remove(fileNameKey);
-        FileConstant.readyUploadFileMap.remove(fileNameKey);
-        FileConstant.fileShouldMomentMap.remove(fileNameKey);
-        FileConstant.fileContentMap.remove(fileNameKey);
-        FileConstant.againUploadFileMap.remove(fileNameKey);
-        FileConstant.filePackageNumMap.remove(fileNameKey);
-        log.info("上报对象编号:" + keys[0] + " 文件名:" + keys[2] + " 本次上报结果:成功");
-
-      } else {
-        // 保存上报失败明细表
-        UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-        uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-        uploadFileLogDetail.setUploadFileLogId(uploadFileLog.getId());
-        uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-        uploadFileLogDetail.setFileName(keys[2]);
-        uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-        uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-        uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E3);
-        uploadFileLogDetail.setUploadFailureReason(faileReason);
-        uploadFileLog.setFileStatusEnum(FileStatusEnum.E3);
-        uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter() + 1);
-        uploadFileLogRepository.save(uploadFileLog);
-        uploadFileLogDetailRepository.save(uploadFileLogDetail);
-
-        if (FileConstant.againUploadFileMap.get(fileNameKey) == null) {
-          // 遇到失败,再给这个文件一次上报的机会
-          FileConstant.againUploadFileMap.put(fileNameKey, "");
-          log.info(fileNameKey + "上报结果失败,再报一次变量中存入");
-        } else {
-          // 将文件移动到失败目录
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "error" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-          } catch (Exception e) {
-            log.error("将文件移动到失败目录", e);
-          }
-          FileConstant.readyUploadFileMap.remove(fileNameKey);
-          FileConstant.fileShouldMomentMap.remove(fileNameKey);
-          FileConstant.againUploadFileMap.remove(fileNameKey);
-        }
-        // 清理缓存
-        FileConstant.uploadCountMap.remove(fileNameKey);
-        FileConstant.fileContentMap.remove(fileNameKey);
-        FileConstant.filePackageNumMap.remove(fileNameKey);
-        log.info("上报对象编号:" + keys[0] + " 文件名:" + keys[2] + " 本次上报结果失败:" + faileReason);
-      }
-    }
-    else{
-      log.info("没有找到缓存里的文件,对象编号是:"+uploadObject.getObjectNo());
-    }
-  }
-
-  /**
-   * 读取文件内容转16进制报文
-   *
-   * @param filePath
-   * @param charsetName
-   * @return
-   */
-  public String createFileMessageHex(String filePath, String charsetName, Logger log) {
-    InputStreamReader isr = null;
-    String fileMessageHex = "";
-    try {
-      isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
-      StringBuffer sb = new StringBuffer("");
-      int len1 = 0;
-      while ((len1 = isr.read()) != -1) {
-        sb.append((char) len1);
-      }
-      isr.close();
-
-      String str = sb.toString();
-      fileMessageHex = ByteUtil.Byte2String(str.getBytes(charsetName));
-      fileMessageHex = fileMessageHex.replaceAll(" ", "");
-      ////////////////////以下注释生成本地文件/////////////////////
-//      int len = fileMessageHex.length();
-//      byte[] data = new byte[len / 2];
-//      for (
-//        int i = 0;
-//        i < len; i += 2) {
-//        data[i / 2] = (byte) ((Character.digit(fileMessageHex.charAt(i), 16) << 4)
-//          + Character.digit(fileMessageHex.charAt(i + 1), 16));
-//      }
-//      OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\sdf.PVD"), charsetName);
-//      String res = new String(data);
-//      osw.write(res);
-//      osw.close();
-    } catch (Exception e) {
-      log.error("读取本地文件失败", e);
-    } finally {
-      if (isr != null) {
-        try {
-          isr.close();
-        } catch (IOException e) {
-          e.printStackTrace();
-        }
-      }
-    }
-    return fileMessageHex;
-  }
-
-  /**
-   * 根据通道过滤缓存Map的key是否存在
-   *
-   * @param uploadObjectNo
-   * @param map
-   * @return
-   */
-  public Map<String, UploadFileLog> filterFileByObjectNo(String uploadObjectNo, Map<String, UploadFileLog> map, Logger log) {
-    Map<String, UploadFileLog> copyMap = new HashMap<>();
-    copyMap.putAll(map);
-    // 先过滤出上报对象下的所有文件
-    Map<String, UploadFileLog> filterMap = new HashMap<>();
-    Iterator<Map.Entry<String, UploadFileLog>> it = copyMap.entrySet().iterator();
-    while (it.hasNext()) {
-      Map.Entry<String, UploadFileLog> entry = it.next();
-      if (uploadObjectNo.equals(entry.getKey().substring(0, entry.getKey().indexOf("@")))) {
-        filterMap.put(entry.getKey(), entry.getValue());
-      }
-    }
-    // 再将失效时间的文件移除
-    Map<String, UploadFileLog> fileterFileMap = new HashMap<>();
-    Date d = new Date();
-    for (Map.Entry<String, UploadFileLog> entry : filterMap.entrySet()) {
-      UploadFileLog u = entry.getValue();
-      if (u.getUploadFileEndTime() == null) {
-        // 有效的文件
-        fileterFileMap.put(entry.getKey(), u);
-      } else {
-        if (d.getTime() <= u.getUploadFileEndTime()) {
-          // 有效的文件
-          fileterFileMap.put(entry.getKey(), u);
-        } else {
-          // 过期文件
-          String[] keys = new String[3];
-//          keys[0] = entry.getKey().substring(0,entry.getKey().indexOf("@",0));
-//          keys[1] = entry.getKey().substring(entry.getKey().indexOf("@",1)+1,entry.getKey().indexOf("@",2));
-//          keys[2] = entry.getKey().substring(entry.getKey().indexOf("@",2)+1);
-          keys[0] = entry.getKey().substring(0, entry.getKey().indexOf("@", 0));
-          String tempFileName = entry.getKey().substring(entry.getKey().indexOf("@", 0) + 1);
-          keys[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-          keys[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "expire" + File.separator + keys[0] + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-            log.info("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2]);
-          } catch (Exception e) {
-            log.error("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2] + "失败", e);
-          }
-          // 清理缓存
-          FileConstant.uploadCountMap.remove(entry.getKey());
-          FileConstant.againUploadFileMap.remove(entry.getKey());
-          FileConstant.readyUploadFileMap.remove(entry.getKey());
-          FileConstant.fileShouldMomentMap.remove(entry.getKey());
-          FileConstant.fileContentMap.remove(entry.getKey());
-        }
-      }
-    }
-    return fileterFileMap;
-  }
-
-  /**
-   * 获取文件CODE码
-   *
-   * @return
-   */
-  public Map<String, Integer> getFileCode() {
-    List<UploadFileCode> uploadFileCodeList = uploadFileCodeService.get();
-    Map<String, Integer> codeMap = new HashMap<>();
-    for (UploadFileCode uploadFileCode : uploadFileCodeList) {
-      codeMap.put(uploadFileCode.getFileTypeEnum().toString(), uploadFileCode.getFileTypeCode());
-    }
-    return codeMap;
-  }
-
-  /**
-   * 读取excel文件内容转16进制报文
-   *
-   * @param filePath
-   * @return
-   */
-  public String createFileMessageHexByExcel(String filePath, Logger log) {
-    String fileMessageHex = "";
-    try (
-      FileInputStream inputStream = new FileInputStream(new File(filePath));
-      ByteArrayOutputStream baos = new ByteArrayOutputStream();
-    ) {
-      Workbook workbook = WorkbookFactory.create(inputStream);
-      workbook.write(baos);// 临时存储流到内存
-      baos.flush();
-      fileMessageHex = ByteUtil.Byte2String(baos.toByteArray());
-      fileMessageHex = fileMessageHex.replaceAll(" ", "");
-      workbook.close();
-    } catch (Exception e) {
-      log.error("读取本地文件失败", e);
-    }
-    return fileMessageHex;
-  }
-}

+ 0 - 12
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/NettyParent.java

@@ -1,12 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-/**
- * 启动类抽象父类
- *
- * @author xsl
- * @version 3.0
- */
-public abstract class NettyParent {
-  public abstract void start();
-  public abstract void destroy();
-}

+ 0 - 135
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102Decoder.java

@@ -1,135 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import com.jiayue.ipfcst.fileupload.util.IEC102Uitl;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufUtil;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * 102解码器
- *
- * @author xsl
- * @version 3.0
- */
-@Slf4j
-public class ServerFor102Decoder extends SimpleChannelInboundHandler {
-  //记录上次未读完的字节
-  List<String> messageList = new ArrayList<String>();
-
-  @Autowired
-  AppenderFactory appenderFactory = SpringContextHolder.getApplicationContext().getBean(AppenderFactory.class);
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-
-  @Override
-  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    // 本地IP和端口
-    InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localAddress.getAddress().getHostAddress();
-    String localPort = String.valueOf(localAddress.getPort());
-    // 根据远端IP获取上报对象报文日志
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-    List<UploadFileChannel> uploadFileChannels = uploadFileChannelList.stream().filter(s -> s.getRemoteIp().equals(remoteIP)).collect(Collectors.toList());
-    if (uploadFileChannels.isEmpty()){
-      log.error("远端IP:"+remoteIP+"在通道中不存在,不接收对方内容!");
-      return;
-    }
-//    UploadFileChannel uploadFileChannel = uploadFileChannels.get(0);
-//    List<UploadObject> uploadObjectList = uploadObjectService.get();
-//    UploadObject uploadObject = uploadObjectList.stream().filter(s -> s.getId().equals(uploadFileChannel.getUploadObjectId())).collect(Collectors.toList()).get(0);
-
-    List<UploadObject> tempList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E1")).collect(Collectors.toList());
-    UploadObject uploadObject = null;
-    for (UploadFileChannel u:uploadFileChannelList){
-      if ((u.getLocalIp()!=null && u.getLocalPort()!=null) && u.getLocalIp().equals(localIp) && u.getLocalPort().equals(localPort) && u.getRemoteIp().equals(remoteIP)){
-        for (UploadObject ub:uploadObjectList){
-          if (u.getUploadObjectId()==ub.getId()){
-            uploadObject = ub;
-            break;
-          }
-        }
-      }
-    }
-
-    Logger uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(),uploadObject.getObjectNo());
-
-    try {
-      ByteBuf buf = (ByteBuf) msg;
-      String receiveStr = ByteBufUtil.hexDump(buf).toUpperCase();
-      List<String> receivesList = IEC102Uitl.stingToList(receiveStr);
-      messageList.addAll(receivesList);
-
-      // 至少6个以上字节才报文解码
-      if (messageList.size() >= 6) {
-        if (messageList.size()>300){
-          // 没用的太多了,舍弃掉
-          uploadLogger.info("没用字符串报文超过300个舍弃掉:"+messageList.toString());
-          messageList.clear();
-        }
-        else{
-          int zb = 0;
-          while (true) {
-            String nextMessage = "";
-            for (int k = 0; k < messageList.size(); k++) {
-              if ("10".equals(messageList.get(k)) && (k + 5) <= messageList.size() && messageList.get(k + 5).equals("16")) {
-                List newList = messageList.subList(k, (k + 6));
-                nextMessage = String.join("", newList);
-                String tempStr = String.join("", messageList).substring((k + 6) * 2);
-                messageList.clear();
-                messageList = IEC102Uitl.stingToList(tempStr);
-                break;
-              }
-              if ("68".equals(messageList.get(k)) && (k + 3) <= messageList.size() && messageList.get(k + 3).equals("68")) {
-                int tempLength = ByteUtil.hexToDec(messageList.get(k + 2) + messageList.get(k + 1));
-                int end16 = (k + 3) + tempLength + 2;
-                if (end16 <= messageList.size() && messageList.get(end16).equals("16")) {
-                  List newList = messageList.subList(k, (end16 + 1));
-                  nextMessage = String.join("", newList);
-                  String tempStr = String.join("", messageList).substring((end16 + 1) * 2);
-                  messageList.clear();
-                  messageList = IEC102Uitl.stingToList(tempStr);
-                  break;
-                }
-              }
-            }
-            if (!"".equals(nextMessage)) {
-              if (zb==1){
-                uploadLogger.info("获取到粘包帧:"+nextMessage);
-              }
-              zb++;
-              ctx.fireChannelRead(nextMessage);
-            }
-            else {
-              break;
-            }
-          }
-        }
-      }
-    }
-    catch (Exception e){
-      uploadLogger.error("解码失败",e);
-    }
-  }
-}

+ 0 - 22
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102Encoder.java

@@ -1,22 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.MessageToByteEncoder;
-import lombok.extern.slf4j.Slf4j;
-
-import java.math.BigInteger;
-
-/**
- * 102编码器
- *
- * @author xsl
- * @version 3.0
- */
-public class ServerFor102Encoder extends MessageToByteEncoder<String> {
-    @Override
-    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
-      BigInteger bigint=new BigInteger(msg, 16);
-      out.writeBytes(bigint.toByteArray());
-    }
-}

+ 0 - 37
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102InitChannel.java

@@ -1,37 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import ch.qos.logback.classic.Logger;
-import io.netty.buffer.UnpooledByteBufAllocator;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.handler.timeout.IdleStateHandler;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * netty服务端初始化
- *
- * @author xsl
- * @version 3.0
- */
-public class ServerFor102InitChannel extends ChannelInitializer<SocketChannel> {
-  private int readerIdleTime;
-
-  ServerFor102InitChannel(Integer readerIdleTime) {
-    this.readerIdleTime = readerIdleTime;
-  }
-
-  @Override
-  protected void initChannel(SocketChannel socketChannel) throws Exception {
-    socketChannel.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
-    socketChannel.pipeline().addLast(new IdleStateHandler(
-      readerIdleTime,
-      0,
-      0,
-      TimeUnit.SECONDS));
-    //添加编解码
-    socketChannel.pipeline().addLast("decoder", new ServerFor102Decoder());
-    socketChannel.pipeline().addLast("encoder", new ServerFor102Encoder());
-    socketChannel.pipeline().addLast(new ServerFor102TransitHandler(readerIdleTime));
-  }
-}

+ 0 - 420
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102NMService.java

@@ -1,420 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import cn.hutool.core.map.MapUtil;
-import cn.hutool.core.util.ArrayUtil;
-import cn.hutool.core.util.StrUtil;
-import com.jiayue.ipfcst.common.data.entity.ElectricField;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.fileupload.dto.Validate102Dto;
-import com.jiayue.ipfcst.fileupload.util.*;
-import io.netty.channel.ChannelHandlerContext;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.slf4j.Logger;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.io.*;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 102内蒙服务端业务处理类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class ServerFor102NMService extends Base102Service {
-  @Transactional(propagation = Propagation.REQUIRED)
-  public String handlerMessage(String receiveMessage, UploadObject uploadObject, UploadFileChannel uploadFileChannel, ElectricField electricField, Logger log,ChannelHandlerContext ctx) {
-    String[] rmArray = IEC102Uitl.stingToArray(receiveMessage);
-    String sendMessage = "";
-    String sendCtrlChinese = "";
-    String receiveCtrlChinese = "";
-
-    if (FileConstant.validateMessage.get(uploadFileChannel.getId()+"")!=null){
-      // 需要校验接收的帧是否正确
-      Validate102Dto validate102Dto = FileConstant.validateMessage.get(uploadFileChannel.getId()+"");
-      if (!validate102Dto.getMessageFirst().equals(rmArray[0])){
-        log.info(ctx.channel().remoteAddress()+" - "+"调度应该传"+validate102Dto.getMessageFirst()+"帧并且原因是"+validate102Dto.getMessageReason()+",实际传"+IEC102Uitl.delimiterStringBySpace(receiveMessage)+",断开通道重启");
-//        channelCloseConnect(ctx,uploadObject,uploadFileChannel);
-        log.info("接收到不正确帧,继续等待正确");
-        return "";
-      }
-    }
-
-    if ("10".equals(rmArray[0])) {
-      // 获取控制域,根据功能码判断业务流
-      String fc = rmArray[1].substring(1);
-      if (FileConstant.validateMessage.get(uploadFileChannel.getId()+"")!=null){
-        // 需要校验接收的帧是否正确
-        Validate102Dto validate102Dto = FileConstant.validateMessage.get(uploadFileChannel.getId()+"");
-        if (!fc.equals(validate102Dto.getMessageReason())){
-          log.info(ctx.channel().remoteAddress()+" - "+"调度应该传10原因是"+validate102Dto.getMessageReason()+",实际传"+IEC102Uitl.delimiterStringBySpace(receiveMessage)+",断开通道重启");
-//          channelCloseConnect(ctx,uploadObject,uploadFileChannel);
-          log.info("10帧接收到不正确帧,继续等待正确");
-          return "";
-        }
-      }
-
-      if ("0".equals(fc)) {
-        receiveCtrlChinese = "复位通信";
-        // 回复链路
-        sendMessage = makeMessage10("00");
-        sendCtrlChinese = "确认复位";
-      } else if ("9".equals(fc)) {
-        receiveCtrlChinese = "召唤链路";
-        // 回复链路
-        sendMessage = makeMessage10("0B");
-        sendCtrlChinese = "回应链路请求帧";
-      } else if ("A".equals(fc)) {
-        receiveCtrlChinese = "召唤一级数据";
-        // 先判断文件上报次数累计的缓存变量是否存在
-        Map<String, FileMutableInteger> filterMap = FileConstant.uploadCountMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))))
-          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-        // 上报文件名
-        String fileNameKey = "";
-        String typeSign = "";
-        if (MapUtil.isNotEmpty(filterMap)) {
-          sendCtrlChinese = "子站向主站传输文件内容";
-          // 不是第一次要文件了
-          for (Map.Entry<String, FileMutableInteger> entry : filterMap.entrySet()) {
-            fileNameKey = entry.getKey();
-            log.info(ctx.channel().remoteAddress()+" - "+"上传文件===>"+entry.getKey());
-            typeSign = "199";
-            break;
-          }
-        } else {
-          sendCtrlChinese = "子站向主站传输基本文件信息";
-          // 从待上报的缓存中取一个文件放入次数变量中
-          Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-          for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-            // 从待上报缓存中取一个加入到统计变量中
-            FileMutableInteger fileMutableInteger = new FileMutableInteger(0);
-            FileConstant.uploadCountMap.put(entry.getKey(), fileMutableInteger);
-            log.info(ctx.channel().remoteAddress()+" - "+"找到文件===>"+entry.getKey());
-            fileNameKey = entry.getKey();
-            typeSign = "198";
-            break;
-          }
-          Validate102Dto dto = new Validate102Dto();
-          dto.setMessageFirst("68");
-          dto.setMessageReason("07,0D");
-          FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-        }
-        if ("".equals(fileNameKey)) {
-          sendCtrlChinese = "不正常的回复";
-          sendMessage = "1000FFFFFE16";
-          log.info(ctx.channel().remoteAddress()+" - "+"主站不正常的调用,导致取不到文件无法上报");
-        } else {
-          // 生成传输文件的68帧
-          sendMessage = uploadFile68(typeSign, fileNameKey, electricField, uploadObject, uploadFileChannel, log);
-        }
-      } else if ("B".equals(fc)) {
-        receiveCtrlChinese = "召唤二级数据";
-        // 获取此通道下的上报文件
-        Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-
-        if (MapUtil.isNotEmpty(readyUploadFileMap)) {
-          // 文件缓存中有上报文件
-          sendMessage = makeMessage10("29");
-          sendCtrlChinese = "希望向主站传输一级数据";
-          Validate102Dto dto = new Validate102Dto();
-          dto.setMessageFirst("10");
-          dto.setMessageReason("A");
-          FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-        } else {
-          // 没有文件
-          sendMessage = makeMessage10("09");
-          sendCtrlChinese = "没有文件需要上报";
-          Validate102Dto dto = new Validate102Dto();
-          dto.setMessageFirst("10");
-          dto.setMessageReason("B");
-          FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-        }
-      }
-    } else {
-      // 68开头报文判断传输原因
-      String cot = rmArray[9];
-      if ("07".equals(cot)) {
-        receiveCtrlChinese = "主站允许本次文件请求";
-        sendMessage = "1020FFFF1E16";
-        sendCtrlChinese = "确认有一级数据";
-        Validate102Dto dto = new Validate102Dto();
-        dto.setMessageFirst("10");
-        dto.setMessageReason("A");
-        FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-      } else {
-        if ("0A".equals(cot)) {
-          // 上报成功
-          receiveCtrlChinese = "文件成功接收结束";
-          super.totalFileUploadNums(uploadObject, uploadFileChannel, "", log);
-        } else {
-          // 上报失败
-          receiveCtrlChinese = "error";
-          if ("0D".equals(cot)) {
-            receiveCtrlChinese = "文件重复传输";
-          } else if ("0B".equals(cot)) {
-            receiveCtrlChinese = "文件名错误";
-          } else if ("0C".equals(cot)) {
-            receiveCtrlChinese = "文件过大(大于1MB)";
-          } else if ("0E".equals(cot)) {
-            receiveCtrlChinese = "文件类型错误";
-          } else if ("10".equals(cot)) {
-            receiveCtrlChinese = "文件接收错误(长度、MD5校验等),发送方准备重新传输该文件";
-          }
-          super.totalFileUploadNums(uploadObject, uploadFileChannel, receiveCtrlChinese, log);
-        }
-        sendCtrlChinese = "对上一条命令确认";
-        sendMessage = "1000FFFFFE16";
-        Validate102Dto dto = new Validate102Dto();
-        dto.setMessageFirst("10");
-        dto.setMessageReason("B");
-        FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-      }
-    }
-    log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-    log.info(ctx.channel().remoteAddress()+" - "+"发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage));
-    return sendMessage;
-  }
-
-  /**
-   * 生成10帧报文
-   * 格式说明:10|控制域|地址低字节|地址高字节|校验和|16
-   *
-   * @param ctrl 控制域字节
-   * @return 10帧报文
-   */
-  private String makeMessage10(String ctrl) {
-    String[] returnMessage = {"10", "ctrl", "FF", "FF", "crc", "16"};
-    String crc = IEC102Uitl.makeChecksum(ctrl + returnMessage[2] + returnMessage[3]);
-    returnMessage[1] = ctrl;
-    returnMessage[4] = crc;
-    String sendMessage = ArrayUtil.join(returnMessage, "");
-    return sendMessage.toUpperCase();
-  }
-
-  /**
-   * 传输文件的68帧报文
-   * crc校验和:从[控制域]到[校验和]之前
-   * 帧长:从[控制域]到[校验和]之前所有字节数
-   *
-   * @return 68帧报文
-   */
-  private String uploadFile68(String typeSign, String fileNameKey, ElectricField electricField, UploadObject uploadObject, UploadFileChannel uploadFileChannel, Logger log) {
-    String[] tempKey = new String[3];
-    tempKey[0] = fileNameKey.substring(0,fileNameKey.indexOf("@",0));
-    tempKey[1] = fileNameKey.substring(fileNameKey.indexOf("@",1)+1,fileNameKey.indexOf("@",2));
-    tempKey[2] = fileNameKey.substring(fileNameKey.indexOf("@",2)+1);
-    String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-    String sendMessage = "";
-    // 获取本地物理文件路径
-    String filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + tempKey[0] + File.separator + tempKey[1] + File.separator + tempKey[2];
-
-    if ("198".equals(typeSign)) {
-      // 子站向主站传输文件基本信息(68|帧长低字节|帧长高字节|68|控制域|地址低字节|地址高字节|类型标识|可变限定词|传输原因|设备地址低字节|设备地址高字节|记录地址|文件名字节|文件类型|文件长度|文件内容MD5数字签名|校验和|16)
-      String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "28", "FF", "FF", "C6", "01", "06", "FF", "FF", "00", "fileNameByte", "fileType", "fileContentAllLength", "fileContentMD5", "crc", "16"};
-      // 生成文件名
-      String fileName = tempKey[2];
-      byte[] tempFileNameBytes = null;
-      try {
-        tempFileNameBytes = fileName.getBytes(charsetName);
-      } catch (Exception e) {
-        log.error("转换文件名编码失败", e);
-      }
-      // 获取文件名称长度
-      String fileNameLength = uploadFileChannel.getUploadFileNameLengthEnum().getMessage();
-      String fileNameByte = ByteUtil.Byte2String(tempFileNameBytes);
-      returnMessage[13] = StrUtil.padAfter(fileNameByte.replace(" ", ""), Integer.parseInt(fileNameLength) * 2, '0');
-      // 生成类型标识
-      Map<String, Integer> codeMap = super.getFileCode();
-      returnMessage[14] = Integer.toHexString(codeMap.get(tempKey[1]));
-      String fileContentByte = "";
-      String tempContent = "";
-      try {
-        fileContentByte = nmCreateFileMessageHex(filePath, log, uploadObject.getId(), fileNameKey);
-        tempContent = new String(fileContentByte);
-        fileContentByte = ByteUtil.Byte2String(fileContentByte.getBytes(charsetName));
-      } catch (FileNotFoundException e) {
-        log.error("没找到文件", e);
-        totalFileUploadNums(uploadObject, uploadFileChannel, e.toString(), log);
-      } catch (Exception e) {
-        log.error("读取本地文件失败", e);
-        totalFileUploadNums(uploadObject, uploadFileChannel, e.toString(), log);
-      }
-      fileContentByte = fileContentByte.replaceAll(" ", "");
-      returnMessage[15] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(fileContentByte.length() / 2));
-      try {
-        returnMessage[16] = FileUtil.getMD5(tempContent.getBytes(charsetName));
-      } catch (Exception e) {
-        log.error("文件内容加密MD5失败", e);
-      }
-      // 计算校验和,获取从[控制域]到[校验和]之前的报文
-      StringBuffer tempSB = new StringBuffer("");
-      for (int i = 4; i <= 16; i++) {
-        tempSB.append(returnMessage[i]);
-      }
-      returnMessage[17] = IEC102Uitl.makeChecksum(tempSB.toString());
-      // 计算报文的帧长
-      String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-      String mlLow = ml.substring(0, 2);
-      String mlHeight = ml.substring(2);
-      returnMessage[1] = mlLow;
-      returnMessage[2] = mlHeight;
-      sendMessage = ArrayUtil.join(returnMessage, "");
-    } else {
-      // 子站向主站传输文件内容(68|帧长低字节|帧长高字节|68|控制域|地址低字节|地址高字节|类型标识|可变限定词|传输原因|设备地址低字节|设备地址高字节|记录地址|文件内容在文件的起始地址|本帧文件数据长度|文件数据|校验和|16)
-      String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "ctrl", "FF", "FF", "C7", "01", "reason", "FF", "FF", "00", "fileContentStartIndex", "fileContentLength", "fileContentByte", "crc", "16"};
-      String fileContentStartIndex = "";
-      // 获取缓存中文件内容
-      Map<String, String> fileContentMap = new HashMap<>();
-
-      String fileContentByte = "";
-      if (FileConstant.fileContentByIdxMap.get(fileNameKey) == null) {
-        // 缓存中没有文件内容则新生成文件内容报文
-        try {
-          fileContentByte = nmCreateFileMessageHex(filePath, log, uploadObject.getId(), fileNameKey);
-          fileContentByte = ByteUtil.Byte2String(fileContentByte.getBytes(charsetName));
-        } catch (FileNotFoundException e) {
-          log.error("没找到文件", e);
-          totalFileUploadNums(uploadObject, uploadFileChannel, e.toString(), log);
-        } catch (Exception e) {
-          log.error("读取本地文件失败", e);
-          totalFileUploadNums(uploadObject, uploadFileChannel, e.toString(), log);
-        }
-        fileContentByte = fileContentByte.replaceAll(" ", "");
-        fileContentMap.put("contentByteIdx", "0");
-      } else {
-        fileContentMap = FileConstant.fileContentByIdxMap.get(fileNameKey);
-        fileContentByte = fileContentMap.get("fileContent");
-      }
-      // 获取通道单次文件传输字节
-      String singleByte = uploadFileChannel.getUploadFileSingleByteEnum().getMessage();
-      String ctrl = "";
-      String reason = "";
-      if (fileContentByte.length() <= Integer.parseInt(singleByte) * 2) {
-        // 一次可以传输完,生成控制域码
-        ctrl = "08";
-        reason = "08";
-
-        Integer idx = Integer.parseInt(fileContentMap.get("contentByteIdx"));
-        if (idx != 0) {
-          idx = idx + 1;
-        }
-        fileContentStartIndex = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(idx));
-        FileConstant.fileContentByIdxMap.remove(fileNameKey);
-        Validate102Dto dto = new Validate102Dto();
-        dto.setMessageFirst("68");
-        dto.setMessageReason("0A");
-        FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-      } else {
-        // 生成不是最后一帧控制域码
-        ctrl = "28";
-        reason = "09";
-        // 将剩余的文件内容报文存入缓存中
-        Map<String, String> tempContentMap = new HashMap<>();
-        tempContentMap.put("fileContent", fileContentByte.substring(Integer.parseInt(singleByte) * 2));
-        // 上次字节结束的位置
-        Integer lastIdx = Integer.parseInt(fileContentMap.get("contentByteIdx"));
-        if (lastIdx == 0) {
-          tempContentMap.put("contentByteIdx", String.valueOf(Integer.parseInt(singleByte) - 1));
-          fileContentStartIndex = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(0));
-        } else {
-          tempContentMap.put("contentByteIdx", String.valueOf(lastIdx + Integer.parseInt(singleByte)));
-          fileContentStartIndex = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(lastIdx + 1));
-        }
-        FileConstant.fileContentByIdxMap.put(fileNameKey, tempContentMap);
-        fileContentByte = fileContentByte.substring(0, Integer.parseInt(singleByte) * 2);
-
-        Validate102Dto dto = new Validate102Dto();
-        dto.setMessageFirst("10");
-        dto.setMessageReason("A");
-        FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
-      }
-
-      returnMessage[4] = ctrl;
-      returnMessage[9] = reason;
-      returnMessage[13] = fileContentStartIndex;
-      returnMessage[14] = ByteUtil.decToHex(fileContentByte.length() / 2);
-      returnMessage[15] = fileContentByte;
-
-      // 计算校验和,获取从[控制域]到[校验和]之前的报文
-      StringBuffer tempSB = new StringBuffer("");
-      for (int i = 4; i <= 15; i++) {
-        tempSB.append(returnMessage[i]);
-      }
-      returnMessage[16] = IEC102Uitl.makeChecksum(tempSB.toString());
-      // 计算报文的帧长
-      String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-      String mlLow = ml.substring(0, 2);
-      String mlHeight = ml.substring(2);
-      returnMessage[1] = mlLow;
-      returnMessage[2] = mlHeight;
-      sendMessage = ArrayUtil.join(returnMessage, "");
-    }
-    return sendMessage.toUpperCase();
-  }
-
-
-  /**
-   * 读取文件内容转16进制报文
-   *
-   * @param filePath
-   * @param log
-   * @return
-   */
-  private String nmCreateFileMessageHex(String filePath, Logger log, Integer uploadObjectId, String fileNameKey) throws Exception {
-    InputStreamReader isr = null;
-    String fileMessageHex = "";
-    try {
-      isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
-      StringBuffer sb = new StringBuffer("");
-      int len1 = 0;
-      while ((len1 = isr.read()) != -1) {
-        sb.append((char) len1);
-      }
-      isr.close();
-      fileMessageHex = sb.toString();
-    } catch (Exception e) {
-      log.error("没找到文件", e);
-      throw e;
-    } finally {
-      if (isr != null) {
-        try {
-          isr.close();
-        } catch (IOException e) {
-          e.printStackTrace();
-        }
-      }
-    }
-    return fileMessageHex;
-  }
-
-  public void channelCloseConnect(ChannelHandlerContext ctx,UploadObject uploadObject,UploadFileChannel uploadFileChannel){
-    // 传输帧类型不对,断开通道重启
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
-      Map.Entry<String,FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        countMap.remove();
-      }
-    }
-
-    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-    while (contentMap.hasNext()){
-      Map.Entry<String,String> entry = contentMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        contentMap.remove();
-      }
-    }
-    FileConstant.validateMessage.remove(uploadFileChannel.getId()+"");
-    ctx.close();
-  }
-}
-

+ 0 - 396
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102StandardService.java

@@ -1,396 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import cn.hutool.core.map.MapUtil;
-import cn.hutool.core.util.ArrayUtil;
-import cn.hutool.core.util.StrUtil;
-import com.jiayue.ipfcst.common.data.entity.ElectricField;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.fileupload.dto.Validate102Dto;
-import com.jiayue.ipfcst.fileupload.util.*;
-import io.netty.channel.ChannelHandlerContext;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-/**
- * 102服务端业务处理类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class ServerFor102StandardService extends Base102Service {
-  @Transactional(propagation = Propagation.REQUIRED)
-  public synchronized String handlerMessage(String receiveMessage, UploadObject uploadObject, UploadFileChannel uploadFileChannel, ElectricField electricField, Logger log, ChannelHandlerContext ctx) {
-    String[] rmArray = IEC102Uitl.stingToArray(receiveMessage);
-    String sendMessage = "";
-    String sendCtrlChinese = "";
-    String receiveCtrlChinese = "";
-
-    if (FileConstant.validateMessage.get(uploadFileChannel.getId() + "") != null) {
-      // 需要校验接收的帧是否正确
-      Validate102Dto validate102Dto = FileConstant.validateMessage.get(uploadFileChannel.getId() + "");
-      if (!validate102Dto.getMessageFirst().equals(rmArray[0])) {
-        log.info(ctx.channel().remoteAddress() + " - " + "调度应该传" + validate102Dto.getMessageFirst() + "帧并且原因是" + validate102Dto.getMessageReason() + ",实际传" + IEC102Uitl.delimiterStringBySpace(receiveMessage) + ",断开通道重启");
-//        super.totalFileUploadNums(uploadObject,uploadFileChannel, "调度应该传"+validate102Dto.getMessageFirst()+"帧,实际传"+IEC102Uitl.delimiterStringBySpace(receiveMessage), log);
-        if ("10".equals(rmArray[0])) {
-          channelCloseConnect(ctx, uploadObject, uploadFileChannel);
-          return "";
-        } else if ("68".equals(rmArray[0])) {
-          if (!"0A".equals(rmArray[9])) {
-            channelCloseConnect(ctx, uploadObject, uploadFileChannel);
-            return "";
-          }
-        }
-      }
-    }
-
-    if ("10".equals(rmArray[0])) {
-      // 获取控制域,根据功能码判断业务流
-      String fc = rmArray[1].substring(1);
-
-      if (FileConstant.validateMessage.get(uploadFileChannel.getId() + "") != null) {
-        // 需要校验接收的帧是否正确
-        Validate102Dto validate102Dto = FileConstant.validateMessage.get(uploadFileChannel.getId() + "");
-        if (!"".equals(validate102Dto.getMessageReason())) {
-          if (!fc.equals(validate102Dto.getMessageReason())) {
-            log.info(ctx.channel().remoteAddress() + " - " + "调度应该传10原因是" + validate102Dto.getMessageReason() + ",实际传" + IEC102Uitl.delimiterStringBySpace(receiveMessage) + ",断开通道重启");
-            channelCloseConnect(ctx, uploadObject, uploadFileChannel);
-            return "";
-          }
-        }
-      }
-
-      if ("0".equals(fc)) {
-        receiveCtrlChinese = "复位通信";
-        // 回复链路
-        sendMessage = makeMessage10("00");
-        sendCtrlChinese = "确认复位";
-        // xsl 2024.3.8增加开关用于是否继续读取上次未完成的文件帧(ON 继续上次读取  OFF  不继续上次读取)
-        String cfrVal = sysParameterService.getSysParameter("CFR","OFF");
-        if ("OFF".equals(cfrVal)) {
-          // 清除对应缓存
-          Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-          while (countMap.hasNext()) {
-            Map.Entry<String, FileMutableInteger> entry = countMap.next();
-            String key = entry.getKey();
-            if (key.substring(0, key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-              countMap.remove();
-            }
-          }
-          Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-          while (contentMap.hasNext()) {
-            Map.Entry<String, String> entry = contentMap.next();
-            String key = entry.getKey();
-            if (key.substring(0, key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-              contentMap.remove();
-            }
-          }
-        }
-      } else if ("3".equals(fc)) {
-        receiveCtrlChinese = "传送数据";
-      } else if ("9".equals(fc)) {
-        receiveCtrlChinese = "召唤链路";
-        // 回复链路
-        sendMessage = makeMessage10("0B");
-        sendCtrlChinese = "回应链路请求帧";
-      } else if ("A".equals(fc)) {
-        receiveCtrlChinese = "召唤一级数据";
-        // 先判断文件上报次数累计的缓存变量是否存在
-        Map<String, FileMutableInteger> filterMap = FileConstant.uploadCountMap.entrySet().stream().filter(r -> Integer.parseInt(uploadObject.getObjectNo()) == Integer.parseInt(r.getKey().substring(0, r.getKey().indexOf("@"))))
-          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-        // 上报文件名
-        String fileNameKey = "";
-        if (MapUtil.isNotEmpty(filterMap)) {
-          // 不是第一次要文件了
-          for (Map.Entry<String, FileMutableInteger> entry : filterMap.entrySet()) {
-            fileNameKey = entry.getKey();
-            log.info(ctx.channel().remoteAddress() + " - " + "上传文件===>" + entry.getKey());
-            break;
-          }
-        } else {
-          // 从待上报的缓存中取一个文件放入次数变量中
-          Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-          for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-            // 从待上报缓存中取一个加入到累计次数变量中
-            FileMutableInteger fileMutableInteger = new FileMutableInteger(0);
-            FileConstant.uploadCountMap.put(entry.getKey(), fileMutableInteger);
-            log.info(ctx.channel().remoteAddress() + " - " + "找到文件===>" + entry.getKey());
-            fileNameKey = entry.getKey();
-            break;
-          }
-        }
-        if ("".equals(fileNameKey)) {
-          sendCtrlChinese = "没有找到上报文件";
-          sendMessage = makeMessage10("09");
-          FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
-        } else {
-          // 生成传输文件的68帧
-          sendMessage = uploadFile68(fileNameKey, electricField, uploadObject, uploadFileChannel, log);
-          sendCtrlChinese = "通道:" + uploadFileChannel.getChannelName() + "上报:" + fileNameKey;
-        }
-      } else if ("B".equals(fc)) {
-        receiveCtrlChinese = "召唤二级数据";
-        // 获取此通道下的上报文件
-        Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-
-        if (MapUtil.isNotEmpty(readyUploadFileMap)) {
-          // 文件缓存中有上报文件
-          sendMessage = makeMessage10("29");
-          sendCtrlChinese = "希望向主站传输一级数据";
-          Validate102Dto dto = new Validate102Dto();
-          dto.setMessageFirst("10");
-          dto.setMessageReason("A");
-          FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
-        } else {
-          // 没有文件
-          sendMessage = makeMessage10("09");
-          sendCtrlChinese = "没有文件需要上报";
-          Validate102Dto dto = new Validate102Dto();
-          dto.setMessageFirst("10");
-          dto.setMessageReason("B");
-          FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
-        }
-      } else if ("C".equals(fc)) {
-        receiveCtrlChinese = "下发数据通知";
-      }
-      log.info(ctx.channel().remoteAddress() + " - " + "接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-    } else {// 68开头报文
-      // 判断传输原因
-      String cot = rmArray[9];
-      String[] send68Array = ArrayUtil.clone(rmArray);
-      if ("E34".equals(electricField.getProvinceEnum().toString())){
-        // 针对安徽升级,修改控制域为00
-        send68Array[4] = "00";
-      }
-      if ("0A".equals(cot)) {
-        receiveCtrlChinese = "文件接收结束";
-        send68Array[9] = "0B";
-        // 计算校验和
-        String tempStr = StringUtils.join(send68Array, "");
-        String crc = IEC102Uitl.makeChecksum(tempStr.substring(8, 34));
-        send68Array[17] = crc;
-        sendCtrlChinese = "确认文件传输结束";
-        log.info(ctx.channel().remoteAddress() + " - " + "接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-        super.totalFileUploadNums(uploadObject, uploadFileChannel, "", log);
-        // 文件状态成功
-        sendMessage = ArrayUtil.join(send68Array, "");
-      } else {
-        // 文件状态失败
-        if ("0D".equals(cot)) {
-          receiveCtrlChinese = "文件重复传输";
-          send68Array[9] = "0E";
-          // 计算校验和
-          String tempStr = StringUtils.join(send68Array, "");
-          String crc = IEC102Uitl.makeChecksum(tempStr.substring(8, 26));
-          send68Array[13] = crc;
-          sendCtrlChinese = "确认文件重复传输";
-        } else if ("0F".equals(cot)) {
-          receiveCtrlChinese = "文件长度超出规定最大长度";
-          send68Array[9] = "10";
-          // 计算校验和
-          String tempStr = StringUtils.join(send68Array, "");
-          String crc = IEC102Uitl.makeChecksum(tempStr.substring(8, 26));
-          send68Array[13] = crc;
-          sendCtrlChinese = "确认传输文件过长";
-        } else if ("11".equals(cot)) {
-          receiveCtrlChinese = "文件名格式不符合要求";
-          send68Array[9] = "12";
-          // 计算校验和
-          String tempStr = StringUtils.join(send68Array, "");
-          String crc = IEC102Uitl.makeChecksum(tempStr.substring(8, 26));
-          send68Array[13] = crc;
-          sendCtrlChinese = "确认文件名格式不符合要求";
-        } else if ("13".equals(cot)) {
-          receiveCtrlChinese = "传输单帧报文长度过长";
-          send68Array[9] = "14";
-          // 计算校验和
-          String tempStr = StringUtils.join(send68Array, "");
-          String crc = IEC102Uitl.makeChecksum(tempStr.substring(8, 26));
-          send68Array[13] = crc;
-          sendCtrlChinese = "确认单帧报文长度过长";
-        } else {
-          receiveCtrlChinese = "接收的内容程序没做判断";
-          sendCtrlChinese = "不是正常的报文回复内容";
-        }
-        log.info(ctx.channel().remoteAddress() + " - " + "接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-        super.totalFileUploadNums(uploadObject, uploadFileChannel, sendCtrlChinese, log);
-        sendMessage = ArrayUtil.join(send68Array, "");
-      }
-      Validate102Dto dto = new Validate102Dto();
-      dto.setMessageFirst("10");
-      dto.setMessageReason("");
-      FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
-    }
-    log.info(ctx.channel().remoteAddress() + " - " + "发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage));
-    return sendMessage;
-  }
-
-  /**
-   * 生成10帧报文
-   * 格式说明:10|控制域|地址低字节|地址高字节|校验和|16
-   *
-   * @param ctrl 控制域字节
-   * @return 10帧报文
-   */
-  private synchronized String makeMessage10(String ctrl) {
-    String[] returnMessage = {"10", "ctrl", "FF", "FF", "crc", "16"};
-    String crc = IEC102Uitl.makeChecksum(ctrl + returnMessage[2] + returnMessage[3]);
-    returnMessage[1] = ctrl;
-    returnMessage[4] = crc;
-    String sendMessage = ArrayUtil.join(returnMessage, "");
-    return sendMessage.toUpperCase();
-  }
-
-  /**
-   * 传输文件的68帧报文
-   * 格式说明:68|帧长低字节|帧长高字节|68|控制域|地址低字节|地址高字节|类型标识|可变限定词|传输原因|设备地址低字节|设备地址高字节|记录地址|文件名字节|文件内容字节|校验和|16
-   * crc校验和:从[控制域]到[校验和]之前
-   * 帧长:从[控制域]到[校验和]之前所有字节数
-   *
-   * @return 68帧报文
-   */
-  private synchronized String uploadFile68(String fileNameKey, ElectricField electricField, UploadObject uploadObject, UploadFileChannel uploadFileChannel, Logger log) {
-    String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "ctrl", "FF", "FF", "typeCode", "01", "reason", "FF", "FF", "00", "fileNameByte", "fileContentByte", "crc", "16"};
-    String[] tempKey = new String[3];
-    String tempFileName = fileNameKey;
-    tempKey[0] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-    tempFileName = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-    tempKey[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-    tempKey[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-
-    // 生成文件名及内容
-    String fileName = tempKey[2];
-    byte[] tempFileNameBytes = null;
-    String charsetName;
-    if ("E42".equals(electricField.getProvinceEnum().toString()) && ("E9".equals(tempKey[1]) || "E74".equals(tempKey[1]) || "E92".equals(tempKey[1]))) {
-      // 湖北省新风机文件用GBK上报,其他用UTF-8
-      charsetName = "GBK";
-    } else {
-      charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-    }
-    try {
-      tempFileNameBytes = fileName.getBytes(charsetName);
-    } catch (Exception e) {
-      log.error("转换文件名编码失败", e);
-    }
-    // 获取文件名称长度
-    String fileNameLength = uploadFileChannel.getUploadFileNameLengthEnum().getMessage();
-    String fileNameByte = ByteUtil.Byte2String(tempFileNameBytes);
-    fileNameByte = StrUtil.padAfter(fileNameByte.replace(" ", ""), Integer.parseInt(fileNameLength) * 2, '0');
-    // 获取本地物理文件路径
-    String filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + tempKey[0] + File.separator + tempKey[1] + File.separator + tempKey[2];
-
-    String fileContentByte = FileConstant.fileContentMap.get(fileNameKey);
-    if (StrUtil.hasBlank(fileContentByte)) {
-      if ("E13".equals(electricField.getProvinceEnum().toString()) && ("E206".equals(tempKey[1]) || "E207".equals(tempKey[1]))) {
-        fileContentByte = super.createFileMessageHexByExcel(filePath, log);
-      }
-      else{
-        // 缓存中没有文件内容则新生成文件内容报文
-        fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-      }
-    }
-    // 生成不是最后一帧控制域码
-    String ctrl = "28";
-    String reason = "08";
-    // 获取通道单次文件传输字节
-    String singleByte = uploadFileChannel.getUploadFileSingleByteEnum().getMessage();
-    if (fileContentByte.length() <= Integer.parseInt(singleByte) * 2) {
-      // 一次可以传输完,生成控制域码
-      ctrl = "08";
-      reason = "07";
-
-      Validate102Dto dto = new Validate102Dto();
-      dto.setMessageFirst("68");
-      dto.setMessageReason("0A");
-      FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
-
-    } else {
-      // 将剩余的文件内容报文存入缓存中
-      FileConstant.fileContentMap.put(fileNameKey, fileContentByte.substring(Integer.parseInt(singleByte) * 2));
-      fileContentByte = fileContentByte.substring(0, Integer.parseInt(singleByte) * 2);
-
-//      Validate102Dto dto = new Validate102Dto();
-//      dto.setMessageFirst("10");
-//      dto.setMessageReason("A");
-      FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
-    }
-    // 生成类型标识
-//    List<UploadFileCode> uploadFileCodeList = uploadFileCodeService.get();
-
-    Map<String, Integer> codeMap = super.getFileCode();
-    String typeCode = "";
-    if ("E37".equals(electricField.getProvinceEnum().toString())) {
-      Map<String, Integer> tempMap = new HashMap<>();
-      // 山东
-      for (Map.Entry<String, Integer> entry : codeMap.entrySet()) {
-        if (entry.getKey().equals("E131") || entry.getKey().equals("E132") || entry.getKey().equals("E133") || entry.getKey().equals("E134") || entry.getKey().equals("E135") || entry.getKey().equals("E136") || entry.getKey().equals("E137") || entry.getKey().equals("E138") || entry.getKey().equals("E139") || entry.getKey().equals("E140") || entry.getKey().equals("E331") || entry.getKey().equals("E332") || entry.getKey().equals("E333") || entry.getKey().equals("E334") || entry.getKey().equals("E335") || entry.getKey().equals("E336") || entry.getKey().equals("E337") || entry.getKey().equals("E338") || entry.getKey().equals("E339")) {
-          tempMap.put(entry.getKey(), entry.getValue());
-        }
-      }
-      typeCode = Integer.toHexString(tempMap.get(tempKey[1]));
-    } else {
-      typeCode = Integer.toHexString(codeMap.get(tempKey[1]));
-    }
-
-
-    returnMessage[4] = ctrl;
-    returnMessage[7] = typeCode;
-    returnMessage[9] = reason;
-    returnMessage[13] = fileNameByte;
-    returnMessage[14] = fileContentByte;
-
-    // 获取从[控制域]到[校验和]之前的报文
-    StringBuffer tempSB = new StringBuffer("");
-    for (int i = 4; i <= 14; i++) {
-      tempSB.append(returnMessage[i]);
-    }
-    // 计算校验和
-    String crc = IEC102Uitl.makeChecksum(tempSB.toString());
-    returnMessage[15] = crc;
-    // 计算报文的帧长
-    String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-    String mlLow = ml.substring(0, 2);
-    String mlHeight = ml.substring(2);
-    returnMessage[1] = mlLow;
-    returnMessage[2] = mlHeight;
-    String sendMessage = ArrayUtil.join(returnMessage, "");
-    return sendMessage.toUpperCase();
-  }
-
-  public void channelCloseConnect(ChannelHandlerContext ctx, UploadObject uploadObject, UploadFileChannel uploadFileChannel) {
-    // 传输帧类型不对,断开通道重启
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()) {
-      Map.Entry<String, FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.substring(0, key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-        countMap.remove();
-      }
-    }
-
-    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-    while (contentMap.hasNext()) {
-      Map.Entry<String, String> entry = contentMap.next();
-      String key = entry.getKey();
-      if (key.substring(0, key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-        contentMap.remove();
-      }
-    }
-    FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
-    ctx.close();
-  }
-}

+ 0 - 362
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102TransitHandler.java

@@ -1,362 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.*;
-import com.jiayue.ipfcst.console.service.ChannelDisconLogService;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.E63.E63UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * netty服务端中转处理类
- *
- * @author xsl
- * @version 3.0
- */
-@Slf4j
-public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-  @Autowired
-  ElectricFieldService electricFieldService = SpringContextHolder.getApplicationContext().getBean(ElectricFieldService.class);
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  ServerFor102StandardService serverFor102StandardService = SpringContextHolder.getApplicationContext().getBean(ServerFor102StandardService.class);
-  @Autowired
-  ServerFor102NMService serverFor102NMService = SpringContextHolder.getApplicationContext().getBean(ServerFor102NMService.class);
-  @Autowired
-  ChannelDisconLogService channelDisconLogService = SpringContextHolder.getApplicationContext().getBean(ChannelDisconLogService.class);
-  @Autowired
-  AppenderFactory appenderFactory = SpringContextHolder.getApplicationContext().getBean(AppenderFactory.class);
-  @Autowired
-  E63UploadFileService e63UploadFileService = SpringContextHolder.getApplicationContext().getBean(E63UploadFileService.class);
-
-  private int readerIdleTime;
-
-  ServerFor102TransitHandler(Integer readerIdleTime) {
-    this.readerIdleTime = readerIdleTime;
-  }
-
-  /**
-   * 客户端连接会触发
-   */
-  @Override
-  public void channelActive(ChannelHandlerContext ctx) throws Exception {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-
-    // 本地IP和端口
-    InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localAddress.getAddress().getHostAddress();
-    String localPort = String.valueOf(localAddress.getPort());
-
-    List<UploadObject> tempList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E1")).collect(Collectors.toList());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-
-    UploadObject uploadObject = null;
-    UploadFileChannel uploadFileChannel = null;
-    for (UploadFileChannel u:uploadFileChannelList){
-      if ((u.getLocalIp()!=null && u.getLocalPort()!=null) && u.getLocalIp().equals(localIp) && u.getLocalPort().equals(localPort) && u.getRemoteIp().equals(remoteIP)){
-        for (UploadObject ub:uploadObjectList){
-          if (u.getUploadObjectId()==ub.getId()){
-            uploadFileChannel = u;
-            uploadObject = ub;
-            break;
-          }
-        }
-      }
-    }
-    if(uploadFileChannel.getChannelStatusEnum().name().equals("E1")){
-      Logger uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-      uploadLogger.info("远程"+remoteIP+"准备接入通道至本机的"+localIp+":"+localPort);
-      if (FileConstant.channelIpPortMap.get(uploadObject.getId()+remoteIP) != null||(FileConstant.objectStatusMap.get(uploadObject.getId())!=null&&FileConstant.objectStatusMap.get(uploadObject.getId()).equals("1"))) {
-        uploadLogger.info(remoteIP + ":" + FileConstant.channelIpPortMap.get(uploadObject.getId()+remoteIP) + "已在交互,新连接" + remoteIP + ":" + insocket.getPort() + "不能再次连接");
-        ctx.close();
-      } else {
-        uploadLogger.info(ctx.channel().remoteAddress() + "接入通道");
-
-        FileConstant.objectStatusMap.put(uploadObject.getId(),"1");
-        // 设置通道状态正常
-        FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-        FileConstant.channelIpPortMap.put(uploadObject.getId()+remoteIP, insocket.getPort());
-//        List<ChannelDisconLog> channelDisconLogList = channelDisconLogService.get(String.valueOf(uploadFileChannel.getId()));
-//        if (channelDisconLogList.size() > 0) {
-//          channelDisconLogList.sort(Comparator.comparing(ChannelDisconLog::getCreateTime).reversed());
-//          Long reconnectTime = new Date().getTime();
-//          ChannelDisconLog channelDisconLog = channelDisconLogList.get(0);
-//          channelDisconLog.setReconnectTime(reconnectTime);
-//          // 计算时长
-//          Long durationL = reconnectTime - channelDisconLog.getDisconnectTime();
-//          if (durationL / 1000 >= 60) {
-//            channelDisconLog.setDuration(String.valueOf(durationL / (1000 * 60)) + "分");
-//          } else {
-//            channelDisconLog.setDuration(String.valueOf(durationL / 1000) + "秒");
-//          }
-//          channelDisconLogService.save(channelDisconLog);
-//        }
-      }
-    }
-  }
-
-  /**
-   * 客户端发消息会触发
-   */
-  @Override
-  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    // 本地IP和端口
-    InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localAddress.getAddress().getHostAddress();
-    String localPort = String.valueOf(localAddress.getPort());
-
-    List<UploadObject> tempList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E1")).collect(Collectors.toList());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-
-    UploadObject uploadObject = null;
-    UploadFileChannel uploadFileChannel = null;
-    for (UploadFileChannel u:uploadFileChannelList){
-      if ((u.getLocalIp()!=null && u.getLocalPort()!=null) && u.getLocalIp().equals(localIp) && u.getLocalPort().equals(localPort) && u.getRemoteIp().equals(remoteIP)){
-        for (UploadObject ub:uploadObjectList){
-          if (u.getUploadObjectId()==ub.getId()){
-            uploadFileChannel = u;
-            uploadObject = ub;
-            break;
-          }
-        }
-      }
-    }
-    Logger uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-    FileConstant.objectStatusMap.put(uploadObject.getId(),"1");
-    // 设置通道状态正常
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-    // 获取场站信息
-    ElectricField electricField = electricFieldService.get();
-    // 返回的报文
-    String receiveMessage = "";
-    String province = electricField.getProvinceEnum().name().toString();
-    if ("E15".equals(province)) {
-      // 蒙东102服务端
-      receiveMessage = serverFor102NMService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, electricField, uploadLogger, ctx);
-    }
-    else {  // 标准102服务端
-      receiveMessage = serverFor102StandardService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, electricField, uploadLogger, ctx);
-    }
-    ctx.channel().writeAndFlush(receiveMessage);
-  }
-
-  /**
-   * 发生异常触发
-   */
-  @Override
-  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    // 本地IP和端口
-    InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localAddress.getAddress().getHostAddress();
-    String localPort = String.valueOf(localAddress.getPort());
-
-    List<UploadObject> tempList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E1")).collect(Collectors.toList());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-
-    UploadObject uploadObject = null;
-    UploadFileChannel uploadFileChannel = null;
-    for (UploadFileChannel u:uploadFileChannelList){
-      if ((u.getLocalIp()!=null && u.getLocalPort()!=null) && u.getLocalIp().equals(localIp) && u.getLocalPort().equals(localPort) && u.getRemoteIp().equals(remoteIP)){
-        for (UploadObject ub:uploadObjectList){
-          if (u.getUploadObjectId()==ub.getId()){
-            uploadFileChannel = u;
-            uploadObject = ub;
-            break;
-          }
-        }
-      }
-    }
-    Logger uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()) {
-      Map.Entry<String, FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())){
-        countMap.remove();
-      }
-    }
-
-    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-    while (contentMap.hasNext()) {
-      Map.Entry<String, String> entry = contentMap.next();
-      String key = entry.getKey();
-      if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())){
-        contentMap.remove();
-      }
-    }
-    FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
-
-    uploadLogger.error(uploadFileChannel.getChannelName()+" "+ctx.channel().remoteAddress() + "发生异常", cause);
-    FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp()+ ":" + uploadFileChannel.getLocalPort()).destroy();
-    FileConstant.nettyInstanceMap.remove(uploadFileChannel.getLocalIp()+ ":" + uploadFileChannel.getLocalPort());
-    Thread.sleep(2000);
-    uploadFileChannelService.startAllChannel();
-  }
-
-  /**
-   * 通道断开触发
-   */
-  @Override
-  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    Integer remotePort = insocket.getPort();
-    // 本地IP和端口
-    InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localAddress.getAddress().getHostAddress();
-    String localPort = String.valueOf(localAddress.getPort());
-
-    List<UploadObject> tempList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E1")).collect(Collectors.toList());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-
-    UploadObject uploadObject = null;
-    UploadFileChannel uploadFileChannel = null;
-    for (UploadFileChannel u:uploadFileChannelList){
-      if ((u.getLocalIp()!=null && u.getLocalPort()!=null) && u.getLocalIp().equals(localIp) && u.getLocalPort().equals(localPort) && u.getRemoteIp().equals(remoteIP)){
-        for (UploadObject ub:uploadObjectList){
-          if (u.getUploadObjectId()==ub.getId()){
-            uploadFileChannel = u;
-            uploadObject = ub;
-            break;
-          }
-        }
-      }
-    }
-    Logger uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-    uploadLogger.info("通道断开准备移除对象编号:"+uploadObject.getObjectNo()+",通道名称:"+uploadFileChannel.getChannelName()+",本地ip端口:"+localIp+":"+localPort+",远程ip端口:"+remoteIP+":"+remotePort);
-
-    if (FileConstant.channelIpPortMap.get(uploadObject.getId()+remoteIP) != null) {
-      if (FileConstant.channelIpPortMap.get(uploadObject.getId()+remoteIP).intValue() == remotePort.intValue()) {
-        // 断开的连接是已经交互的连接
-        uploadLogger.info(ctx.channel().remoteAddress() + "通道断开");
-
-        FileConstant.objectStatusMap.put(uploadObject.getId(),"0");
-        // 设置通道状态不通
-        FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-//        // 保存通道断开日志
-//        ChannelDisconLog channelDisconLog = new ChannelDisconLog();
-//        channelDisconLog.setChannelId(String.valueOf(uploadFileChannel.getId()));
-//        channelDisconLog.setChannelName(uploadFileChannel.getChannelName());
-//        channelDisconLog.setDisconnectTime(new Date().getTime());
-//        channelDisconLogService.save(channelDisconLog);
-        Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-        while (countMap.hasNext()) {
-          Map.Entry<String, FileMutableInteger> entry = countMap.next();
-          String key = entry.getKey();
-          if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())){
-            uploadLogger.info("通道断开移除uploadCountMap缓存:"+key+"==>对象编号:"+uploadObject.getObjectNo());
-            countMap.remove();
-          }
-        }
-
-        Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-        while (contentMap.hasNext()) {
-          Map.Entry<String, String> entry = contentMap.next();
-          String key = entry.getKey();
-          if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())){
-            uploadLogger.info("通道断开移除fileContentMap缓存:"+key+"==>对象编号:"+uploadObject.getObjectNo());
-            contentMap.remove();
-          }
-        }
-        FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
-        FileConstant.channelIpPortMap.remove(uploadObject.getId()+remoteIP);
-      }
-    }
-    uploadFileChannelService.startAllChannel();
-    super.channelInactive(ctx);
-  }
-
-  @Override
-  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    Integer remotePort = insocket.getPort();
-    // 本地IP和端口
-    InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localAddress.getAddress().getHostAddress();
-    String localPort = String.valueOf(localAddress.getPort());
-
-    List<UploadObject> tempList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E1")).collect(Collectors.toList());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-
-    UploadObject uploadObject = null;
-    UploadFileChannel uploadFileChannel = null;
-    for (UploadFileChannel u:uploadFileChannelList){
-      if ((u.getLocalIp()!=null && u.getLocalPort()!=null) && u.getLocalIp().equals(localIp) && u.getLocalPort().equals(localPort) && u.getRemoteIp().equals(remoteIP)){
-        for (UploadObject ub:uploadObjectList){
-          if (u.getUploadObjectId()==ub.getId()){
-            uploadFileChannel = u;
-            uploadObject = ub;
-            break;
-          }
-        }
-      }
-    }
-    Logger uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-    uploadLogger.info("没有交互准备移除对象编号:"+uploadObject.getObjectNo()+",通道名称:"+uploadFileChannel.getChannelName()+",本地ip端口:"+localIp+":"+localPort+",远程ip端口:"+remoteIP+":"+remotePort);
-    FileConstant.objectStatusMap.put(uploadObject.getId(),"0");
-    // 设置通道状态不通
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-    uploadLogger.info(ctx.channel().remoteAddress() + " {}秒没有报文交互,关闭通道", readerIdleTime);
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()) {
-      Map.Entry<String, FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())){
-        uploadLogger.info("没有交互移除uploadCountMap缓存:"+key+"==>对象编号:"+uploadObject.getObjectNo());
-        countMap.remove();
-      }
-    }
-
-    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-    while (contentMap.hasNext()) {
-      Map.Entry<String, String> entry = contentMap.next();
-      String key = entry.getKey();
-      if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())){
-        uploadLogger.info("没有交互移除fileContentMap缓存:"+key+"==>对象编号:"+uploadObject.getObjectNo());
-        contentMap.remove();
-      }
-    }
-    FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
-
-    log.info(uploadFileChannel.getChannelName()+" "+ctx.channel().remoteAddress() + " {}秒没有报文交互,自动重启102服务端", readerIdleTime);
-    uploadLogger.info(uploadFileChannel.getChannelName()+" "+ctx.channel().remoteAddress() + " {}秒没有报文交互,自动重启102服务端", readerIdleTime);
-    FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp()+ ":" + uploadFileChannel.getLocalPort()).destroy();
-    FileConstant.nettyInstanceMap.remove(uploadFileChannel.getLocalIp()+ ":" + uploadFileChannel.getLocalPort());
-    Thread.sleep(2000);
-
-  }
-}

+ 0 - 78
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/UploadFileNettyServer.java

@@ -1,78 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102;
-
-import ch.qos.logback.classic.Logger;
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.buffer.PooledByteBufAllocator;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-import lombok.extern.slf4j.Slf4j;
-
-import java.net.InetSocketAddress;
-
-/**
- * 开启netty服务端
- *
- * @author xsl
- * @version 3.0
- */
-@Slf4j
-public class UploadFileNettyServer extends NettyParent{
-//  private Logger log;
-  private int readerIdleTime;
-  public ChannelFuture future = null;
-  private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
-  private final EventLoopGroup workerGroup = new NioEventLoopGroup(10);
-  public String localPort = "";
-  InetSocketAddress socketAddress = null;
-
-  public UploadFileNettyServer(InetSocketAddress socketAddress,Integer readerIdleTime){
-    this.socketAddress = socketAddress;
-    this.readerIdleTime = readerIdleTime;
-  }
-
-  public void start() {
-    ServerBootstrap bootstrap = new ServerBootstrap()
-      .group(bossGroup, workerGroup)
-      .channel(NioServerSocketChannel.class)
-      .childHandler(new ServerFor102InitChannel(readerIdleTime))
-      .localAddress(socketAddress)
-      //设置队列大小
-      .option(ChannelOption.SO_BACKLOG, 1024)
-      .option(ChannelOption.SO_REUSEADDR,true)
-//      .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
-//      .option(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
-      // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
-      .childOption(ChannelOption.SO_KEEPALIVE, true);
-    try {
-      this.localPort = String.valueOf(socketAddress.getPort());
-      future = bootstrap.bind(socketAddress).sync();
-      log.info("102服务器启动开始监听端口: {}", socketAddress.getPort());
-    } catch (Exception e) {
-      e.printStackTrace();
-      log.error("开启102服务端口: {}失败", socketAddress.getPort(), e);
-      // 确保在使用完服务器后关闭相关资源
-      if (future != null) {
-        try {
-          future.channel().closeFuture().sync();
-        } catch (InterruptedException interruptedException) {
-          interruptedException.printStackTrace();
-        }
-      }
-    }
-  }
-
-  /**
-   * 停止服务
-   */
-  public void destroy() {
-    log.info("Shutdown Netty Server...");
-    if (future != null) {
-      future.channel().close();
-    }
-    workerGroup.shutdownGracefully();
-    bossGroup.shutdownGracefully();
-    log.info("Shutdown Netty Server Success!");
-  }
-
-}

+ 0 - 320
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiBase102Service.java

@@ -1,320 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.mengxi;
-
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.*;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogDetailRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.console.service.SysParameterService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileCodeService;
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.WorkbookFactory;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * 102业务处理基础类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class MengXiBase102Service {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  @Autowired
-  UploadFileLogDetailRepository uploadFileLogDetailRepository;
-  @Autowired
-  SysParameterService sysParameterService;
-  @Autowired
-  UploadFileCodeService uploadFileCodeService;
-  @Autowired
-  ElectricFieldService electricFieldService;
-
-
-  /**
-   * 统计文件上报成功或者失败并移动文件
-   *
-   * @param uploadFileChannel 通道信息
-   * @param faileReason       失败原因
-   */
-
-  public void totalFileUploadNums(UploadObject uploadObject, UploadFileChannel uploadFileChannel, String faileReason, Logger log) {
-    // 上报文件次数缓存加1
-//    Map<String, FileMutableInteger> filterMap = FileConstant.uploadCountMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))))
-//      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-//        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-
-
-
-    if (!"".equals(FileConstant.mxCurrentFileName)) {
-      String[] keys = new String[3];
-      String tempFileName = FileConstant.mxCurrentFileName;
-      log.info("UploadNums操作文件:" + tempFileName);
-      keys[0] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-      tempFileName = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-      keys[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-      keys[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-
-      Integer id = FileConstant.fileShouldMomentMap.get(FileConstant.mxCurrentFileName);
-      UploadFileLog uploadFileLog = null;
-      Optional<UploadFileLog> fileLogOptional = uploadFileLogRepository.findById(id);
-      if (fileLogOptional.isPresent()) {
-        uploadFileLog = fileLogOptional.get();
-      }
-
-      // 先判断是否查出日志,如果没有则认为文件是本地拷贝进去的
-      if (uploadFileLog == null) {
-        UploadFileLog newUploadFileLog = new UploadFileLog();
-        newUploadFileLog.setUploadObjectId(uploadObject.getId());
-        newUploadFileLog.setFileStatusEnum(FileStatusEnum.E1);
-        newUploadFileLog.setUploadProtocolEnum(uploadObject.getUploadProtocolEnum());
-        newUploadFileLog.setFileName(keys[2]);
-        newUploadFileLog.setFileTypeEnum(FileTypeEnum.valueOf(keys[1]));
-        newUploadFileLog.setUploadObjectName(uploadObject.getUploadObjectName());
-        newUploadFileLog.setUploadObjectNo(uploadObject.getObjectNo());
-        newUploadFileLog.setUploadCounter(0);
-        newUploadFileLog.setFileRemarks("当日没找到日志记录,系统插入一条");
-        uploadFileLog = uploadFileLogRepository.save(newUploadFileLog);
-      }
-
-      if ("".equals(faileReason)) {
-        UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-        uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-        uploadFileLogDetail.setUploadFileLogId(uploadFileLog.getId());
-        uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-        uploadFileLogDetail.setFileName(keys[2]);
-        uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-        uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-        uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E2);
-//      fileMutableInteger.getUploadFileLogDetail().add(uploadFileLogDetail);
-        // 上报成功保存数据库,更新上报表,上报明细
-//      uploadFileLogRepository.updateFileUploadCount(FileStatusEnum.E2, fileMutableInteger.getValue(), uploadObject.getId(), keys[2]);
-//        uploadFileLog.setFileStatusEnum(FileStatusEnum.E2);
-//        uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter()+1);
-//        uploadFileLogRepository.save(uploadFileLog);
-        uploadFileLogRepository.uploadFileUpdate(FileStatusEnum.E2, uploadFileLog.getUploadCounter() + 1, uploadFileLog.getId());
-        uploadFileLogDetailRepository.save(uploadFileLogDetail);
-        // 将文件移动到成功目录
-        String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-        String targetPath = FileUtil.getFileUploadPath() + File.separator + "backups" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-
-        try {
-          FileUtil.move(srcPath, targetPath);
-        } catch (Exception e) {
-          log.error("上报成功移动文件失败", e);
-        }
-        // 清理缓存
-        FileConstant.uploadCountMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.readyUploadFileMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.fileShouldMomentMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.fileContentMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.againUploadFileMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.filePackageNumMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.mxCurrentFileName = "";
-        log.info("上报对象编号:" + keys[0] + " 文件名:" + keys[2] + " 本次上报结果:成功");
-
-      } else {
-        // 保存上报失败明细表
-        UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-        uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-        uploadFileLogDetail.setUploadFileLogId(uploadFileLog.getId());
-        uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-        uploadFileLogDetail.setFileName(keys[2]);
-        uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-        uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-        uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E3);
-        uploadFileLogDetail.setUploadFailureReason(faileReason);
-        uploadFileLog.setFileStatusEnum(FileStatusEnum.E3);
-        uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter() + 1);
-        uploadFileLogRepository.save(uploadFileLog);
-        uploadFileLogDetailRepository.save(uploadFileLogDetail);
-
-        if (FileConstant.againUploadFileMap.get(FileConstant.mxCurrentFileName) == null) {
-          // 遇到失败,再给这个文件一次上报的机会
-          FileConstant.againUploadFileMap.put(FileConstant.mxCurrentFileName, "");
-          log.info(FileConstant.mxCurrentFileName + "上报结果失败,再报一次变量中存入");
-        } else {
-          // 将文件移动到失败目录
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "error" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-          } catch (Exception e) {
-            log.error("将文件移动到失败目录", e);
-          }
-          FileConstant.readyUploadFileMap.remove(FileConstant.mxCurrentFileName);
-          FileConstant.fileShouldMomentMap.remove(FileConstant.mxCurrentFileName);
-          FileConstant.againUploadFileMap.remove(FileConstant.mxCurrentFileName);
-        }
-        // 清理缓存
-        FileConstant.uploadCountMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.fileContentMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.filePackageNumMap.remove(FileConstant.mxCurrentFileName);
-        FileConstant.mxCurrentFileName = "";
-        log.info("上报对象编号:" + keys[0] + " 文件名:" + keys[2] + " 本次上报结果失败:" + faileReason);
-      }
-    }
-    else{
-      log.info("没有找到缓存里的文件,对象编号是:"+uploadObject.getObjectNo());
-    }
-  }
-
-  /**
-   * 读取文件内容转16进制报文
-   *
-   * @param filePath
-   * @param charsetName
-   * @return
-   */
-  public String createFileMessageHex(String filePath, String charsetName, Logger log) {
-    InputStreamReader isr = null;
-    String fileMessageHex = "";
-    try {
-      isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
-      StringBuffer sb = new StringBuffer("");
-      int len1 = 0;
-      while ((len1 = isr.read()) != -1) {
-        sb.append((char) len1);
-      }
-      isr.close();
-
-      String str = sb.toString();
-      fileMessageHex = ByteUtil.Byte2String(str.getBytes(charsetName));
-      fileMessageHex = fileMessageHex.replaceAll(" ", "");
-      ////////////////////以下注释生成本地文件/////////////////////
-//      int len = fileMessageHex.length();
-//      byte[] data = new byte[len / 2];
-//      for (
-//        int i = 0;
-//        i < len; i += 2) {
-//        data[i / 2] = (byte) ((Character.digit(fileMessageHex.charAt(i), 16) << 4)
-//          + Character.digit(fileMessageHex.charAt(i + 1), 16));
-//      }
-//      OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\sdf.PVD"), charsetName);
-//      String res = new String(data);
-//      osw.write(res);
-//      osw.close();
-    } catch (Exception e) {
-      log.error("读取本地文件失败", e);
-    } finally {
-      if (isr != null) {
-        try {
-          isr.close();
-        } catch (IOException e) {
-          e.printStackTrace();
-        }
-      }
-    }
-    return fileMessageHex;
-  }
-
-  /**
-   * 根据通道过滤缓存Map的key是否存在
-   *
-   * @param uploadObjectNo
-   * @param map
-   * @return
-   */
-  public Map<String, UploadFileLog> filterFileByObjectNo(String uploadObjectNo, Map<String, UploadFileLog> map, Logger log) {
-    Map<String, UploadFileLog> copyMap = new HashMap<>();
-    copyMap.putAll(map);
-    // 先过滤出上报对象下的所有文件
-    Map<String, UploadFileLog> filterMap = new HashMap<>();
-    Iterator<Map.Entry<String, UploadFileLog>> it = copyMap.entrySet().iterator();
-    while (it.hasNext()) {
-      Map.Entry<String, UploadFileLog> entry = it.next();
-      if (uploadObjectNo.equals(entry.getKey().substring(0, entry.getKey().indexOf("@")))) {
-        filterMap.put(entry.getKey(), entry.getValue());
-      }
-    }
-    // 再将失效时间的文件移除
-    Map<String, UploadFileLog> fileterFileMap = new HashMap<>();
-    Date d = new Date();
-    for (Map.Entry<String, UploadFileLog> entry : filterMap.entrySet()) {
-      UploadFileLog u = entry.getValue();
-      if (u.getUploadFileEndTime() == null) {
-        // 有效的文件
-        fileterFileMap.put(entry.getKey(), u);
-      } else {
-        if (d.getTime() <= u.getUploadFileEndTime()) {
-          // 有效的文件
-          fileterFileMap.put(entry.getKey(), u);
-        } else {
-          // 过期文件
-          String[] keys = new String[3];
-//          keys[0] = entry.getKey().substring(0,entry.getKey().indexOf("@",0));
-//          keys[1] = entry.getKey().substring(entry.getKey().indexOf("@",1)+1,entry.getKey().indexOf("@",2));
-//          keys[2] = entry.getKey().substring(entry.getKey().indexOf("@",2)+1);
-          keys[0] = entry.getKey().substring(0, entry.getKey().indexOf("@", 0));
-          String tempFileName = entry.getKey().substring(entry.getKey().indexOf("@", 0) + 1);
-          keys[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-          keys[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "expire" + File.separator + keys[0] + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-            log.info("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2]);
-          } catch (Exception e) {
-            log.error("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2] + "失败", e);
-          }
-          // 清理缓存
-          FileConstant.uploadCountMap.remove(entry.getKey());
-          FileConstant.againUploadFileMap.remove(entry.getKey());
-          FileConstant.readyUploadFileMap.remove(entry.getKey());
-          FileConstant.fileShouldMomentMap.remove(entry.getKey());
-          FileConstant.fileContentMap.remove(entry.getKey());
-        }
-      }
-    }
-    return fileterFileMap;
-  }
-
-  /**
-   * 获取文件CODE码
-   *
-   * @return
-   */
-  public Map<String, Integer> getFileCode() {
-    List<UploadFileCode> uploadFileCodeList = uploadFileCodeService.get();
-    Map<String, Integer> codeMap = new HashMap<>();
-    for (UploadFileCode uploadFileCode : uploadFileCodeList) {
-      codeMap.put(uploadFileCode.getFileTypeEnum().toString(), uploadFileCode.getFileTypeCode());
-    }
-    return codeMap;
-  }
-
-  /**
-   * 读取excel文件内容转16进制报文
-   *
-   * @param filePath
-   * @return
-   */
-  public String createFileMessageHexByExcel(String filePath, Logger log) {
-    String fileMessageHex = "";
-    try (
-      FileInputStream inputStream = new FileInputStream(new File(filePath));
-      ByteArrayOutputStream baos = new ByteArrayOutputStream();
-    ) {
-      Workbook workbook = WorkbookFactory.create(inputStream);
-      workbook.write(baos);// 临时存储流到内存
-      baos.flush();
-      fileMessageHex = ByteUtil.Byte2String(baos.toByteArray());
-      fileMessageHex = fileMessageHex.replaceAll(" ", "");
-      workbook.close();
-    } catch (Exception e) {
-      log.error("读取本地文件失败", e);
-    }
-    return fileMessageHex;
-  }
-}

+ 0 - 130
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiClient.java

@@ -1,130 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.mengxi;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.fileupload.IEC102.NettyParent;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongClientHandler;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongDecoder;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongEncoder;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.IdleStateHandler;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * 蒙西客户端
- *
- * @author xsl
- * @version 3.0
- */
-public class MengXiClient extends NettyParent {
-  private String host;
-  private int port;
-  private Logger log;
-
-  private Bootstrap bootstrap = new Bootstrap();
-  EventLoopGroup workerGroup = new NioEventLoopGroup();
-  private Channel channel;
-  private ChannelFuture future;
-
-  private UploadFileChannel uploadFileChannel;
-
-  private UploadObject uploadObject;
-
-  /**
-   * 获取 host
-   *
-   * @return host
-   */
-  public String getHost() {
-    return host;
-  }
-
-  /**
-   * 获取 port
-   *
-   * @return port
-   */
-  public int getPort() {
-    return port;
-  }
-
-  public MengXiClient(String host, int port, Logger log, UploadObject uploadObject, UploadFileChannel uploadFileChannel) {
-    this.host = host;
-    this.port = port;
-    this.log = log;
-    this.uploadFileChannel = uploadFileChannel;
-    this.uploadObject = uploadObject;
-    init();
-  }
-
-  /**
-   * 初始化客户端
-   */
-  private void init() {
-    final MengXiClient client = this;
-    bootstrap.group(workerGroup);
-    bootstrap.channel(NioSocketChannel.class);
-    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
-    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
-      @Override
-      protected void initChannel(SocketChannel ch) {
-//        ch.pipeline().addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));
-        ch.pipeline().addLast("decoder", new MengXiDecoder(log));
-        ch.pipeline().addLast("encoder", new MengXiEncoder(log));
-        ch.pipeline().addLast(new MengXiClientHandler(client, log,uploadObject,uploadFileChannel));
-      }
-    });
-    log.info("客户端初始化完成");
-  }
-
-  /**
-   * 与服务端建立连接
-   * (注册重连机制)
-   */
-  public void start() {
-    future = bootstrap.connect(host, port);
-    this.channel = future.channel();
-
-    future.addListener(new ChannelFutureListener() {
-      //使用匿名内部类,ChannelFutureListener接口
-      //重写operationComplete方法
-      @Override
-      public void operationComplete(ChannelFuture future) throws Exception {
-        //判断是否操作成功
-        if (future.isSuccess()) {
-          log.info("客户端连接成功==>"+uploadFileChannel.getRemoteIp()+":"+uploadFileChannel.getRemotePort());
-        } else {
-          log.info("=======");
-          FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId() + "");
-          FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-          log.info("客户端连接失败==>"+uploadFileChannel.getRemoteIp()+":"+uploadFileChannel.getRemotePort());
-        }
-      }
-    });
-    this.channel = future.channel();
-//    try {
-//      future.channel().closeFuture().sync();
-//    } catch (InterruptedException e) {
-//      throw new RuntimeException(e);
-//    }
-  }
-
-  /**
-   * 停止服务
-   */
-  public void destroy() {
-    if (future != null) {
-      future.channel().close();
-    }
-    System.out.println("bootstrap实例:"+bootstrap.hashCode());
-    workerGroup.shutdownGracefully();
-    log.info("客户端通道连接销毁成功!");
-  }
-}

+ 0 - 182
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiClientHandler.java

@@ -1,182 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.mengxi;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.util.RuntimeUtil;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongHandlerService;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import com.jiayue.ipfcst.fileupload.util.IEC102Uitl;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.channel.EventLoop;
-import org.springframework.beans.factory.annotation.Autowired;
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-/**
- * 山东客户端Handler
- *
- * @author xsl
- * @version 3.0
- */
-public class MengXiClientHandler extends ChannelInboundHandlerAdapter {
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-  @Autowired
-  AppenderFactory appenderFactory = SpringContextHolder.getApplicationContext().getBean(AppenderFactory.class);
-  @Autowired
-  MengXiHandlerService mengxiHandlerService = SpringContextHolder.getApplicationContext().getBean(MengXiHandlerService.class);
-
-  private MengXiClient client;
-
-  private Logger log;
-
-  private UploadFileChannel uploadFileChannel;
-
-  private UploadObject uploadObject;
-
-//  MengXiClientTask task = null;
-
-
-  public MengXiClientHandler(MengXiClient client,Logger log,UploadObject uploadObject,UploadFileChannel uploadFileChannel) {
-    this.client = client;
-    this.log = log;
-    this.uploadObject = uploadObject;
-    this.uploadFileChannel = uploadFileChannel;
-  }
-
-  /**
-   * 接收服务端消息
-   *
-   * @param ctx channel上下文
-   * @param msg 消息
-   */
-  @Override
-  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
-    // 返回的报文
-    String receiveMessage = mengxiHandlerService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, log,ctx);
-    ctx.channel().writeAndFlush(receiveMessage);
-  }
-
-  /**
-   * 首次建立连接
-   *
-   * @param ctx channel上下文
-   */
-  @Override
-  public void channelActive(ChannelHandlerContext ctx) {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    int remotePort = insocket.getPort();
-    log.info("客户端连接对端成功"+remoteIP+":"+remotePort);
-    // 设置通道状态正常
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-    FileConstant.fileContentByIdxMap.clear();
-
-//    if (FileConstant.isSendVisitPath){
-      // 发送10帧
-      String firstMessage = "1049FFFF4716";
-      log.info(ctx.channel().remoteAddress() + " - " + "发送报文:[请求链路]" + IEC102Uitl.delimiterStringBySpace(firstMessage));
-      ctx.writeAndFlush(firstMessage);
-//    }
-//    else{
-//      // 发送访问路径
-//      String firstMessage = "6882006873FFFFAA010DFFFF002F57494E445F43445100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BF16";
-//      log.info(ctx.channel().remoteAddress() + " - " + "发送报文:[访问目录]" + IEC102Uitl.delimiterStringBySpace(firstMessage));
-//      ctx.writeAndFlush(firstMessage);
-//    }
-
-  }
-
-
-  /**
-   * 空闲发送心跳
-   *
-   * @param ctx channel上下文
-   * @param evt 事件
-   */
-  @Override
-  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
-//    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-//    // 获取远程IP
-//    String remoteIP = insocket.getAddress().getHostAddress();
-//    int remotePort = insocket.getPort();
-//
-//    List<UploadObject> tempList = uploadObjectService.get();
-//    List<UploadObject> uploadObjectList = tempList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E8")).collect(Collectors.toList());
-//    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-//
-//    UploadObject uploadObject = null;
-//    UploadFileChannel uploadFileChannel = null;
-//    for (UploadFileChannel u:uploadFileChannelList){
-//      if (u.getRemoteIp().equals(remoteIP) && u.getRemotePort().equals(String.valueOf(remotePort))){
-//        for (UploadObject ub:uploadObjectList){
-//          if (u.getUploadObjectId()==ub.getId()){
-//            uploadFileChannel = u;
-//            uploadObject = ub;
-//            break;
-//          }
-//        }
-//      }
-//    }
-//    if (FileConstant.mengxiSend68){
-//      // 允许发送68帧,查找文件是否存在
-//      String sendMessage = mengxiHandlerService.createFileInfo68(uploadObject,ctx,log);
-//      if (!"".equals(sendMessage)){
-//        ctx.writeAndFlush(sendMessage);
-//      }
-//    }
-//    else{
-//      // 发送10帧
-//      String firstMessage = "1049FFFF4716";
-//      log.info(ctx.channel().remoteAddress() + " - " + "发送报文:[请求链路]" + IEC102Uitl.delimiterStringBySpace(firstMessage));
-//      ctx.writeAndFlush(firstMessage);
-//    }
-  }
-
-  /**
-   * 异常处理
-   *
-   * @param ctx   channel上下文
-   * @param cause 异常
-   */
-  @Override
-  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-    FileConstant.fileContentByIdxMap.clear();
-    FileConstant.mxstatus = false;
-    FileConstant.fileContentCounter=-1;
-    FileConstant.mxCurrentFileName = "";
-    if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "") != null) {
-      FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "").destroy();
-    }
-    FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId() + "");
-    log.error("客户端发生异常:", cause);
-    ctx.channel().close();
-  }
-
-  /**
-   * 断线重连(10秒不间断重试)
-   */
-  @Override
-  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-    FileConstant.fileContentByIdxMap.clear();
-    FileConstant.mxstatus = false;
-    FileConstant.fileContentCounter=-1;
-    FileConstant.mxCurrentFileName = "";
-    if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "") != null) {
-      FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "").destroy();
-    }
-    FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId() + "");
-  }
-}

+ 0 - 90
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiDecoder.java

@@ -1,90 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.mengxi;
-
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import com.jiayue.ipfcst.fileupload.util.IEC102Uitl;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.ByteBufUtil;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import org.slf4j.Logger;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * 蒙西解码
- *
- * @author xsl
- * @version 3.0
- */
-public class MengXiDecoder extends SimpleChannelInboundHandler {
-  //记录上次未读完的字节
-  List<String> messageList = new ArrayList<String>();
-
-  private Logger log;
-
-  MengXiDecoder(Logger log) {
-    this.log = log;
-  }
-
-  @Override
-  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
-    try {
-      ByteBuf buf = (ByteBuf) msg;
-      String receiveStr = ByteBufUtil.hexDump(buf).toUpperCase();
-      List<String> receivesList = IEC102Uitl.stingToList(receiveStr);
-      messageList.addAll(receivesList);
-
-      // 至少6个以上字节才报文解码
-      if (messageList.size() >= 6) {
-        if (messageList.size()>600){
-          // 没用的太多了,舍弃掉
-          log.info("没用字符串报文超过600个舍弃掉:"+messageList.toString());
-          messageList.clear();
-        }
-        else{
-          int zb = 0;
-          while (true) {
-            String nextMessage = "";
-            for (int k = 0; k < messageList.size(); k++) {
-              if ("10".equals(messageList.get(k)) && (k + 5) <= messageList.size() && messageList.get(k + 5).equals("16")) {
-                List newList = messageList.subList(k, (k + 6));
-                nextMessage = String.join("", newList);
-                String tempStr = String.join("", messageList).substring((k + 6) * 2);
-                messageList.clear();
-                messageList = IEC102Uitl.stingToList(tempStr);
-                break;
-              }
-              if ("68".equals(messageList.get(k)) && (k + 3) <= messageList.size() && messageList.get(k + 3).equals("68")) {
-                int tempLength = ByteUtil.hexToDec(messageList.get(k + 2) + messageList.get(k + 1));
-                int end16 = (k + 3) + tempLength + 2;
-                if (end16 <= messageList.size() && messageList.get(end16).equals("16")) {
-                  List newList = messageList.subList(k, (end16 + 1));
-                  nextMessage = String.join("", newList);
-                  String tempStr = String.join("", messageList).substring((end16 + 1) * 2);
-                  messageList.clear();
-                  messageList = IEC102Uitl.stingToList(tempStr);
-                  break;
-                }
-              }
-            }
-            if (!"".equals(nextMessage)) {
-              if (zb==1){
-                log.info("获取到粘包帧:"+nextMessage);
-              }
-              zb++;
-              ctx.fireChannelRead(nextMessage);
-            }
-            else {
-              break;
-            }
-          }
-        }
-      }
-    }
-
-    catch (Exception e){
-      log.error("解码失败",e);
-    }
-  }
-}

+ 0 - 27
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiEncoder.java

@@ -1,27 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.mengxi;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.MessageToByteEncoder;
-import org.slf4j.Logger;
-
-import java.math.BigInteger;
-
-/**
- * 蒙西编码
- *
- * @author xsl
- * @version 3.0
- */
-public class MengXiEncoder extends MessageToByteEncoder<String> {
-  private Logger log;
-
-  MengXiEncoder(Logger log) {
-    this.log = log;
-  }
-    @Override
-    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
-      BigInteger bigint=new BigInteger(msg, 16);
-      out.writeBytes(bigint.toByteArray());
-    }
-}

+ 0 - 395
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/mengxi/MengXiHandlerService.java

@@ -1,395 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.mengxi;
-
-import cn.hutool.core.map.MapUtil;
-import cn.hutool.core.util.ArrayUtil;
-import cn.hutool.core.util.StrUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.SdBase102Service;
-import com.jiayue.ipfcst.fileupload.dto.Validate102Dto;
-import com.jiayue.ipfcst.fileupload.util.*;
-import io.netty.channel.ChannelHandlerContext;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.core.env.Environment;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.io.*;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-/**
- * 蒙西业务处理类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class MengXiHandlerService extends MengXiBase102Service {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  private final Environment environment;
-  @Autowired
-  public MengXiHandlerService(Environment environment) {
-    this.environment = environment;
-  }
-
-  @Transactional(propagation = Propagation.REQUIRED)
-  public String handlerMessage(String receiveMessage, UploadObject uploadObject, UploadFileChannel uploadFileChannel, Logger log, ChannelHandlerContext ctx) throws Exception{
-    String[] rmArray = IEC102Uitl.stingToArray(receiveMessage);
-    String sendMessage = "";
-    String sendCtrlChinese = "";
-    String receiveCtrlChinese = "";
-
-
-    if ("10".equals(rmArray[0])) {
-      if (receiveMessage.toUpperCase().equals("100BFFFF0916")) {
-        receiveCtrlChinese = "响应链路状态";
-        if (FileConstant.mxstatus==true){
-          Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-          String fileNameKey = "";
-          for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-            fileNameKey = entry.getKey();
-            break;
-          }
-          if (!"".equals(fileNameKey)){
-            // 发送访问目录帧
-            String[] tempKey = new String[3];
-            tempKey[0] = fileNameKey.substring(0, fileNameKey.indexOf("@", 0));
-            String tempFileName = fileNameKey.substring(fileNameKey.indexOf("@", 0) + 1);
-            tempKey[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-
-            String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "cr", "FF", "FF", "AA", "01", "0D", "FF", "FF", "00", "filePathByte","00", "crc", "16"};
-            returnMessage[4] = FileConstant.controlReversal;
-            if (FileConstant.controlReversal.equals("53")){
-              FileConstant.controlReversal = "73";
-            }
-            else{
-              FileConstant.controlReversal = "53";
-            }
-            String uploadPath = this.environment.getProperty("mengxi.uploadpath."+tempKey[1]);
-            String filePathByte = ByteUtil.Byte2String(uploadPath.getBytes());
-            filePathByte = StrUtil.padAfter(filePathByte.replace(" ", ""), 240, '0');
-            returnMessage[13] = filePathByte;
-            // 获取从[控制域]到[校验和]之前的报文
-            StringBuffer tempSB = new StringBuffer("");
-            for (int i = 4; i <= 14; i++) {
-              tempSB.append(returnMessage[i]);
-            }
-            // 计算校验和
-            String crc = IEC102Uitl.makeChecksum(tempSB.toString());
-            returnMessage[15] = crc;
-            // 计算报文的帧长
-            String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-            String mlLow = ml.substring(0, 2);
-            String mlHeight = ml.substring(2);
-            returnMessage[1] = mlLow;
-            returnMessage[2] = mlHeight;
-            sendMessage = ArrayUtil.join(returnMessage, "");
-            sendMessage = sendMessage.toUpperCase();
-            sendCtrlChinese = "访问目录"+uploadPath;
-          }
-          else{
-            // 没有文件关闭通道
-            log.info(ctx.channel().remoteAddress()+" - "+"没有可用文件上报,客户端主动断开连接");
-            ctx.channel().close();
-          }
-        }
-        else{
-          sendMessage = "1040FFFF3E16";
-          sendCtrlChinese = "复位远方链路";
-        }
-      }
-      if (receiveMessage.toUpperCase().equals("1000FFFFFE16")) {
-        receiveCtrlChinese = "确认复位";
-        // 二次发送1049FFFF4716
-        sendMessage = "1049FFFF4716";
-        sendCtrlChinese = "请求链路";
-        FileConstant.mxstatus = true;
-      }
-    }
-    else{
-      if ("AA".equals(rmArray[7])) {
-        receiveCtrlChinese = "确认目录";
-        // 发送文件内容
-        sendCtrlChinese = "发送文件信息";
-        sendMessage = createFileInfo68(uploadObject,ctx,log);
-      }
-      if ("B0".equals(rmArray[7])) {
-        receiveCtrlChinese = "确认文件信息";
-        // 发送文件内容
-        sendCtrlChinese = "发送文件内容";
-        // 开始文件内容第一帧
-        FileConstant.fileContentCounter=0;
-        sendMessage = createFileContentFirst68(uploadObject,ctx,log);
-      }
-      if ("B1".equals(rmArray[7])) {
-        receiveCtrlChinese = "确认文件内容";
-        if (FileConstant.fileContentCounter>0){
-          // 续传内容
-          sendCtrlChinese = "发送文件内容";
-          sendMessage = createFileContentFirst68(uploadObject,ctx,log);
-        }
-        else {
-          // 发送文件结束帧
-          sendCtrlChinese = "上传文件结束";
-          sendMessage = createEnd68(uploadObject,log);
-        }
-      }
-      if ("AD".equals(rmArray[7])) {
-        receiveCtrlChinese = "确认文件结束";
-        // 调用数据库
-        super.totalFileUploadNums(uploadObject, uploadFileChannel, "", log);
-        // 本次成功后,1分钟之后再进行文件上报
-        FileConstant.uploadSuccessTime = new Date();
-
-        log.info("本次交互完成关闭通道");
-        ctx.channel().close();
-      }
-    }
-
-    log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-    if (!"".equals(sendMessage)) {
-      log.info(ctx.channel().remoteAddress()+" - "+"发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage.toUpperCase()));
-    }
-    return sendMessage.toUpperCase();
-  }
-
-  public String createEnd68(UploadObject uploadObject,Logger log)throws Exception{
-    String sendMessage = "";
-    String fileNameKey = "";
-    String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "cr", "FF", "FF", "ad", "01", "0d", "FF", "FF", "00","00","fileLengthByte", "fileContentMD5", "crc", "16"};
-    // 生成第一帧,从待上报的缓存中取一个文件放入次数变量中
-    Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-    for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-      fileNameKey = entry.getKey();
-      break;
-    }
-    String[] tempKey = new String[3];
-    tempKey[0] = fileNameKey.substring(0, fileNameKey.indexOf("@", 0));
-    String tempFileName = fileNameKey.substring(fileNameKey.indexOf("@", 0) + 1);
-    tempKey[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-    tempKey[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-
-    returnMessage[4] = FileConstant.controlReversal;
-    if (FileConstant.controlReversal.equals("53")){
-      FileConstant.controlReversal = "73";
-    }
-    else{
-      FileConstant.controlReversal = "53";
-    }
-
-    // 获取本地物理文件路径
-    String filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + tempKey[0] + File.separator + tempKey[1] + File.separator + tempKey[2];
-    String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-    String fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-    String[] fileContentByteArray = IEC102Uitl.stingToArray(fileContentByte);
-    returnMessage[14] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(fileContentByteArray.length));
-    String fileContentOriginal = fileContentOriginal(filePath);
-    returnMessage[15] = FileUtil.getMD5(fileContentOriginal.getBytes(charsetName));
-    // 获取从[控制域]到[校验和]之前的报文
-    StringBuffer tempSB = new StringBuffer("");
-    for (int i = 4; i <= 15; i++) {
-      tempSB.append(returnMessage[i]);
-    }
-    // 计算校验和
-    String crc = IEC102Uitl.makeChecksum(tempSB.toString());
-    returnMessage[16] = crc;
-    // 计算报文的帧长
-    String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-    String mlLow = ml.substring(0, 2);
-    String mlHeight = ml.substring(2);
-    returnMessage[1] = mlLow;
-    returnMessage[2] = mlHeight;
-    sendMessage = ArrayUtil.join(returnMessage, "");
-    sendMessage = sendMessage.toUpperCase();
-    FileConstant.fileContentMap.remove(fileNameKey);
-    return sendMessage;
-  }
-
-  public String createFileContentFirst68(UploadObject uploadObject,ChannelHandlerContext ctx,Logger log)throws Exception{
-    String sendMessage = "";
-    String fileNameKey = "";
-    String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "cr", "FF", "FF", "ac", "01", "0d", "FF", "FF", "00","00","00", "fileContentAddressByte","fileContentDataLengthByte","fileDateByte", "crc", "16"};
-    // 生成第一帧,从待上报的缓存中取一个文件放入次数变量中
-    Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-    for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-      log.info("准备上传文件文件===>" + entry.getKey());
-      fileNameKey = entry.getKey();
-      break;
-    }
-    FileConstant.mxCurrentFileName = fileNameKey;
-    String[] tempKey = new String[3];
-    String tempFileName = fileNameKey;
-    tempKey[0] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-    tempFileName = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-    tempKey[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-    tempKey[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-
-    returnMessage[4] = FileConstant.controlReversal;
-    if (FileConstant.controlReversal.equals("53")){
-      FileConstant.controlReversal = "73";
-    }
-    else{
-      FileConstant.controlReversal = "53";
-    }
-
-    String fileContentByte = "";
-    if (FileConstant.fileContentCounter==0){
-      // 获取本地物理文件路径
-      String filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + tempKey[0] + File.separator + tempKey[1] + File.separator + tempKey[2];
-      String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-      fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-    }
-    else{
-      fileContentByte = FileConstant.fileContentMap.get(fileNameKey);
-    }
-
-    returnMessage[15]=ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(FileConstant.fileContentCounter));;
-    if (fileContentByte.length() <= 1024) {
-      // 一次可以传输完
-      String[] fileContentByteArray = IEC102Uitl.stingToArray(fileContentByte);
-      returnMessage[16] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh2(fileContentByteArray.length));
-      FileConstant.fileContentCounter = -1;
-    }
-    else{
-      // 剩余内容存入缓存?????
-      FileConstant.fileContentMap.put(fileNameKey, fileContentByte.substring(1024));
-      fileContentByte = fileContentByte.substring(0, 1024);
-      String[] fileContentByteArray = IEC102Uitl.stingToArray(fileContentByte);
-      returnMessage[16] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh2(fileContentByteArray.length));
-      FileConstant.fileContentCounter=FileConstant.fileContentCounter+512;
-    }
-
-    returnMessage[17]= fileContentByte;
-    // 获取从[控制域]到[校验和]之前的报文
-    StringBuffer tempSB = new StringBuffer("");
-    for (int i = 4; i <= 17; i++) {
-      tempSB.append(returnMessage[i]);
-    }
-    // 计算校验和
-    String crc = IEC102Uitl.makeChecksum(tempSB.toString());
-    returnMessage[18] = crc;
-    // 计算报文的帧长
-    String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-    String mlLow = ml.substring(0, 2);
-    String mlHeight = ml.substring(2);
-    returnMessage[1] = mlLow;
-    returnMessage[2] = mlHeight;
-    sendMessage = ArrayUtil.join(returnMessage, "");
-    sendMessage = sendMessage.toUpperCase();
-    return sendMessage;
-  }
-
-
-  public String createFileInfo68(UploadObject uploadObject,ChannelHandlerContext ctx,Logger log)throws Exception{
-    String sendMessage = "";
-    // 从待上报的缓存中取一个文件放入次数变量中
-    String fileNameKey="";
-    log.info("find upload file.....");
-    Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
-    for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-      log.info("找到文件===>" + entry.getKey());
-      fileNameKey = entry.getKey();
-      break;
-    }
-    if (!"".equals(fileNameKey)) {
-      // 文件信息68帧
-      String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "cr", "FF", "FF", "ab", "01", "0d", "FF", "FF", "00", "fileNameByte","01","fileLengthByte", "fileContentMD5", "crc", "16"};
-
-      String[] tempKey = new String[3];
-      tempKey[0] = fileNameKey.substring(0, fileNameKey.indexOf("@", 0));
-      String tempFileName = fileNameKey.substring(fileNameKey.indexOf("@", 0) + 1);;
-      tempKey[1] = tempFileName.substring(0, tempFileName.indexOf("@", 0));
-      tempKey[2] = tempFileName.substring(tempFileName.indexOf("@", 0) + 1);
-
-      returnMessage[4] = FileConstant.controlReversal;
-      if (FileConstant.controlReversal.equals("53")){
-        FileConstant.controlReversal = "73";
-      }
-      else{
-        FileConstant.controlReversal = "53";
-      }
-
-      // 获取本地物理文件路径
-      String filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + tempKey[0] + File.separator + tempKey[1] + File.separator + tempKey[2];
-      String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-      String fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-      String[] fileContentByteArray = IEC102Uitl.stingToArray(fileContentByte);
-      returnMessage[15] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(fileContentByteArray.length));
-      // 获取配置文件里上报路径
-//      String uploadPath = this.environment.getProperty("mengxi.uploadpath."+tempKey[1]);
-      String fileNameByte = ByteUtil.Byte2String(tempKey[2].getBytes());
-      fileNameByte = StrUtil.padAfter(fileNameByte.replace(" ", ""), 240, '0');
-      returnMessage[13] = fileNameByte;
-
-      String fileContentOriginal = fileContentOriginal(filePath);
-      returnMessage[16] = FileUtil.getMD5(fileContentOriginal.getBytes(charsetName));
-
-      // 获取从[控制域]到[校验和]之前的报文
-      StringBuffer tempSB = new StringBuffer("");
-      for (int i = 4; i <= 16; i++) {
-        tempSB.append(returnMessage[i]);
-      }
-      // 计算校验和
-      String crc = IEC102Uitl.makeChecksum(tempSB.toString());
-      returnMessage[17] = crc;
-      // 计算报文的帧长
-      String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-      String mlLow = ml.substring(0, 2);
-      String mlHeight = ml.substring(2);
-      returnMessage[1] = mlLow;
-      returnMessage[2] = mlHeight;
-      sendMessage = ArrayUtil.join(returnMessage, "");
-      sendMessage = sendMessage.toUpperCase();
-    }
-    else{
-      log.info("not found file");
-    }
-    return sendMessage;
-  }
-
-  /**
-   * 读取文件内容
-   *
-   * @param filePath
-   * @return
-   */
-  private String fileContentOriginal(String filePath) throws Exception {
-    InputStreamReader isr = null;
-    String fileMessageHex = "";
-    try {
-      isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
-      StringBuffer sb = new StringBuffer("");
-      int len1 = 0;
-      while ((len1 = isr.read()) != -1) {
-        sb.append((char) len1);
-      }
-      isr.close();
-      fileMessageHex = sb.toString();
-    } catch (Exception e) {
-      throw e;
-    } finally {
-      if (isr != null) {
-        try {
-          isr.close();
-        } catch (IOException e) {
-          e.printStackTrace();
-        }
-      }
-    }
-    return fileMessageHex;
-  }
-}

+ 0 - 312
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/SdBase102Service.java

@@ -1,312 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.*;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogDetailRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.console.service.SysParameterService;
-import com.jiayue.ipfcst.fileupload.service.E63.E63UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileCodeService;
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 102业务处理基础类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class SdBase102Service {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  @Autowired
-  UploadFileLogDetailRepository uploadFileLogDetailRepository;
-  @Autowired
-  SysParameterService sysParameterService;
-  @Autowired
-  UploadFileCodeService uploadFileCodeService;
-  @Autowired
-  ElectricFieldService electricFieldService;
-
-
-  /**
-   * 统计文件上报成功或者失败并移动文件
-   *
-   * @param uploadFileChannel 通道信息
-   * @param faileReason       失败原因
-   */
-
-  public void totalFileUploadNums(UploadObject uploadObject, UploadFileChannel uploadFileChannel, String faileReason, Logger log) {
-    // 上报文件次数缓存加1
-//    Map<String, FileMutableInteger> filterMap = FileConstant.uploadCountMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))))
-//      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-//        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-
-    // 上报文件名
-    String fileNameKey = "";
-    Iterator<Map.Entry<String, FileMutableInteger>> filterMap = FileConstant.sdUploadCountMap.entrySet().iterator();
-    while (filterMap.hasNext()) {
-      Map.Entry<String, FileMutableInteger> entry = filterMap.next();
-      String key = entry.getKey();
-      if (key.substring(0,key.indexOf("@")).equals(uploadObject.getObjectNo())) {
-        fileNameKey = key;
-        break;
-      }
-    }
-
-    if (!"".equals(fileNameKey)){
-      String[] keys = new String[3];
-      String tempFileName = fileNameKey;
-      log.info("UploadNums操作文件:"+tempFileName);
-      keys[0] = tempFileName.substring(0,tempFileName.indexOf("@",0));
-      tempFileName = tempFileName.substring(tempFileName.indexOf("@",0)+1);
-      keys[1] = tempFileName.substring(0,tempFileName.indexOf("@",0));
-      keys[2] = tempFileName.substring(tempFileName.indexOf("@",0)+1);
-
-      // 找到文件日志记录
-      //今日凌晨
-//    Long st = DateTimeUtil.getMillisecondsSubDay();
-      //明日凌晨
-//    Long et = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24-1;
-
-//    Date fileCreateTime = FileConstant.fileShouldMomentMap.get(fileNameKey);
-      Integer id = FileConstant.fileShouldMomentMap.get(fileNameKey);
-      UploadFileLog uploadFileLog = null;
-      Optional<UploadFileLog> fileLogOptional = uploadFileLogRepository.findById(id);
-      if (fileLogOptional.isPresent()) {
-        uploadFileLog = fileLogOptional.get();
-      }
-
-      // 先判断是否查出日志,如果没有则认为文件是本地拷贝进去的
-      if (uploadFileLog == null) {
-        UploadFileLog newUploadFileLog = new UploadFileLog();
-        newUploadFileLog.setUploadObjectId(uploadObject.getId());
-        newUploadFileLog.setFileStatusEnum(FileStatusEnum.E1);
-        newUploadFileLog.setUploadProtocolEnum(uploadObject.getUploadProtocolEnum());
-        newUploadFileLog.setFileName(keys[2]);
-        newUploadFileLog.setFileTypeEnum(FileTypeEnum.valueOf(keys[1]));
-        newUploadFileLog.setUploadObjectName(uploadObject.getUploadObjectName());
-        newUploadFileLog.setUploadObjectNo(uploadObject.getObjectNo());
-        newUploadFileLog.setUploadCounter(0);
-        newUploadFileLog.setFileRemarks("当日没找到日志记录,系统插入一条");
-        uploadFileLog = uploadFileLogRepository.save(newUploadFileLog);
-      }
-
-      if ("".equals(faileReason)) {
-        UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-        uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-        uploadFileLogDetail.setUploadFileLogId(uploadFileLog.getId());
-        uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-        uploadFileLogDetail.setFileName(keys[2]);
-        uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-        uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-        uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E2);
-//      fileMutableInteger.getUploadFileLogDetail().add(uploadFileLogDetail);
-        // 上报成功保存数据库,更新上报表,上报明细
-//      uploadFileLogRepository.updateFileUploadCount(FileStatusEnum.E2, fileMutableInteger.getValue(), uploadObject.getId(), keys[2]);
-//        uploadFileLog.setFileStatusEnum(FileStatusEnum.E2);
-//        uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter()+1);
-//        uploadFileLogRepository.save(uploadFileLog);
-        uploadFileLogRepository.uploadFileUpdate(FileStatusEnum.E2,uploadFileLog.getUploadCounter()+1,uploadFileLog.getId());
-        uploadFileLogDetailRepository.save(uploadFileLogDetail);
-        // 将文件移动到成功目录
-        String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-        String targetPath = FileUtil.getFileUploadPath() + File.separator + "backups" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-
-        try {
-          FileUtil.move(srcPath, targetPath);
-        } catch (Exception e) {
-          log.error("上报成功移动文件失败",e);
-        }
-        // 清理缓存
-        FileConstant.sdUploadCountMap.remove(fileNameKey);
-        FileConstant.readyUploadFileMap.remove(fileNameKey);
-        FileConstant.fileShouldMomentMap.remove(fileNameKey);
-        FileConstant.fileContentMap.remove(fileNameKey);
-        FileConstant.againUploadFileMap.remove(fileNameKey);
-        FileConstant.filePackageNumMap.remove(fileNameKey);
-        log.info("上报对象编号:" + keys[0] + " 文件名:" + keys[2] + " 本次上报结果:成功");
-
-      } else {
-        // 保存上报失败明细表
-        UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-        uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-        uploadFileLogDetail.setUploadFileLogId(uploadFileLog.getId());
-        uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-        uploadFileLogDetail.setFileName(keys[2]);
-        uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-        uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-        uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E3);
-        uploadFileLogDetail.setUploadFailureReason(faileReason);
-        uploadFileLog.setFileStatusEnum(FileStatusEnum.E3);
-        uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter()+1);
-        uploadFileLogRepository.save(uploadFileLog);
-        uploadFileLogDetailRepository.save(uploadFileLogDetail);
-
-        if (FileConstant.againUploadFileMap.get(fileNameKey)==null){
-          // 遇到失败,再给这个文件一次上报的机会
-          FileConstant.againUploadFileMap.put(fileNameKey,"");
-          log.info(fileNameKey+"上报结果失败,再报一次变量中存入");
-        }
-        else{
-          // 将文件移动到失败目录
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "error"+ File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-          } catch (Exception e) {
-            log.error("将文件移动到失败目录",e);
-          }
-          FileConstant.readyUploadFileMap.remove(fileNameKey);
-          FileConstant.fileShouldMomentMap.remove(fileNameKey);
-          FileConstant.againUploadFileMap.remove(fileNameKey);
-        }
-        // 清理缓存
-        FileConstant.sdUploadCountMap.remove(fileNameKey);
-        FileConstant.fileContentMap.remove(fileNameKey);
-        FileConstant.filePackageNumMap.remove(fileNameKey);
-        log.info("上报对象编号:" + keys[0] + " 文件名:" + keys[2] + " 本次上报结果失败:" + faileReason);
-      }
-    }
-  }
-
-  /**
-   * 读取文件内容转16进制报文
-   *
-   * @param filePath
-   * @param charsetName
-   * @return
-   */
-  public String createFileMessageHex(String filePath, String charsetName, Logger log) {
-    InputStreamReader isr = null;
-    String fileMessageHex = "";
-    try {
-      isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
-      StringBuffer sb = new StringBuffer("");
-      int len1 = 0;
-      while ((len1 = isr.read()) != -1) {
-        sb.append((char) len1);
-      }
-      isr.close();
-
-      String str = sb.toString();
-      fileMessageHex = ByteUtil.Byte2String(str.getBytes(charsetName));
-      fileMessageHex = fileMessageHex.replaceAll(" ", "");
-      ////////////////////以下注释生成本地文件/////////////////////
-//      int len = fileMessageHex.length();
-//      byte[] data = new byte[len / 2];
-//      for (
-//        int i = 0;
-//        i < len; i += 2) {
-//        data[i / 2] = (byte) ((Character.digit(fileMessageHex.charAt(i), 16) << 4)
-//          + Character.digit(fileMessageHex.charAt(i + 1), 16));
-//      }
-//      OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\sdf.PVD"), charsetName);
-//      String res = new String(data);
-//      osw.write(res);
-//      osw.close();
-    } catch (Exception e) {
-      log.error("读取本地文件失败", e);
-    } finally {
-      if (isr != null) {
-        try {
-          isr.close();
-        } catch (IOException e) {
-          e.printStackTrace();
-        }
-      }
-    }
-    return fileMessageHex;
-  }
-
-  /**
-   * 根据通道过滤缓存Map的key是否存在
-   *
-   * @param uploadObjectNo
-   * @param map
-   * @return
-   */
-  public Map<String, UploadFileLog> filterFileByObjectNo(String uploadObjectNo, Map<String, UploadFileLog> map, Logger log) {
-    // 先过滤出上报对象下的所有文件
-    Map<String, UploadFileLog> filterMap = new HashMap<>();
-    Iterator<Map.Entry<String, UploadFileLog>> it = map.entrySet().iterator();
-    while (it.hasNext()) {
-      Map.Entry<String, UploadFileLog> entry = it.next();
-      if (uploadObjectNo.equals(entry.getKey().substring(0, entry.getKey().indexOf("@")))) {
-        filterMap.put(entry.getKey(), entry.getValue());
-      }
-    }
-    // 再将失效时间的文件移除
-    Map<String, UploadFileLog> fileterFileMap = new HashMap<>();
-    Date d = new Date();
-    for (Map.Entry<String, UploadFileLog> entry : filterMap.entrySet()) {
-      UploadFileLog u = entry.getValue();
-      if (u.getUploadFileEndTime() == null) {
-        // 有效的文件
-        fileterFileMap.put(entry.getKey(), u);
-      } else {
-        if (d.getTime() <= u.getUploadFileEndTime()) {
-          // 有效的文件
-          fileterFileMap.put(entry.getKey(), u);
-        } else {
-          // 过期文件
-          String[] keys = new String[3];
-//          keys[0] = entry.getKey().substring(0,entry.getKey().indexOf("@",0));
-//          keys[1] = entry.getKey().substring(entry.getKey().indexOf("@",1)+1,entry.getKey().indexOf("@",2));
-//          keys[2] = entry.getKey().substring(entry.getKey().indexOf("@",2)+1);
-          keys[0] = entry.getKey().substring(0,entry.getKey().indexOf("@",0));
-          String tempFileName = entry.getKey().substring(entry.getKey().indexOf("@",0)+1);
-          keys[1] = tempFileName.substring(0,tempFileName.indexOf("@",0));
-          keys[2] = tempFileName.substring(tempFileName.indexOf("@",0)+1);
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "expire" + File.separator + keys[0] + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-            log.info("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2]);
-          } catch (Exception e) {
-            log.error("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2] + "失败", e);
-          }
-          // 清理缓存
-          FileConstant.sdUploadCountMap.remove(entry.getKey());
-          FileConstant.againUploadFileMap.remove(entry.getKey());
-          FileConstant.readyUploadFileMap.remove(entry.getKey());
-          FileConstant.fileShouldMomentMap.remove(entry.getKey());
-          FileConstant.fileContentMap.remove(entry.getKey());
-        }
-      }
-    }
-    return fileterFileMap;
-  }
-
-  /**
-   * 获取文件CODE码
-   *
-   * @return
-   */
-  public Map<String, Integer> getFileCode() {
-    List<UploadFileCode> uploadFileCodeList = uploadFileCodeService.get();
-    Map<String, Integer> codeMap = new HashMap<>();
-    for (UploadFileCode uploadFileCode : uploadFileCodeList) {
-      codeMap.put(uploadFileCode.getFileTypeEnum().toString(), uploadFileCode.getFileTypeCode());
-    }
-    return codeMap;
-  }
-}

+ 0 - 144
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongClient.java

@@ -1,144 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.fileupload.IEC102.NettyParent;
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.IdleStateHandler;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * 开启山东客户端
- *
- * @author xsl
- * @version 3.0
- */
-public class ShanDongClient extends NettyParent {
-  private String host;
-  private int port;
-  private Logger log;
-
-  private Bootstrap bootstrap = new Bootstrap();
-  EventLoopGroup workerGroup = new NioEventLoopGroup();
-  private Channel channel;
-  private ChannelFuture future;
-
-  /**
-   * 获取 host
-   *
-   * @return host
-   */
-  public String getHost() {
-    return host;
-  }
-
-  /**
-   * 获取 port
-   *
-   * @return port
-   */
-  public int getPort() {
-    return port;
-  }
-
-  public ShanDongClient(String host, int port, Logger log) {
-    this.host = host;
-    this.port = port;
-    this.log = log;
-    init();
-  }
-
-  /**
-   * 初始化客户端
-   */
-  private void init() {
-    final ShanDongClient client = this;
-    bootstrap.group(workerGroup);
-    bootstrap.channel(NioSocketChannel.class);
-    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
-    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
-      @Override
-      protected void initChannel(SocketChannel ch) {
-        ch.pipeline().addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS));
-        ch.pipeline().addLast("decoder", new ShanDongDecoder(log));
-        ch.pipeline().addLast("encoder", new ShanDongEncoder(log));
-        ch.pipeline().addLast(new ShanDongClientHandler(client, log));
-      }
-    });
-    log.info("客户端初始化完成");
-  }
-
-  /**
-   * 与服务端建立连接
-   * (注册重连机制)
-   */
-  public void start() {
-    future = bootstrap.connect(host, port);
-    if (channel != null && channel.isActive()) {
-      return;
-    }
-    //添加监听器,失连自动重连
-    future.addListener(new ChannelFutureListener() {
-      @Override
-      public void operationComplete(ChannelFuture futureListener) {
-        if (futureListener.isSuccess()) {
-          channel = futureListener.channel();
-          log.info("客户端连接服务端成功[{}:{}]", host, port);
-        } else {
-          log.info("客户端连接服务端失败[{}:{}],将在1分钟后尝试重新建立连接", host, port);
-          futureListener.channel().eventLoop().schedule(new Runnable() {
-            @Override
-            public void run() {
-              try {
-                start();
-              } catch (Exception e) {
-                log.error("客户端重接服务端[" + host + ":" + port + "]失败:e=", e);
-              }
-            }
-          }, 60L, TimeUnit.SECONDS);
-        }
-      }
-    });
-    this.channel = future.channel();
-  }
-
-  /**
-   * 停止服务
-   */
-  public void destroy() {
-    if (future != null) {
-      future.channel().close();
-    }
-    workerGroup.shutdownGracefully();
-    log.info("客户端通道连接销毁成功!");
-  }
-//  /**
-//   * 客户端发送自定义消息
-//   *
-//   * @param msg 消息体
-//   * @throws InterruptedException 中断异常
-//   */
-//  public void send(String msg) throws InterruptedException {
-//    logger.info("client => server [{}:{}] msg:{}", host, port, msg);
-//    FepProtocolMsg protocol = new FepProtocolMsg(FepProtocolMsg.Constants.TYPE_OTHER, msg);
-//    channel.writeAndFlush(protocol).sync();
-//  }
-//
-//  /**
-//   * 客户端发送自定义消息
-//   *
-//   * @param type 消息类型
-//   * @param msg  消息体
-//   * @throws InterruptedException 中断异常
-//   * @see FepProtocolMsg.Constants 消息类型
-//   */
-//  public void send(byte type, String msg) throws InterruptedException {
-//    logger.info("client => server [{}:{}] type:{}, msg:{}", host, port, type, msg);
-//    FepProtocolMsg protocol = new FepProtocolMsg(type, msg);
-//    channel.writeAndFlush(protocol).sync();
-//  }
-}

+ 0 - 257
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongClientHandler.java

@@ -1,257 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.util.RuntimeUtil;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.ChannelDisconLog;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.repository.UploadFileChannelRepository;
-import com.jiayue.ipfcst.console.service.ChannelDisconLogService;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.channel.EventLoop;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-/**
- * 山东客户端Handler
- *
- * @author xsl
- * @version 3.0
- */
-public class ShanDongClientHandler extends ChannelInboundHandlerAdapter {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-  @Autowired
-  ElectricFieldService electricFieldService = SpringContextHolder.getApplicationContext().getBean(ElectricFieldService.class);
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  ShanDongHandlerService shanDongHandlerService = SpringContextHolder.getApplicationContext().getBean(ShanDongHandlerService.class);
-  @Autowired
-  ChannelDisconLogService channelDisconLogService = SpringContextHolder.getApplicationContext().getBean(ChannelDisconLogService.class);
-
-  private UploadFileChannel uploadFileChannel = null;
-
-  private UploadObject uploadObject = null;
-
-  private ShanDongClient client;
-
-  private Logger log;
-
-  ShanDongClientTask task = null;
-
-  public ShanDongClientHandler(ShanDongClient client,Logger log) {
-    this.client = client;
-    this.log = log;
-  }
-
-  /**
-   * 接收服务端消息
-   *
-   * @param ctx channel上下文
-   * @param msg 消息
-   */
-  @Override
-  public void channelRead(ChannelHandlerContext ctx, Object msg) {
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-//    log.info("收到服务端信息:"+msg);
-    // 返回的报文
-    String receiveMessage = shanDongHandlerService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, log,ctx);
-    ctx.channel().writeAndFlush(receiveMessage);
-  }
-
-  /**
-   * 首次建立连接
-   *
-   * @param ctx channel上下文
-   */
-  @Override
-  public void channelActive(ChannelHandlerContext ctx) {
-//    InetSocketAddress localsocket = (InetSocketAddress) ctx.channel().localAddress();
-//    String localIp = localsocket.getAddress().getHostAddress();
-//    String localPort = String.valueOf(localsocket.getPort());
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    String remotePort = String.valueOf(insocket.getPort());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-    // 获取上报对象及通道信息
-//    List<UploadFileChannel> filterUploadFileChannelList = uploadFileChannelList.stream().filter(s -> s.getRemoteIp().equals(remoteIP) && s.getRemotePort().equals(remotePort) && !s.getUploadUserName().equals("") && !s.getUploadPassword().equals("")).collect(Collectors.toList());
-    for (UploadFileChannel u:uploadFileChannelList){
-      if (u.getRemoteIp().equals(remoteIP) && u.getUploadUserName()!=null && !"".equals(u.getUploadUserName())){
-        uploadFileChannel = u;
-        break;
-      }
-    }
-
-    List<UploadObject> uploadObjectList = uploadObjectService.get();
-    Map<Integer, UploadObject> uploadObjectMap = uploadObjectList.stream().collect(Collectors.toMap(UploadObject::getId, a -> a, (k1, k2) -> k1));
-    uploadObject = uploadObjectMap.get(uploadFileChannel.getUploadObjectId());
-
-    // 设置通道状态正常
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-    FileConstant.downLoadFileContentMap.clear();
-    FileConstant.fileContentByIdxMap.clear();
-
-    List<ChannelDisconLog> channelDisconLogList = channelDisconLogService.get(String.valueOf(uploadFileChannel.getId()));
-    if (channelDisconLogList.size()>0){
-      channelDisconLogList.sort(Comparator.comparing(ChannelDisconLog::getCreateTime).reversed());
-      Long reconnectTime = new Date().getTime();
-      ChannelDisconLog channelDisconLog = channelDisconLogList.get(0);
-      channelDisconLog.setReconnectTime(reconnectTime);
-      // 计算时长
-      Long durationL = reconnectTime-channelDisconLog.getDisconnectTime();
-      if (durationL/1000>=60){
-        channelDisconLog.setDuration(String.valueOf(durationL/(1000*60))+"分");
-      }
-      else{
-        channelDisconLog.setDuration(String.valueOf(durationL/1000)+"秒");
-      }
-      channelDisconLogService.save(channelDisconLog);
-    }
-
-    // 客户端每隔一段时间向主站要发电计划
-    task = new ShanDongClientTask(ctx);
-    task.start();
-  }
-
-
-  /**
-   * 空闲发送心跳
-   *
-   * @param ctx channel上下文
-   * @param evt 事件
-   */
-  @Override
-  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
-    log.info("3秒没有收到调度报文,主动发起心跳");
-    ctx.channel().writeAndFlush("6800000000FF0000");
-//    if (evt instanceof IdleStateEvent) {
-//      FepProtocolMsg heartBeat = new FepProtocolMsg(FepProtocolMsg.Constants.TYPE_HEART_BEAT, client.getClientId());
-//      ctx.writeAndFlush(heartBeat);
-//      logger.info("client => server : 心跳");
-//    } else {
-//      super.userEventTriggered(ctx, evt);
-//    }
-  }
-
-  /**
-   * 异常处理
-   *
-   * @param ctx   channel上下文
-   * @param cause 异常
-   */
-  @Override
-  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-    log.error("客户端发生异常:", cause);
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.sdUploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
-      Map.Entry<String,FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        countMap.remove();
-      }
-    }
-
-//    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-//    while (contentMap.hasNext()){
-//      Map.Entry<String,String> entry = contentMap.next();
-//      String key = entry.getKey();
-//      if (key.contains(uploadObject.getObjectNo() + "@")){
-//        contentMap.remove();
-//      }
-//    }
-    Iterator<Map.Entry<String, String>> downLoadFileContentMap = FileConstant.downLoadFileContentMap.entrySet().iterator();
-    while (downLoadFileContentMap.hasNext()){
-      Map.Entry<String,String> entry = downLoadFileContentMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        downLoadFileContentMap.remove();
-      }
-    }
-    ctx.close();
-  }
-
-  /**
-   * 断线重连(10秒不间断重试)
-   */
-  @Override
-  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-    log.info("服务端断开了"+ctx.channel().remoteAddress());
-//    String str = RuntimeUtil.execForStr("ping "+uploadFileChannel.getRemoteIp() +"-c 4");
-//    log.info("ping远程IP结果:"+str);
-    if (task!=null){
-      // 保存通道断开日志
-      ChannelDisconLog channelDisconLog = new ChannelDisconLog();
-      channelDisconLog.setChannelId(String.valueOf(uploadFileChannel.getId()));
-      channelDisconLog.setChannelName(uploadFileChannel.getChannelName());
-      channelDisconLog.setDisconnectTime(new Date().getTime());
-      channelDisconLogService.save(channelDisconLog);
-      // 销毁客户端索要发电计划的线程
-      task.closed();
-    }
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-    final EventLoop eventLoop = ctx.channel().eventLoop();
-    //60秒重新建立连接
-    eventLoop.schedule(new Runnable() {
-      @Override
-      public void run() {
-        try {
-          client.start();
-        } catch (Exception e) {
-          log.error("服务端断开后,客户端重连异常:", e);
-        }
-      }
-    }, 60L, TimeUnit.SECONDS);
-    super.channelInactive(ctx);
-  }
-
-  class ShanDongClientTask extends Thread{
-    private volatile boolean closed = false;
-    ChannelHandlerContext ctx;
-    ShanDongClientTask(ChannelHandlerContext ctx) {
-      this.ctx = ctx;
-    }
-    @Override
-    public void run() {
-      while(!closed && !isInterrupted()){
-        Calendar ca = Calendar.getInstance();
-        try {
-          // 时间间隔5分钟
-          Thread.sleep(300000);
-        } catch (InterruptedException e) {
-          log.info("通道中断,客户端不发送下载发电计划的请求报文!");
-        }
-        if (ca.get(ca.MINUTE) % 5 == 0) {
-          try {
-            // 不整点执行避免与文件上报的一起发送,延时1分钟再发起
-            Thread.sleep(60000);
-          } catch (InterruptedException e) {
-          }
-        }
-        if (!closed && !isInterrupted()) {
-          // 要发电计划报文
-          String planMessage = "6891000000B4010015000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
-          log.info("发送报文{}", planMessage);
-          ctx.writeAndFlush(planMessage);
-        }
-      }
-    }
-    public void closed(){
-      this.closed = true;
-      this.interrupt();
-    }
-  }
-}

+ 0 - 139
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongDecoder.java

@@ -1,139 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.util.ReferenceCountUtil;
-import org.slf4j.Logger;
-
-import javax.xml.bind.DatatypeConverter;
-
-/**
- * 山东102解码
- *
- * @author xsl
- * @version 3.0
- */
-public class ShanDongDecoder extends SimpleChannelInboundHandler {
-  //记录上次未读完的字节
-  ByteBuf tempMessage = Unpooled.buffer();
-
-  private Logger log;
-
-  ShanDongDecoder(Logger log) {
-    this.log = log;
-  }
-
-  @Override
-  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
-    ByteBuf msgCopy = (ByteBuf) msg;
-    int inSize = msgCopy.readableBytes();
-    log.debug("=========本次收到" + inSize + "字节========内容:" + ByteUtil.ByteBuf2String(msgCopy));
-    if (inSize > 0) {
-      // tempMessage为缓存区,在此缓存解码报文
-      if (tempMessage.readableBytes() == 0) {
-        tempMessage = msgCopy.copy(0, inSize);
-      } else {
-        tempMessage.writeBytes(msgCopy);
-      }
-
-      // 显示当前缓存里的内容
-      if (tempMessage.readableBytes() > 0) {
-        byte[] tempByte = new byte[tempMessage.readableBytes()];
-        tempMessage.readBytes(tempByte);
-//        String tempByteInfo = DatatypeConverter.printHexBinary(tempByte);
-//        log.debug("当前缓存中报文内容:" + tempByteInfo);
-      }
-
-      // 读下标重置
-      tempMessage.resetReaderIndex();
-      // 6个以上字节才报文解码
-      if (tempMessage.readableBytes() >= 8) {
-        // 此变量为了一串报文能继续往下解码
-        int i = 0;
-        while (true) {
-          String message = "";
-          // 检查68的下标位置
-          int s68 = tempMessage.indexOf(i, tempMessage.readableBytes(), (byte) 104);
-          if (s68==-1 || tempMessage.readableBytes() - s68 < 8) {
-            // 没有68字节或者68字节后面不够8个退出(至少满足心跳帧)
-            break;
-          }
-          // 获取应用数据长度
-          ByteBuf dataLengthBuf = tempMessage.copy(s68 + 1, 4);
-          byte[] bf = new byte[dataLengthBuf.readableBytes()];
-          dataLengthBuf.readBytes(bf);
-          int dataLength = ByteUtil.bytesToIntFromLowToHigh(bf);
-          if (dataLength == 0) {
-            ByteBuf messageBuf = tempMessage.copy(s68, 8);
-            byte[] messageByte = new byte[messageBuf.readableBytes()];
-            messageBuf.readBytes(messageByte);
-            message = DatatypeConverter.printHexBinary(messageByte);
-            handlerLoseMessage(s68, tempMessage);
-            tempMessage.readerIndex(s68 + 8);
-            tempMessage.discardReadBytes();
-            ReferenceCountUtil.release(messageBuf);
-          } else {
-            if (tempMessage.isReadable((s68 + 1) + 7 + dataLength)) {
-              ByteBuf messageBuf = tempMessage.copy(s68, (s68 + 1) + 7 + dataLength);
-              byte[] messageByte = new byte[messageBuf.readableBytes()];
-              messageBuf.readBytes(messageByte);
-              message = DatatypeConverter.printHexBinary(messageByte);
-              handlerLoseMessage(s68, tempMessage);
-              tempMessage.readerIndex((s68 + 1) + 7 + dataLength);
-              tempMessage.discardReadBytes();
-              ReferenceCountUtil.release(messageBuf);
-            }
-          }
-          if (!"".equals(message)) {
-            // 解码成功将下标重置0为了继续下一个解码循环
-            i = 0;
-            ctx.fireChannelRead(message);
-          } else {
-            i = s68 + 1;
-          }
-          ReferenceCountUtil.release(dataLengthBuf);
-        }
-      }
-
-      // 缓存超过范围丢弃所有的内容
-      if (tempMessage.readableBytes() > 2048) {
-        byte[] clearByte = new byte[tempMessage.readableBytes()];
-        tempMessage.readBytes(clearByte);
-        String clearInfo = DatatypeConverter.printHexBinary(clearByte);
-        log.debug("无效报文超过范围数量舍弃:" + clearInfo);
-        ReferenceCountUtil.release(tempMessage);
-        tempMessage = Unpooled.buffer();
-      }
-
-      // 显示解码后剩余的报文
-      if (tempMessage.readableBytes() > 0) {
-        byte[] leftOverByte = new byte[tempMessage.readableBytes()];
-        tempMessage.readBytes(leftOverByte);
-        String leftOverInfo = DatatypeConverter.printHexBinary(leftOverByte);
-        log.debug("剩余的报文:" + leftOverInfo);
-      }
-      tempMessage.resetReaderIndex();
-    }
-  }
-
-  /**
-   * 显示头之前没用的报文
-   *
-   * @param useHeadIndex
-   * @param inMessage
-   */
-  private void handlerLoseMessage(int useHeadIndex, ByteBuf inMessage) {
-    if (useHeadIndex > 0) {
-      // 舍弃的报文
-      ByteBuf loseMessage = inMessage.copy(0, useHeadIndex);
-      byte[] loseByte = new byte[loseMessage.readableBytes()];
-      loseMessage.readBytes(loseByte);
-      String loseInfo = DatatypeConverter.printHexBinary(loseByte);
-      log.debug("舍弃的报文:" + loseInfo);
-      ReferenceCountUtil.release(loseMessage);
-    }
-  }
-}

+ 0 - 28
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongEncoder.java

@@ -1,28 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.MessageToByteEncoder;
-import lombok.extern.slf4j.Slf4j;
-import org.slf4j.Logger;
-
-import java.math.BigInteger;
-
-/**
- * 山东102编码
- *
- * @author xsl
- * @version 3.0
- */
-public class ShanDongEncoder extends MessageToByteEncoder<String> {
-  private Logger log;
-
-  ShanDongEncoder(Logger log) {
-    this.log = log;
-  }
-    @Override
-    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
-      BigInteger bigint=new BigInteger(msg, 16);
-      out.writeBytes(bigint.toByteArray());
-    }
-}

+ 0 - 467
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongHandlerService.java

@@ -1,467 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import cn.hutool.core.map.MapUtil;
-import cn.hutool.core.util.ArrayUtil;
-import cn.hutool.core.util.StrUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.fileupload.util.*;
-import io.netty.channel.ChannelHandlerContext;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-import java.io.*;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-/**
- * 山东业务处理类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class ShanDongHandlerService extends SdBase102Service {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-
-  @Transactional(propagation = Propagation.REQUIRED)
-  public String handlerMessage(String receiveMessage, UploadObject uploadObject, UploadFileChannel uploadFileChannel, Logger log, ChannelHandlerContext ctx) {
-    String[] rmArray = IEC102Uitl.stingToArray(receiveMessage);
-    String sendMessage = "";
-    String sendCtrlChinese = "";
-    String receiveCtrlChinese = "";
-
-    // 判断ASDU类型
-    if ("FF".equals(rmArray[5])) {
-      receiveCtrlChinese = "心跳";
-      // 心跳
-      sendMessage = "6800000000FF0000";
-      sendCtrlChinese = "心跳";
-    } else if ("FE".equals(rmArray[5])) {
-      if ("0101".equals(rmArray[6] + rmArray[7])) {
-        // 主站召唤用户名密码
-        receiveCtrlChinese = "主站召唤用户名密码";
-        String[] returnMessage = {"68", "3C", "00", "00", "00", "FE", "00", "00", "18", "userNameHex", "passWordHex"};
-        try {
-          // 用户名转16进制并且30字节用0补全
-          String userNameHex = ByteUtil.bytesToHexStringFromHighToLow(uploadFileChannel.getUploadUserName().getBytes("UTF-8"));
-          returnMessage[9] = StrUtil.padAfter(userNameHex, 30 * 2, '0');
-          // 密码转16进制并且30字节用0补全
-          String passWordHex = ByteUtil.bytesToHexStringFromHighToLow(uploadFileChannel.getUploadPassword().getBytes("UTF-8"));
-          returnMessage[10] = StrUtil.padAfter(passWordHex, 30 * 2, '0');
-        } catch (UnsupportedEncodingException e) {
-          log.error(ctx.channel().remoteAddress()+" - "+"用户名密码转码异常:", e);
-        }
-        sendMessage = ArrayUtil.join(returnMessage, "");
-        sendCtrlChinese = "子站应答用户名密码";
-      } else if ("0001".equals(rmArray[6] + rmArray[7]) && "20".equals(rmArray[8])) {
-        // 子站不用响应主站的报文
-        receiveCtrlChinese = "主站回复用户名密码认证成功";
-      } else if ("0001".equals(rmArray[6] + rmArray[7]) && !"20".equals(rmArray[8])) {
-        // 子站不用响应主站的报文
-        receiveCtrlChinese = "主站回复用户名密码认证失败";
-      } else {
-        receiveCtrlChinese = "主站报文程序无法解析";
-      }
-    } else {
-      // 判断主站索要的ASDU文件类型是否存在
-      int fileTypeCode = ByteUtil.hexToDec(rmArray[5]);
-      String fileType = "";
-
-      if (fileTypeCode==180){
-        fileType = "B4";
-      }
-      else{
-        Map<String,Integer> codeMap = super.getFileCode();
-        for (Map.Entry<String, Integer> entry : codeMap.entrySet()) {
-          if (entry.getKey().equals("E1")||entry.getKey().equals("E2")||entry.getKey().equals("E4")||entry.getKey().equals("E5")||entry.getKey().equals("E11")||entry.getKey().equals("E12")||entry.getKey().equals("E15")||entry.getKey().equals("E16")||entry.getKey().equals("E17")||entry.getKey().equals("E18")||entry.getKey().equals("E19")){
-            if (fileTypeCode == entry.getValue().intValue()){
-              fileType = entry.getKey();
-            }
-          }
-        }
-      }
-
-      if (StringUtils.isEmpty(fileType)) {
-        receiveCtrlChinese = "主站报文里文件类型码没找到,子站无法解析";
-        String[] rmArrayCopy = ArrayUtil.clone(rmArray);
-        rmArrayCopy[6] = "00";
-        rmArrayCopy[7] = "00";
-        rmArrayCopy[8] = "13";
-        sendMessage = ArrayUtil.join(rmArrayCopy, "");
-        sendCtrlChinese = "本地没有" + fileType + "文件上报";
-      }
-      else if ("B4".equals(fileType)) {// 下载的发电计划
-        if ("13".equals(rmArray[8])) {
-          receiveCtrlChinese = "主站没有发电计划文件";
-        }
-        else if ("16".equals(rmArray[8])) {
-          receiveCtrlChinese = "主站有发电计划文件";
-          String[] rmArrayCopy = ArrayUtil.clone(rmArray);
-          rmArrayCopy[6] = "01";
-          rmArrayCopy[7] = "00";
-          rmArrayCopy[8] = "17";
-          sendMessage = ArrayUtil.join(rmArrayCopy, "");
-          sendCtrlChinese = "子站召唤发电计划文件";
-        }
-        else if ("07".equals(rmArray[8])) {
-          // 最后一帧
-          receiveCtrlChinese = "主站传送最后一帧的发电计划文件";
-          String fileNameHex = "";
-          //取文件名报文
-          for (int i = 9; i < 128; i++) {
-            if ("00".equals(rmArray[i])) {
-              break;
-            }
-            fileNameHex = fileNameHex + rmArray[i];
-          }
-          String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-          String planFileName = "";
-          try {
-            planFileName = new String(ByteUtil.toByteArray(fileNameHex), charsetName);
-          } catch (UnsupportedEncodingException e) {
-            log.error(ctx.channel().remoteAddress()+" - "+"在接收发电计划时转换文件名失败:",e);
-          }
-
-          // 获取本次文件内容
-          String tempStr = "";
-          if (FileConstant.downLoadFileContentMap.get(uploadObject.getObjectNo() + "-B4") != null) {
-            // 上次剩余的
-            tempStr = FileConstant.downLoadFileContentMap.get(uploadObject.getObjectNo() + "-B4");
-          }
-          String fileContentHex = tempStr + receiveMessage.substring(306);
-
-          OutputStreamWriter osw = null;
-          try {
-            int len = fileContentHex.length();
-            byte[] data = new byte[len / 2];
-            for (int i = 0; i < len; i += 2) {
-              data[i / 2] = (byte) ((Character.digit(fileContentHex.charAt(i), 16) << 4) + Character.digit(fileContentHex.charAt(i + 1), 16));
-            }
-            String downLoadPath = FileUtil.getDownloadFilePath() + File.separator + "sdpowerplan" + File.separator + "new";
-            File destDir = new File(downLoadPath);
-            if (!destDir.exists()) {// 如果目录不存在则创建目录
-              boolean b = destDir.mkdirs();
-              if (!b) // 如果创建失败则抛出异常
-                throw new RuntimeException(downLoadPath + " 目录创建失败");
-            }
-            osw = new OutputStreamWriter(new FileOutputStream(downLoadPath+File.separator+planFileName),"UTF-8");
-            String res = new String(data,charsetName);
-            osw.write(res);
-            osw.close();
-            sendCtrlChinese = "子站接收发电计划成功";
-            sendMessage="6891000000B400000A";
-          } catch (Exception e) {
-            log.error(ctx.channel().remoteAddress()+" - "+"保存发电计划失败:",e);
-            sendCtrlChinese = "子站接收发电计划失败";
-            sendMessage="6891000000B4000014";
-          } finally {
-            if (osw != null) {
-              try {
-                osw.close();
-              } catch (IOException e) {
-                log.error(ctx.channel().remoteAddress()+" - "+"保存发电计划关闭流失败",e);
-              }
-            }
-          }
-          sendMessage = sendMessage+receiveMessage.substring(18,298)+"00000000";
-          FileConstant.downLoadFileContentMap.remove(uploadObject.getObjectNo() + "-B4");
-        }
-        else if ("08".equals(rmArray[8])) {
-          // 不是最后一帧
-          receiveCtrlChinese = "主站传送不是最后一帧的发电计划文件";
-          StringBuffer tempSB = new StringBuffer("6891000000B4010017");
-          for (int i = 9; i <= 136; i++) {
-            tempSB.append(rmArray[i]);
-          }
-          tempSB.append("0000000000000000");
-          sendMessage = tempSB.toString();
-          // 将文件内容放入临时变量中,等待最后一帧
-          String tempStr = "";
-          if (FileConstant.downLoadFileContentMap.get(uploadObject.getObjectNo() + "-B4") != null) {
-            // 上次剩余的
-            tempStr = FileConstant.downLoadFileContentMap.get(uploadObject.getObjectNo() + "-B4");
-          }
-          // 将本次文件内容也存入临时变量中
-          FileConstant.downLoadFileContentMap.put(uploadObject.getObjectNo() + "-B4", tempStr + receiveMessage.substring(306));
-          sendCtrlChinese = "子站召唤下一帧发电计划文件";
-        }
-        else{
-          receiveCtrlChinese = "主站报文里文件类型码没找到,子站无法解析";
-        }
-      }
-      else {
-        if ("15".equals(rmArray[8])) {
-          String finalFileType = fileType;
-          Map<String, FileMutableInteger> filterMap = FileConstant.sdUploadCountMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))) && finalFileType.equals(r.getKey().substring(r.getKey().indexOf("@") + 1, r.getKey().lastIndexOf("@"))))
-            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-              (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-
-          // 上报文件名
-          String fileNameKey = "";
-          String filePath = "";
-          if (MapUtil.isNotEmpty(filterMap)) {
-            // 不是第一次要文件了
-            for (Map.Entry<String, FileMutableInteger> entry : filterMap.entrySet()) {
-              fileNameKey = entry.getKey();
-              break;
-            }
-          }
-
-          if ("".equals(fileNameKey)) {
-            // 从待上报缓存中取文件类型
-            Map<String, UploadFileLog> readyUploadFileMap = sdFilterFileByChannelNo(uploadObject.getObjectNo(), fileType, FileConstant.readyUploadFileMap,log);
-            for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-              // 从待上报缓存中取一个加入到累计次数变量中
-              FileMutableInteger fileMutableInteger = new FileMutableInteger(0);
-              FileConstant.sdUploadCountMap.put(entry.getKey(), fileMutableInteger);
-              fileNameKey = entry.getKey();
-              String[] keys = fileNameKey.split("@");
-              filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-              break;
-            }
-          } else {
-            String[] keys = fileNameKey.split("@");
-            filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          }
-
-          String fileTypeName = FileTypeEnum.valueOf(fileType).getMessage();
-          receiveCtrlChinese = "召唤" + fileTypeName + "文件信息";
-
-          if ("".equals(filePath)) {
-            // 说明没有文件上报
-            String[] rmArrayCopy = ArrayUtil.clone(rmArray);
-            rmArrayCopy[6] = "00";
-            rmArrayCopy[7] = "00";
-            rmArrayCopy[8] = "13";
-            sendMessage = ArrayUtil.join(rmArrayCopy, "");
-            sendCtrlChinese = "没有" + fileTypeName + "文件上报";
-          } else {
-            String[] returnMessage = {"68", "91", "00", "00", "00", rmArray[5], "00", "00", "16", "fileNameHex", "fileTimeHex", "fileContentLengthHex", "00000000", "00000000"};
-            String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-            // 产生上报信息
-            String[] tempKey = fileNameKey.split("@");
-            // 生成文件名
-            String fileName = tempKey[2];
-            byte[] tempFileNameBytes = null;
-            try {
-              tempFileNameBytes = fileName.getBytes(charsetName);
-            } catch (Exception e) {
-              log.error("转换文件名编码失败", e);
-            }
-            // 获取文件名称长度
-            String fileNameLength = uploadFileChannel.getUploadFileNameLengthEnum().getMessage();
-            String fileNameByte = ByteUtil.Byte2String(tempFileNameBytes);
-            returnMessage[9] = StrUtil.padAfter(fileNameByte.replace(" ", ""), Integer.parseInt(fileNameLength) * 2, '0');
-            String fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-            String[] fileContentByteArray = IEC102Uitl.stingToArray(fileContentByte);
-            returnMessage[11] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(fileContentByteArray.length));
-            Long fileCreateTime = FileUtil.getFileCreateTime(filePath);
-            returnMessage[10] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(ByteUtil.hexToDec(Long.toHexString(fileCreateTime))));
-            sendCtrlChinese = "找到" + fileTypeName + "文件上报:" + fileName;
-            sendMessage = ArrayUtil.join(returnMessage, "");
-          }
-        } else if ("17".equals(rmArray[8])) {
-          // 召唤需要传输的文件数据
-          String finalFileType1 = fileType;
-          Map<String, FileMutableInteger> filterMap = FileConstant.sdUploadCountMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))) && finalFileType1.equals(r.getKey().substring(r.getKey().indexOf("@") + 1, r.getKey().lastIndexOf("@"))))
-            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-              (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-          String fileTypeName = FileTypeEnum.valueOf(fileType).getMessage();
-
-          receiveCtrlChinese = "召唤" + fileTypeName + "文件数据";
-
-          String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-
-          if (MapUtil.isNotEmpty(filterMap)) {
-            String fileNameKey = "";
-            String filePath = "";
-            // 取上报的文件名
-            for (Map.Entry<String, FileMutableInteger> entry : filterMap.entrySet()) {
-              fileNameKey = entry.getKey();
-              String[] keys = fileNameKey.split("@");
-              filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-              break;
-            }
-
-            String[] returnMessage = {"68", "dataLengthHex", rmArray[5], "00", "00", "messageEnd", "fileNameHex", "fileTimeHex", "fileCountLengthHex", "contentIdx", "fileContentLength", "fileData"};
-            String fileContentStartIndex = "";
-            // 获取缓存中文件内容
-            Map<String, String> fileContentMap = new HashMap<>();
-
-            String fileContentByte = "";
-            if (FileConstant.fileContentByIdxMap.get(fileNameKey) == null) {
-              // 缓存中没有文件内容则新生成文件内容报文
-              fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-              fileContentMap.put("contentByteIdx", "0");
-            } else {
-              fileContentMap = FileConstant.fileContentByIdxMap.get(fileNameKey);
-              fileContentByte = fileContentMap.get("fileContent");
-            }
-            String[] fileContentByteArray = IEC102Uitl.stingToArray(fileContentByte);
-            // 获取通道单次文件传输字节
-            String singleByte = uploadFileChannel.getUploadFileSingleByteEnum().getMessage();
-            // 减去145,因应用数据长度包含文件名、文件生成时间、文件总长度等等的字节数
-            int maxFileContentByte = (Integer.parseInt(singleByte)*20 - 145);
-
-            String[] tempKey = fileNameKey.split("@");
-            // 生成文件名
-            String fileName = tempKey[2];
-            byte[] tempFileNameBytes = null;
-            try {
-              tempFileNameBytes = fileName.getBytes(charsetName);
-            } catch (Exception e) {
-              log.error("转换文件名编码失败", e);
-            }
-            // 本次传输的文件内容字节
-            String[] contentByteArray = null;
-            if (fileContentByteArray.length <= maxFileContentByte) {
-              // 一次可以传输完,生成控制域码
-              returnMessage[5] = "07";
-              Integer idx = Integer.parseInt(fileContentMap.get("contentByteIdx"));
-              if (idx != 0) {
-                // 最后一次的传输
-                idx = idx + 1;
-              }
-              fileContentStartIndex = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(idx));
-              FileConstant.fileContentByIdxMap.remove(fileNameKey);
-              contentByteArray = fileContentByteArray;
-              sendCtrlChinese = "最后一帧传输" + fileTypeName + "文件完成:"+fileName;
-            } else {
-              // 生成不是最后一帧控制域码
-              returnMessage[5] = "08";
-              Map<String, String> tempContentMap = new HashMap<>();
-              String[] remainFileContent = new String[fileContentByteArray.length-maxFileContentByte];
-              System.arraycopy(fileContentByteArray,maxFileContentByte,remainFileContent,0,fileContentByteArray.length-maxFileContentByte);
-              // 将剩余的文件内容报文存入缓存中
-              tempContentMap.put("fileContent", ArrayUtil.join(remainFileContent,""));
-              // 上次字节结束的位置
-              Integer lastIdx = Integer.parseInt(fileContentMap.get("contentByteIdx"));
-              if (lastIdx == 0) {
-                fileContentStartIndex = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(0));
-              } else {
-                fileContentStartIndex = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(lastIdx + 1));
-              }
-              tempContentMap.put("contentByteIdx", String.valueOf(lastIdx+maxFileContentByte-1));
-              FileConstant.fileContentByIdxMap.put(fileNameKey, tempContentMap);
-              // 本次传输的文件内容字节
-              contentByteArray = java.util.Arrays.copyOf(fileContentByteArray,maxFileContentByte);
-              sendCtrlChinese = "分包传输" + fileTypeName + "文件:"+fileName;
-            }
-
-            String fileNameLength = uploadFileChannel.getUploadFileNameLengthEnum().getMessage();
-            String fileNameByte = ByteUtil.Byte2String(tempFileNameBytes);
-
-            // 文件名长度
-            returnMessage[6] = StrUtil.padAfter(fileNameByte.replace(" ", ""), Integer.parseInt(fileNameLength) * 2, '0');
-            String fileCountLengthHex = super.createFileMessageHex(filePath, charsetName, log);
-            // 文件总长度
-            returnMessage[8] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(fileCountLengthHex.length() / 2));
-            Long fileCreateTime = FileUtil.getFileCreateTime(filePath);
-            // 文件时间
-            returnMessage[7] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(ByteUtil.hexToDec(Long.toHexString(fileCreateTime))));
-            // 文件偏移量
-            returnMessage[9] = fileContentStartIndex;
-            // 本包传输的文件内容数据长度
-            returnMessage[10] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(contentByteArray.length));
-            // 本包传输的文件内容数据
-            returnMessage[11] =  ArrayUtil.join(contentByteArray,"");
-
-            // 计算校验和,获取从[控制域]到[校验和]之前的报文
-            StringBuffer tempSB = new StringBuffer("");
-            for (int i = 5; i <= 11; i++) {
-              tempSB.append(returnMessage[i]);
-            }
-            // 计算应用数据长度
-            returnMessage[1] = ByteUtil.bytesToHexStringFromHighToLow(ByteUtil.intToBytesFromLowToHigh(tempSB.length() / 2));
-            sendMessage = ArrayUtil.join(returnMessage, "");
-          } else {
-            // 上报次数缓存中没有此通道的文件,无法上报
-            String[] rmArrayCopy = ArrayUtil.clone(rmArray);
-            rmArrayCopy[6] = "00";
-            rmArrayCopy[7] = "00";
-            rmArrayCopy[8] = "13";
-            sendMessage = ArrayUtil.join(rmArrayCopy, "");
-            sendCtrlChinese = "由于主站不正常交互,回复无文件";
-          }
-        } else if ("0A".equals(rmArray[8])) {
-          String fileTypeName = FileTypeEnum.valueOf(fileType).getMessage();
-          receiveCtrlChinese = "主站接收" + fileTypeName + "文件成功";
-          super.totalFileUploadNums(uploadObject,uploadFileChannel, "", log);
-        } else if ("14".equals(rmArray[8])) {
-          String fileTypeName = FileTypeEnum.valueOf(fileType).getMessage();
-          receiveCtrlChinese = "主站接收" + fileTypeName + "文件失败";
-          super.totalFileUploadNums(uploadObject,uploadFileChannel, receiveCtrlChinese, log);
-        }
-      }
-    }
-    log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-    if (!"".equals(sendMessage)) {
-      log.info(ctx.channel().remoteAddress()+" - "+"发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage.toUpperCase()));
-    }
-    return sendMessage.toUpperCase();
-  }
-
-  /**
-   * 根据通道过滤缓存Map的key是否存在
-   *
-   * @param channelNo
-   * @param map
-   * @return
-   */
-  private Map<String, UploadFileLog> sdFilterFileByChannelNo(String channelNo, String fileType, Map<String, UploadFileLog> map,Logger log) {
-    Map<String, UploadFileLog> filterMap = map.entrySet().stream().filter(r -> channelNo.equals(r.getKey().substring(0, r.getKey().indexOf("@"))) && fileType.equals(r.getKey().substring(r.getKey().indexOf("@") + 1, r.getKey().lastIndexOf("@"))))
-      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-
-    // 再将失效时间的文件移除
-    Map<String, UploadFileLog> fileterFileMap = new HashMap<>();
-    Date d = new Date();
-    for (Map.Entry<String, UploadFileLog> entry : filterMap.entrySet()) {
-      UploadFileLog u = entry.getValue();
-
-      if (u.getUploadFileEndTime()!=null){
-        if (d.getTime()>u.getUploadFileEndTime()){
-          // 过期文件
-          String[] keys = entry.getKey().split("@");
-          String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "expire" + File.separator + keys[0] + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[1];
-          try {
-            FileUtil.move(srcPath, targetPath);
-            log.info("上报对象编号:"+keys[0]+",将过期的文件移到expire过期文件夹下:"+keys[2]);
-            u.setFileStatusEnum(FileStatusEnum.E7);
-            uploadFileLogRepository.save(u);
-          } catch (Exception e) {
-            log.error("上报对象编号:"+keys[0]+",将过期的文件移到expire过期文件夹下:"+keys[2]+"失败",e);
-          }
-          // 清理缓存
-          FileConstant.sdUploadCountMap.remove(entry.getKey());
-          FileConstant.readyUploadFileMap.remove(entry.getKey());
-//          FileConstant.fileContentMap.remove(entry.getKey());
-          FileConstant.againUploadFileMap.remove(entry.getKey());
-        }
-        else{
-          // 有效的文件
-          fileterFileMap.put(entry.getKey(),u);
-        }
-      }
-      else{
-        // 有效的文件
-        fileterFileMap.put(entry.getKey(),u);
-      }
-    }
-    return fileterFileMap;
-  }
-}

+ 0 - 75
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongServer.java

@@ -1,75 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.fileupload.IEC102.NettyParent;
-import com.jiayue.ipfcst.fileupload.IEC102.ServerFor102InitChannel;
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-
-import java.net.InetSocketAddress;
-
-/**
- * 开启山东服务端
- *
- * @author xsl
- * @version 3.0
- */
-public class ShanDongServer extends NettyParent {
-  private Logger log;
-  public ChannelFuture future = null;
-  private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
-  private final EventLoopGroup workerGroup = new NioEventLoopGroup(1);
-  public String localPort = "";
-  InetSocketAddress socketAddress = null;
-
-  public ShanDongServer(InetSocketAddress socketAddress,Logger log){
-    this.socketAddress = socketAddress;
-    this.log = log;
-  }
-
-  public void start() {
-    ServerBootstrap bootstrap = new ServerBootstrap()
-      .group(bossGroup, workerGroup)
-      .channel(NioServerSocketChannel.class)
-      .childHandler(new ChannelInitializer<SocketChannel>() {
-        @Override
-        protected void initChannel(SocketChannel ch) {
-          ch.pipeline().addLast("decoder", new ShanDongDecoder(log));
-          ch.pipeline().addLast("encoder", new ShanDongEncoder(log));
-          ch.pipeline().addLast(new ShanDongServerHandler(log));
-        }
-      })
-      .localAddress(socketAddress)
-      //设置队列大小
-      .option(ChannelOption.SO_BACKLOG, 1024)
-      // 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
-      .childOption(ChannelOption.SO_KEEPALIVE, true);
-    try {
-      this.localPort = String.valueOf(socketAddress.getPort());
-      future = bootstrap.bind(socketAddress).sync();
-      log.info("山东102服务器启动开始监听端口: {}", socketAddress.getPort());
-    } catch (Exception e) {
-      e.printStackTrace();
-      log.error("山东102服务端口: {}失败", socketAddress.getPort(), e);
-    }
-  }
-
-  /**
-   * 停止服务
-   */
-  public void destroy() {
-    if (future != null) {
-      future.channel().close();
-    }
-    workerGroup.shutdownGracefully();
-    bossGroup.shutdownGracefully();
-    log.info("服务端通道连接销毁成功!");
-  }
-
-}

+ 0 - 178
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongServerHandler.java

@@ -1,178 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import cn.hutool.core.util.RuntimeUtil;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.ChannelDisconLog;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.console.service.ChannelDisconLogService;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 山东服务端Handler
- *
- * @author xsl
- * @version 3.0
- */
-public class ShanDongServerHandler extends ChannelInboundHandlerAdapter {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-  @Autowired
-  ElectricFieldService electricFieldService = SpringContextHolder.getApplicationContext().getBean(ElectricFieldService.class);
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  ShanDongHandlerService shanDongHandlerService = SpringContextHolder.getApplicationContext().getBean(ShanDongHandlerService.class);
-  @Autowired
-  ChannelDisconLogService channelDisconLogService = SpringContextHolder.getApplicationContext().getBean(ChannelDisconLogService.class);
-
-  private Logger log;
-
-  ShanDongServerHandler(Logger log) {
-    this.log = log;
-  }
-
-  private UploadFileChannel uploadFileChannel = null;
-
-  private UploadObject uploadObject = null;
-
-  ShanDongServerTask task = null;
-
-  /**
-   * 客户端连接会触发
-   */
-  @Override
-  public void channelActive(ChannelHandlerContext ctx) throws Exception {
-    log.info(ctx.channel().remoteAddress() + "接入通道");
-    InetSocketAddress localsocket = (InetSocketAddress) ctx.channel().localAddress();
-    String localIp = localsocket.getAddress().getHostAddress();
-    String localPort = String.valueOf(localsocket.getPort());
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-//    // 获取远程IP
-//    String clientIP = insocket.getAddress().getHostAddress();
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-    // 获取上报对象及通道信息
-    List<UploadFileChannel> filterUploadFileChannelList = uploadFileChannelList.stream().filter(s -> s.getLocalIp().equals(localIp) && s.getLocalPort().equals(localPort)).collect(Collectors.toList());
-    uploadFileChannel = filterUploadFileChannelList.get(0);
-    List<UploadObject> uploadObjectList = uploadObjectService.get();
-    Map<Integer, UploadObject> uploadObjectMap = uploadObjectList.stream().collect(Collectors.toMap(UploadObject::getId, a -> a, (k1, k2) -> k1));
-    uploadObject = uploadObjectMap.get(uploadFileChannel.getUploadObjectId());
-
-    // 设置通道状态正常
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-    FileConstant.downLoadFileContentMap.clear();
-    FileConstant.fileContentByIdxMap.clear();
-
-    List<ChannelDisconLog> channelDisconLogList = channelDisconLogService.get(String.valueOf(uploadFileChannel.getId()));
-    if (channelDisconLogList.size()>0){
-      channelDisconLogList.sort(Comparator.comparing(ChannelDisconLog::getCreateTime).reversed());
-      Long reconnectTime = new Date().getTime();
-      ChannelDisconLog channelDisconLog = channelDisconLogList.get(0);
-      channelDisconLog.setReconnectTime(reconnectTime);
-      // 计算时长
-      Long durationL = reconnectTime-channelDisconLog.getDisconnectTime();
-      if (durationL/1000>=60){
-        channelDisconLog.setDuration(String.valueOf(durationL/(1000*60))+"分");
-      }
-      else{
-        channelDisconLog.setDuration(String.valueOf(durationL/1000)+"秒");
-      }
-      channelDisconLogService.save(channelDisconLog);
-    }
-
-    // 服务端每隔一段时间向主站要发电计划
-    task = new ShanDongServerHandler.ShanDongServerTask(ctx);
-    task.start();
-  }
-
-  /**
-   * 客户端发消息会触发
-   */
-  @Override
-  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-    // 返回的报文
-    String receiveMessage = shanDongHandlerService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, log,ctx);
-    ctx.channel().writeAndFlush(receiveMessage);
-  }
-
-  /**
-   * 发生异常触发
-   */
-  @Override
-  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-    log.error("102上报异常", cause);
-//    ctx.close();
-  }
-
-  /**
-   * 通道断开触发
-   */
-  @Override
-  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-    log.info("服务端断开了"+ctx.channel().remoteAddress());
-    String str = RuntimeUtil.execForStr("ping "+uploadFileChannel.getRemoteIp() +"-c 4");
-    log.info("ping远程IP结果:"+str);
-    if (task!=null){
-      // 销毁客户端索要发电计划的线程
-      task.closed();
-    }
-    // 设置通道状态不通
-    FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-    // 保存通道断开日志
-    ChannelDisconLog channelDisconLog = new ChannelDisconLog();
-    channelDisconLog.setChannelId(String.valueOf(uploadFileChannel.getId()));
-    channelDisconLog.setChannelName(uploadFileChannel.getChannelName());
-    channelDisconLog.setDisconnectTime(new Date().getTime());
-    channelDisconLogService.save(channelDisconLog);
-    super.channelInactive(ctx);
-  }
-
-  class ShanDongServerTask extends Thread{
-    private volatile boolean closed = false;
-    ChannelHandlerContext ctx;
-    ShanDongServerTask(ChannelHandlerContext ctx) {
-      this.ctx = ctx;
-    }
-    @Override
-    public void run() {
-      while(!closed && !isInterrupted()){
-        Calendar ca = Calendar.getInstance();
-        try {
-          // 时间间隔5分钟
-          Thread.sleep(60000);
-        } catch (InterruptedException e) {
-          log.info("通道中断,服务端不发送下载发电计划的请求报文!");
-        }
-        if (ca.get(ca.MINUTE) % 5 == 0) {
-          try {
-            // 不整点执行避免与文件上报的一起发送,延时1分钟再发起
-            Thread.sleep(60000);
-          } catch (InterruptedException e) {
-          }
-        }
-        if (!closed && !isInterrupted()){
-          // 要发电计划报文
-          String planMessage = "6891000000B4010015000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
-          log.info("发送报文{}",planMessage);
-          ctx.writeAndFlush(planMessage);
-        }
-      }
-    }
-    public void closed(){
-      this.closed = true;
-      this.interrupt();
-    }
-  }
-}

+ 0 - 129
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangClient.java

@@ -1,129 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.zhejiang;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.fileupload.IEC102.NettyParent;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongClient;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongClientHandler;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongDecoder;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongEncoder;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.timeout.IdleStateHandler;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * 开启浙江丽水地调客户端
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiangClient extends NettyParent {
-  private String host;
-  private int port;
-  private Logger log;
-  private UploadFileChannel uploadFileChannel;
-
-  private Bootstrap bootstrap = new Bootstrap();
-  EventLoopGroup workerGroup = new NioEventLoopGroup();
-  private Channel channel;
-  private ChannelFuture channelFuture;
-
-  /**
-   * 获取 host
-   *
-   * @return host
-   */
-  public String getHost() {
-    return host;
-  }
-
-  /**
-   * 获取 port
-   *
-   * @return port
-   */
-  public int getPort() {
-    return port;
-  }
-
-  public ZheJiangClient(String host, int port, Logger log, UploadFileChannel uploadFileChannel) {
-    this.host = host;
-    this.port = port;
-    this.log = log;
-    this.uploadFileChannel = uploadFileChannel;
-    init();
-  }
-
-  /**
-   * 初始化客户端
-   */
-  private void init() {
-    final ZheJiangClient client = this;
-    bootstrap.group(workerGroup);
-    bootstrap.channel(NioSocketChannel.class);
-    bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
-    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
-      @Override
-      protected void initChannel(SocketChannel ch) {
-        ch.pipeline().addLast("decoder", new ZheJiangDecoder(log));
-        ch.pipeline().addLast("encoder", new ZheJiangEncoder(log));
-        ch.pipeline().addLast(new ZheJiangClientHandler(client, log));
-      }
-    });
-    log.info("客户端初始化完成");
-  }
-
-  /**
-   * 与服务端建立连接
-   * (注册重连机制)
-   */
-  public void start() {
-    try {
-//      if (channel != null && channel.isActive()) {
-//        log.info("channel实例重复调用start启动");
-//        return;
-//      }
-      channelFuture = bootstrap.connect(host, port);
-      this.channel = channelFuture.channel();
-
-      channelFuture.addListener(new ChannelFutureListener() {
-        //使用匿名内部类,ChannelFutureListener接口
-        //重写operationComplete方法
-        @Override
-        public void operationComplete(ChannelFuture future) throws Exception {
-          //判断是否操作成功
-          if (future.isSuccess()) {
-            // 通道变绿
-
-            log.info("客户端连接成功");
-          } else {
-            // 通道变红
-
-            FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "").destroy();
-            FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId()+"");
-            log.info("客户端连接失败");
-          }
-        }
-      });
-    } catch (Exception e) {
-      log.error("启动连接失败", e);
-    }
-  }
-
-  /**
-   * 停止服务
-   */
-  public void destroy() {
-    if (channelFuture != null) {
-      channelFuture.channel().close();
-    }
-    workerGroup.shutdownGracefully();
-    log.info("客户端通道连接销毁成功!");
-  }
-}

+ 0 - 157
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangClientHandler.java

@@ -1,157 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.zhejiang;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.util.RuntimeUtil;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.ElectricField;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.console.service.ChannelDisconLogService;
-import com.jiayue.ipfcst.console.service.ElectricFieldService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 浙江丽水地调客户端Handler
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiangClientHandler extends ChannelInboundHandlerAdapter {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-  @Autowired
-  ElectricFieldService electricFieldService = SpringContextHolder.getApplicationContext().getBean(ElectricFieldService.class);
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  ZheJiangHandlerService zheJiangHandlerService = SpringContextHolder.getApplicationContext().getBean(ZheJiangHandlerService.class);
-  @Autowired
-  ChannelDisconLogService channelDisconLogService = SpringContextHolder.getApplicationContext().getBean(ChannelDisconLogService.class);
-
-  private UploadFileChannel uploadFileChannel = null;
-
-  private UploadObject uploadObject = null;
-
-  private ZheJiangClient client;
-
-  private Logger log;
-
-  public ZheJiangClientHandler(ZheJiangClient client,Logger log) {
-    this.client = client;
-    this.log = log;
-  }
-
-  /**
-   * 接收服务端消息
-   *
-   * @param ctx channel上下文
-   * @param msg 消息
-   */
-  @Override
-  public void channelRead(ChannelHandlerContext ctx, Object msg) {
-    // 获取场站信息
-    ElectricField electricField = electricFieldService.get();
-    // 返回的报文
-    String returnMessage = zheJiangHandlerService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, electricField,log,ctx);
-    ctx.channel().writeAndFlush(returnMessage);
-  }
-
-  /**
-   * 首次建立连接
-   *
-   * @param ctx channel上下文
-   */
-  @Override
-  public void channelActive(ChannelHandlerContext ctx) {
-    InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
-    // 获取远程IP
-    String remoteIP = insocket.getAddress().getHostAddress();
-    String remotePort = String.valueOf(insocket.getPort());
-    List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-    // 获取上报对象及通道信息
-    List<UploadFileChannel> filterUploadFileChannelList = uploadFileChannelList.stream().filter(s -> s.getRemoteIp().equals(remoteIP) && s.getRemotePort().equals(remotePort)).collect(Collectors.toList());
-    uploadFileChannel = filterUploadFileChannelList.get(0);
-    List<UploadObject> uploadObjectList = uploadObjectService.get();
-    Map<Integer, UploadObject> uploadObjectMap = uploadObjectList.stream().collect(Collectors.toMap(UploadObject::getId, a -> a, (k1, k2) -> k1));
-    uploadObject = uploadObjectMap.get(uploadFileChannel.getUploadObjectId());
-    // 获取场站信息
-    ElectricField electricField = electricFieldService.get();
-    String returnMessage = zheJiangHandlerService.handlerMessage("connect", uploadObject, uploadFileChannel, electricField,log,ctx);
-    if (!"".equals(returnMessage)){
-      ctx.channel().writeAndFlush(returnMessage);
-    }
-  }
-
-  /**
-   * 异常处理
-   *
-   * @param ctx   channel上下文
-   * @param cause 异常
-   */
-  @Override
-  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-    log.error("客户端发生异常:", cause);
-    if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "")!=null){
-      FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "").destroy();
-    }
-    FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId()+"");
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
-      Map.Entry<String,FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        countMap.remove();
-      }
-    }
-
-    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-    while (contentMap.hasNext()){
-      Map.Entry<String,String> entry = contentMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        contentMap.remove();
-      }
-    }
-  }
-
-  /**
-   * 断线重连(10秒不间断重试)
-   */
-  @Override
-  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-    log.info("服务端断开:"+ctx.channel().remoteAddress());
-    String str = RuntimeUtil.execForStr("ping "+uploadFileChannel.getRemoteIp() +"-c 4");
-    log.info("ping远程IP结果:"+str);
-    if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "")!=null){
-      FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "").destroy();
-    }
-    FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId()+"");
-    Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
-      Map.Entry<String,FileMutableInteger> entry = countMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        countMap.remove();
-      }
-    }
-
-    Iterator<Map.Entry<String, String>> contentMap = FileConstant.fileContentMap.entrySet().iterator();
-    while (contentMap.hasNext()){
-      Map.Entry<String,String> entry = contentMap.next();
-      String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
-        contentMap.remove();
-      }
-    }
-  }
-}

+ 0 - 209
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangDecoder.java

@@ -1,209 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.zhejiang;
-
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.util.ReferenceCountUtil;
-import lombok.extern.slf4j.Slf4j;
-
-import org.springframework.beans.factory.annotation.Autowired;
-
-import javax.xml.bind.DatatypeConverter;
-
-/**
- * 102解码器
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiangDecoder extends SimpleChannelInboundHandler {
-  private Logger log;
-
-  ZheJiangDecoder(Logger log) {
-    this.log = log;
-  }
-
-  //记录上次未读完的字节
-  ByteBuf tempMessage = Unpooled.buffer();
-
-  @Autowired
-  AppenderFactory appenderFactory = SpringContextHolder.getApplicationContext().getBean(AppenderFactory.class);
-  @Autowired
-  UploadObjectService uploadObjectService = SpringContextHolder.getApplicationContext().getBean(UploadObjectService.class);
-  @Autowired
-  UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
-
-  @Override
-  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
-     ByteBuf msgCopy = (ByteBuf) msg;
-    int inSize = msgCopy.readableBytes();
-
-    if (inSize > 0) {
-      // tempMessage为缓存区,在此缓存解码报文
-      if (tempMessage.readableBytes() == 0) {
-        tempMessage = msgCopy.copy(0, inSize);
-      } else {
-        tempMessage.writeBytes(msgCopy);
-      }
-      if (log.isDebugEnabled()){
-        // 显示当前缓存里的内容
-        if (tempMessage.readableBytes() > 0) {
-          byte[] tempByte = new byte[tempMessage.readableBytes()];
-          tempMessage.readBytes(tempByte);
-        }
-      }
-
-      // 读下标重置
-      tempMessage.resetReaderIndex();
-      // 6个以上字节才报文解码
-      if (tempMessage.readableBytes() >= 6) {
-        // 此变量为了一串报文能继续往下解码
-        int i = 0;
-        while (true) {
-          String message = "";
-          // 检查10和68的下标位置
-          int s10 = tempMessage.indexOf(i, tempMessage.readableBytes(), (byte) 16);
-          int s68 = tempMessage.indexOf(i, tempMessage.readableBytes(), (byte) 104);
-          if (s10 == -1 && s68 == -1) {
-            // 10和68的都不存在,也就是都是-1,报文里没有关键字退出循环,等待接收下次内容
-            break;
-          } else if ((s10 > -1 && s68 > -1 && s10 < s68) || (s10 > -1 && s68 == -1)) {
-            // 调用10固定帧解码规则
-            message = handlerMessage10(s10, tempMessage);
-            if ("".equals(message)) {
-              i = s10 + 1;
-            }
-          } else if ((s10 > -1 && s68 > -1 && s68 < s10) || (s68 > -1 && s10 == -1)) {
-            // 调用68可变帧解码规则
-            message = handlerMessage68(s68, tempMessage);
-            if ("".equals(message)) {
-              i = s68 + 1;
-            }
-          }
-          if (!"".equals(message)) {
-            // 解码成功将下标重置0为了继续下一个解码循环
-            i = 0;
-            ctx.fireChannelRead(message);
-          }
-        }
-      }
-
-      // 缓存超过范围丢弃所有的内容
-      if (tempMessage.readableBytes() > 1024) {
-        byte[] clearByte = new byte[tempMessage.readableBytes()];
-        tempMessage.readBytes(clearByte);
-        String clearInfo = DatatypeConverter.printHexBinary(clearByte);
-//        uploadLogger.info("无效报文超过范围数量舍弃:"+ clearInfo);
-        ReferenceCountUtil.release(tempMessage);
-        tempMessage = Unpooled.buffer();
-      }
-//      if (uploadLogger.isDebugEnabled()){
-//        // 显示解码后剩余的报文
-//        if (tempMessage.readableBytes() > 0) {
-//          byte[] leftOverByte = new byte[tempMessage.readableBytes()];
-//          tempMessage.readBytes(leftOverByte);
-//          String leftOverInfo = DatatypeConverter.printHexBinary(leftOverByte);
-//          uploadLogger.debug("剩余的报文:"+ leftOverInfo);
-//        }
-//      }
-
-      tempMessage.resetReaderIndex();
-    }
-  }
-
-  /**
-   * 10固定帧报文处理
-   *
-   * @param s10       10所在缓存字节下标位置
-   * @param inMessage 缓存内容
-   * @return 符合固定帧规则的十六进制报文字符串
-   */
-  private String handlerMessage10(int s10, ByteBuf inMessage) {
-    int inMessageLength = inMessage.readableBytes();
-    String message = "";
-    // 调用10固定帧规则
-    if (s10 + 5 <= inMessageLength) {
-      byte e16 = inMessage.getByte(s10 + 5);
-      if (e16 == (byte) 22) {
-        // 找到了10开头并且16结尾的固定报文
-        ByteBuf gd10 = inMessage.copy(s10, 6);
-        byte[] kdst = new byte[gd10.readableBytes()];
-        gd10.readBytes(kdst);
-        message = DatatypeConverter.printHexBinary(kdst);
-        handlerLoseMessage(s10, inMessage);
-        inMessage.readerIndex(s10 + 6);
-        // 删除报文到解码成功最后一位
-        inMessage.discardReadBytes();
-        ReferenceCountUtil.release(gd10);
-      }
-    }
-    return message;
-  }
-
-  /**
-   * 68可变帧报文处理
-   *
-   * @param s68       68所在缓存字节下标位置
-   * @param inMessage 缓存内容
-   * @return 符合固定帧规则的十六进制报文字符串
-   */
-  private String handlerMessage68(int s68, ByteBuf inMessage) {
-    int inMessageLength = inMessage.readableBytes();
-    String message = "";
-    // 判断第二个68
-    int second68 = inMessage.indexOf(s68 + 3, inMessageLength, (byte) 104);
-    if (second68 == s68 + 3) {
-      // 获取2个68之间的报文长度低高位
-      ByteBuf b = inMessage.copy(s68 + 1, 2);
-      byte[] dst = new byte[b.readableBytes()];
-      b.readBytes(dst);
-      // 将低高位反转
-      String messageLength = DatatypeConverter.printHexBinary(ByteUtil.bytesFlipping(dst));
-      // 算出第二个68后面数据段长度
-      int tempLength = ByteUtil.hexToDec(messageLength);
-      int end16 = second68 + tempLength + 2;
-      if (inMessageLength - 1 >= end16) {
-        // 满足长度,再判断是否以16结尾
-        if (inMessage.indexOf(end16, end16 + 1, (byte) 22) > -1) {
-          // 合法可变报文,将可变报文转成16进制给业务
-          ByteBuf kb = inMessage.copy(s68, 4 + tempLength + 2);
-          byte[] kdst = new byte[kb.readableBytes()];
-          kb.readBytes(kdst);
-          message = DatatypeConverter.printHexBinary(kdst);
-          handlerLoseMessage(s68, inMessage);
-          inMessage.readerIndex(end16 + 1);
-          inMessage.discardReadBytes();
-          ReferenceCountUtil.release(kb);
-        }
-      }
-      ReferenceCountUtil.release(b);
-    }
-    return message;
-  }
-
-  /**
-   * 显示头之前没用的报文
-   *
-   * @param useHeadIndex
-   * @param inMessage
-   */
-  private void handlerLoseMessage(int useHeadIndex, ByteBuf inMessage) {
-    if (useHeadIndex > 0) {
-      // 舍弃的报文
-      ByteBuf loseMessage = inMessage.copy(0, useHeadIndex);
-      byte[] loseByte = new byte[loseMessage.readableBytes()];
-      loseMessage.readBytes(loseByte);
-      String loseInfo = DatatypeConverter.printHexBinary(loseByte);
-//      uploadLogger.debug("舍弃的报文:"+ loseInfo);
-      ReferenceCountUtil.release(loseMessage);
-    }
-  }
-}

+ 0 - 27
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangEncoder.java

@@ -1,27 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.zhejiang;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.MessageToByteEncoder;
-import org.slf4j.Logger;
-
-import java.math.BigInteger;
-
-/**
- * 浙江丽水地调102编码
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiangEncoder extends MessageToByteEncoder<String> {
-  private Logger log;
-
-  ZheJiangEncoder(Logger log) {
-    this.log = log;
-  }
-    @Override
-    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
-      BigInteger bigint=new BigInteger(msg, 16);
-      out.writeBytes(bigint.toByteArray());
-    }
-}

+ 0 - 241
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/zhejiang/ZheJiangHandlerService.java

@@ -1,241 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.zhejiang;
-
-import cn.hutool.core.map.MapUtil;
-import cn.hutool.core.util.ArrayUtil;
-import cn.hutool.core.util.StrUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.ElectricField;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.fileupload.IEC102.Base102Service;
-import com.jiayue.ipfcst.fileupload.dto.Validate102Dto;
-import com.jiayue.ipfcst.fileupload.util.*;
-import io.netty.channel.ChannelHandlerContext;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.slf4j.Logger;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-import java.io.*;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 浙江丽水地调业务处理类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class ZheJiangHandlerService extends Base102Service {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-
-  @Transactional(propagation = Propagation.REQUIRED)
-  public String handlerMessage(String receiveMessage, UploadObject uploadObject, UploadFileChannel uploadFileChannel, ElectricField electricField,Logger log, ChannelHandlerContext ctx) {
-    String sendMessage = "";
-    String sendCtrlChinese = "";
-
-    if ("connect".equals(receiveMessage)){
-      // 连接成功后,发送给主站复位报文
-      sendMessage = "1040FFFF3E16";
-      sendCtrlChinese = "复位请求";
-    }
-    else{
-      String[] rmArray = IEC102Uitl.stingToArray(receiveMessage);
-      // 地调回复100BFFFF0916,同意接收文件|| 680B继续文件传输
-      if ("100BFFFF0916".equals(receiveMessage) || ("680B".equals(rmArray[3]+rmArray[4])) && "96".equals(rmArray[9])){
-        if ("100BFFFF0916".equals(receiveMessage)){
-          log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + "应答复位" + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-        }
-        else{
-          log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + "等待后续上传" + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-        }
-        // 先判断文件上报次数累计的缓存变量是否存在
-        Map<String, FileMutableInteger> filterMap = FileConstant.uploadCountMap.entrySet().stream().filter(r -> uploadObject.getId()== Integer.parseInt(r.getKey().substring(0, r.getKey().indexOf("@"))))
-          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-        // 上报文件名
-        String fileNameKey = "";
-        if (MapUtil.isNotEmpty(filterMap)) {
-          // 不是第一次要文件了
-          for (Map.Entry<String, FileMutableInteger> entry : filterMap.entrySet()) {
-            fileNameKey = entry.getKey();
-            log.info(ctx.channel().remoteAddress()+" - "+"上传文件===>"+entry.getKey());
-            break;
-          }
-        } else {
-          // 从待上报的缓存中取一个文件放入次数变量中
-          Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap,log);
-          for (Map.Entry<String, UploadFileLog> entry : readyUploadFileMap.entrySet()) {
-            // 从待上报缓存中取一个加入到累计次数变量中
-            FileMutableInteger fileMutableInteger = new FileMutableInteger(0);
-            FileConstant.uploadCountMap.put(entry.getKey(), fileMutableInteger);
-            log.info(ctx.channel().remoteAddress()+" - "+"找到文件===>"+entry.getKey());
-            fileNameKey = entry.getKey();
-            break;
-          }
-        }
-        // 生成传输文件的68帧
-        sendMessage = uploadFile68(fileNameKey, electricField,uploadObject, uploadFileChannel, log);
-        sendCtrlChinese = "通道:"+uploadFileChannel.getChannelName()+"上报:"+fileNameKey;
-      }
-      else{
-        if ("6853".equals(rmArray[3]+rmArray[4]) && "96".equals(rmArray[9])){
-          // 地调接收结束
-          log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + "接收结束" + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-          String handMessage = receiveMessage.replace(" ","");
-          // 文件名去掉尾部占位的0
-          String fileNameHex = handMessage.substring(34,handMessage.length()-4).replaceAll("0*$", "");
-          int fileNameHexLength = fileNameHex.length();
-          byte[] fnData = new byte[fileNameHexLength / 2];
-          for (
-            int k = 0;
-            k < fileNameHexLength; k += 2) {
-            fnData[k / 2] = (byte) ((Character.digit(fileNameHex.charAt(k), 16) << 4)
-              + Character.digit(fileNameHex.charAt(k + 1), 16));
-          }
-          try {
-            String filename = new String(fnData, uploadObject.getUploadFileCharSetEnum().getMessage());
-            log.info(ctx.channel().remoteAddress()+" - "+"地调成功接收文件:"+filename);
-          } catch (UnsupportedEncodingException e) {
-            log.error("转换文件名出错",e);
-          }
-          super.totalFileUploadNums(uploadObject,uploadFileChannel, "", log);
-        }
-        else if ("97".equals(rmArray[9])){
-          // 重复上报
-          log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + "重复上报" + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-          super.totalFileUploadNums(uploadObject,uploadFileChannel, "重复上报", log);
-        }
-        else if ("98".equals(rmArray[9])){
-          // 文件长度超出
-          log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + "文件长度超出" + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-          super.totalFileUploadNums(uploadObject,uploadFileChannel, "文件长度超出", log);
-        }
-        else if ("99".equals(rmArray[9])){
-          // 文件名格式错误
-          log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + "文件名格式错误" + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-          super.totalFileUploadNums(uploadObject,uploadFileChannel, "文件名格式错误", log);
-        }
-
-        // 是否还有新的文件上传
-        Map<String, UploadFileLog> filterMap = FileConstant.readyUploadFileMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))))
-          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-            (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-
-        if (MapUtil.isNotEmpty(filterMap)) {
-          // 有新文件继续请求复位
-          sendMessage = "1040FFFF3E16";
-          sendCtrlChinese = "复位请求";
-        }
-        else{
-          // 没有文件,主动断开通道连接
-          log.info(ctx.channel().remoteAddress()+" - "+"没有上报文件,客户端主动断开连接");
-          ctx.close();
-        }
-      }
-    }
-    if (!"".equals(sendMessage)){
-      log.info(ctx.channel().remoteAddress()+" - "+"发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage.toUpperCase()));
-    }
-    return sendMessage.toUpperCase();
-  }
-
-  /**
-   * 传输文件的68帧报文
-   * 格式说明:68|帧长低字节|帧长高字节|68|控制域|场站ID|文件类型|01|是否最后一包|场站ID|00|包号|文件名字节|文件内容字节|校验和|16
-   * 帧长:控制域位置--校验和之前个数,结果高低位交互显示
-   * 控制域:08写死(代表发送数据)
-   * 是否最后一包:07 最后 08 不是
-   * 包号:用2个字节显示
-   * crc校验和:从[控制域]到[校验和]之前
-   * 帧长:从[控制域]到[校验和]之前所有字节数
-   *
-   * @return 68帧报文
-   */
-  private String uploadFile68(String fileNameKey, ElectricField electricField,UploadObject uploadObject, UploadFileChannel uploadFileChannel, Logger log) {
-    String[] returnMessage = {"68", "mlLow", "mlHeight", "68", "08", "eid", "typeCode", "01", "pLast", "eid", "00", "pNo","fileNameByte", "fileContentByte", "crc", "16"};
-    String[] tempKey = new String[3];
-    String tempFileName = fileNameKey;
-    tempKey[0] = tempFileName.substring(0,tempFileName.indexOf("@",0));
-    tempFileName = tempFileName.substring(tempFileName.indexOf("@",0)+1);
-    tempKey[1] = tempFileName.substring(0,tempFileName.indexOf("@",0));
-    tempKey[2] = tempFileName.substring(tempFileName.indexOf("@",0)+1);
-
-    // 生成文件名及内容
-    String fileName = tempKey[2];
-    byte[] tempFileNameBytes = null;
-    String charsetName = uploadObject.getUploadFileCharSetEnum().getMessage();
-    try {
-      tempFileNameBytes = fileName.getBytes(charsetName);
-    } catch (Exception e) {
-      log.error("转换文件名编码失败", e);
-    }
-    // 获取文件名称长度
-    String fileNameLength = uploadFileChannel.getUploadFileNameLengthEnum().getMessage();
-    String fileNameByte = ByteUtil.Byte2String(tempFileNameBytes);
-    fileNameByte = StrUtil.padAfter(fileNameByte.replace(" ", ""), Integer.parseInt(fileNameLength) * 2, '0');
-
-    String fileContentByte = FileConstant.fileContentMap.get(fileNameKey);
-    if (StrUtil.hasBlank(fileContentByte)) {
-      // 缓存中没有文件内容则新生成文件内容报文
-      String filePath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + tempKey[0] + File.separator + tempKey[1] + File.separator + tempKey[2];
-      fileContentByte = super.createFileMessageHex(filePath, charsetName, log);
-    }
-    // 生成不是最后一帧控制域码
-    String pLast = "08";
-    // 获取通道单次文件传输字节
-    String singleByte = uploadFileChannel.getUploadFileSingleByteEnum().getMessage();
-    if (fileContentByte.length() <= Integer.parseInt(singleByte) * 2) {
-      // 一次可以传输完,生成控制域码
-      pLast = "07";
-    } else {
-      // 将剩余的文件内容报文存入缓存中
-      FileConstant.fileContentMap.put(fileNameKey, fileContentByte.substring(Integer.parseInt(singleByte) * 2));
-      fileContentByte = fileContentByte.substring(0, Integer.parseInt(singleByte) * 2);
-    }
-    returnMessage[12] = fileNameByte;
-    returnMessage[13] = fileContentByte;
-    // 生成类型标识
-    Map<String,Integer> codeMap = super.getFileCode();
-    String typeCode = Integer.toHexString(codeMap.get(tempKey[1]));
-    // 场站ID
-    String eId = ByteUtil.decToHex(Integer.parseInt(electricField.getNetSubstationName()));
-    returnMessage[5] = eId;
-    returnMessage[6] = typeCode;
-    returnMessage[8] = pLast;
-    returnMessage[9] = eId;
-    // 包号
-    String packageNum = FileConstant.filePackageNumMap.get(fileNameKey);
-    int pNo = 0;
-    if (!StrUtil.hasBlank(packageNum)) {
-      pNo = Integer.parseInt(packageNum)+1;
-    }
-    FileConstant.filePackageNumMap.put(fileNameKey,pNo+"");
-
-    returnMessage[11] = ByteUtil.decToHex(Integer.parseInt(pNo+""));
-
-    StringBuffer tempSB = new StringBuffer("");
-    for (int i = 4; i <= 13; i++) {
-      tempSB.append(returnMessage[i]);
-    }
-    // 计算报文的帧长
-    String ml = StrUtil.padAfter(ByteUtil.decToHex(tempSB.length() / 2), 4, '0');
-    String mlLow = ml.substring(0, 2);
-    String mlHeight = ml.substring(2);
-    returnMessage[1] = mlLow;
-    returnMessage[2] = mlHeight;
-    // 计算校验和
-    String crc = IEC102Uitl.makeChecksum(tempSB.toString());
-    returnMessage[14] = crc;
-
-    String sendMessage = ArrayUtil.join(returnMessage, "");
-    return sendMessage.toUpperCase();
-  }
-}

+ 0 - 121
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/config/AppenderFactory.java

@@ -1,121 +0,0 @@
-package com.jiayue.ipfcst.fileupload.config;
-
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.classic.LoggerContext;
-import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
-import ch.qos.logback.classic.filter.ThresholdFilter;
-import ch.qos.logback.core.rolling.RollingFileAppender;
-import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
-import ch.qos.logback.core.util.FileSize;
-import ch.qos.logback.core.util.OptionHelper;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * 创建动态日志
- *
- * @author xsl
- * @version 3.0
- */
-@Component
-public class AppenderFactory {
-  @Value("${fileupload.log.level}")
-  private String logLevel;
-  @Value("${fileupload.log.totalSizeCap}")
-  private String totalSizeCap;
-  @Value("${fileupload.log.maxFileSize}")
-  private String maxFileSize;
-  @Value("${fileupload.log.maxHistory}")
-  private String maxHistory;
-
-  public Logger getLogger(String name, String type, String no) {
-    Logger logger = FileConstant.uploadLogMap.get(no);
-    if (logger != null) {
-      return logger;
-    } else {
-      if (logger != null) {
-        return logger;
-      }
-      logger = getAppender(name, type, no);
-      FileConstant.uploadLogMap.put(no, logger);
-    }
-    return logger;
-  }
-
-  /**
-   * 通过传入的名字和级别,动态设置appender
-   *
-   * @param name
-   * @return
-   */
-  public Logger getAppender(String name, String type, String no) {
-//    Level level = Level.toLevel(this.logLevel);
-//    DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE);
-    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
-    //这里是可以用来设置appender的,在xml配置文件里面,是这种形式:
-    // <appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
-    RollingFileAppender appender = new RollingFileAppender();
-    //这里设置级别过滤器
-    ThresholdFilter levelFilter = createLevelFilter(this.logLevel);
-    levelFilter.start();
-    appender.addFilter(levelFilter);
-    // 但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。
-    appender.setContext(context);
-    //appender的name属性
-    appender.setName("upload-" + type + "-" + name + "-" + no);
-    //设置文件名
-//        appender.setFile(OptionHelper.substVars("d:/eppLog/"+ name+"/" + "fileUploadLogFile-" +name+"-"+ type+".%d{yyyy-MM-dd}.%i.log",context));
-    appender.setAppend(true);
-    appender.setPrudent(false);
-    //设置文件创建时间及大小的类
-    SizeAndTimeBasedRollingPolicy policy = new SizeAndTimeBasedRollingPolicy();
-    //文件名格式
-    String fp = OptionHelper.substVars(FileUtil.getLogsPath() + "/" + "%d{yyyy-MM-dd}" + "/" + "upload-" + type + "-" + name + "-" + no + ".%d{yyyy-MM-dd}.%i.log", context);
-    //最大日志文件大小
-    policy.setMaxFileSize(FileSize.valueOf(this.maxFileSize));
-    //设置文件名模式
-    policy.setFileNamePattern(fp);
-    //设置日志文件保留天数
-    policy.setMaxHistory(Integer.parseInt(this.maxHistory));
-    //总大小限制
-    policy.setTotalSizeCap(FileSize.valueOf(this.totalSizeCap));
-    //设置父节点是appender
-    policy.setParent(appender);
-    // 但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。
-    policy.setContext(context);
-    policy.setCleanHistoryOnStart(true);
-    policy.start();
-    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
-    //设置上下文,每个logger都关联到logger上下文,默认上下文名称为default。
-    // 但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。
-    encoder.setContext(context);
-    //设置格式
-//    encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n");
-    encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level - %msg%n");
-    encoder.start();
-    //加入下面两个节点
-    appender.setRollingPolicy(policy);
-    appender.setEncoder(encoder);
-    appender.start();
-    Logger logger = context.getLogger("upload-" + type + "-" + name + "-" + no);
-    //设置不向上级打印信息
-    logger.setAdditive(false);
-    logger.addAppender(appender);
-    return logger;
-  }
-
-  private ThresholdFilter createLevelFilter(String level) {
-    ThresholdFilter levelFilter = new ThresholdFilter();
-    levelFilter.setLevel(level);
-//    levelFilter.setOnMatch(ACCEPT);
-//    levelFilter.setOnMismatch(DENY);
-    levelFilter.start();
-    return levelFilter;
-  }
-}

+ 0 - 118
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/config/FileUploadConfig.java

@@ -1,118 +0,0 @@
-package com.jiayue.ipfcst.fileupload.config;
-
-import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.console.service.SysParameterService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.core.annotation.Order;
-import org.springframework.data.jpa.domain.Specification;
-import org.springframework.stereotype.Component;
-
-import javax.persistence.criteria.Predicate;
-import java.util.*;
-
-/**
- * 启动netty服务端
- *
- * @author xsl
- * @version 3.0
- */
-@Component
-@Order(100)
-@Slf4j
-public class FileUploadConfig {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService;
-  @Autowired
-  SysParameterService sysParameterService;
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  /**
-   * 开启102s服务端
-   */
-  @Bean
-  public void startIec102Server() {
-    uploadFileChannelService.startAllChannel();
-  }
-
-  /**
-   * 启动将fileupload/process目录里的文件加载到文件缓存变量中
-   */
-  @Bean
-  public void loadUploadFileConstant() {
-    // 查询文件日志数据库,将未上报成功的查询出来
-    Specification<UploadFileLog> specification = this.getQuerySpecification();
-    List<UploadFileLog> uploadFileLogList = uploadFileLogRepository.findAll(specification);
-    for (UploadFileLog uploadFileLog:uploadFileLogList){
-      String readyFileKey = uploadFileLog.getUploadObjectNo()+"@"+uploadFileLog.getFileTypeEnum().toString()+"@"+uploadFileLog.getFileName();
-      FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
-      FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
-    }
-//    try {
-//      Files.walkFileTree(Paths.get(FileUtil.getFileUploadPath() + File.separator + "process"), new SimpleFileVisitor<Path>() {
-//        // 访问文件时自动调用此方法,attrs参数可以获取到文件大小
-//        @Override
-//        public FileVisitResult visitFile(Path vfile, BasicFileAttributes attrs) {
-//          try {
-//            File file = vfile.toFile();
-//            int processIdx = file.getPath().indexOf("process");
-//            if (processIdx > -1) {
-//              String separator = "/|\\\\";
-//              String[] dirs = file.getPath().substring(processIdx).split(separator);
-//              String readyFileKey = dirs[dirs.length - 3].toString() + "-" + dirs[dirs.length - 2].toString() + "-" + dirs[dirs.length - 1].toString();
-//              FileConstant.readyUploadFileMap.put(readyFileKey, file.getPath());
-//              log.info("上报文件:" + file.getPath() + "存入缓存,缓存中数量:" + FileConstant.readyUploadFileMap.size());
-//            }
-//          } catch (Exception e) {
-//            log.error("启动加载上报文件失败:" + vfile.toFile().getPath());
-//          }
-//          return FileVisitResult.CONTINUE;
-//        }
-//
-//        // 访问文件夹之前自动调用此方法
-//        @Override
-//        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
-//          return FileVisitResult.CONTINUE;
-//        }
-//
-//        //访问文件失败时自动调用此方法
-//        @Override
-//        public FileVisitResult visitFileFailed(Path file, IOException e) {
-//          return FileVisitResult.CONTINUE;
-//        }
-//
-//        //访问文件夹之后自动调用此方法
-//        @Override
-//        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
-//          return FileVisitResult.CONTINUE;
-//        }
-//      });
-//    } catch (Exception e) {
-//      log.error("启动加载上报文件到缓存中失败:", e);
-//    }
-  }
-
-  /**
-   * 封装文件日志查询条件
-   * @return
-   */
-  private Specification<UploadFileLog> getQuerySpecification() {
-    return (Specification<UploadFileLog>) (root, criteriaQuery, cb) -> {
-      Long startTime = DateMomentUtil.getDayStartTime(new Date().getTime());
-      // 结束时间(开始加24小时再减去1秒)
-      Long endTime = startTime + 1000 *60 * 60 *24 -1;
-
-      List<Predicate> predicates = new ArrayList<>();
-      predicates.add(cb.equal(root.get("fileStatusEnum").as(String.class), "E1"));
-      predicates.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class), DateFormatUtils.format(startTime, "yyyy-MM-dd HH:mm:ss'")));
-      predicates.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class), DateFormatUtils.format(endTime, "yyyy-MM-dd HH:mm:ss'")));
-      return cb.and(predicates.toArray(new Predicate[predicates.size()]));
-    };
-  }
-}

+ 1 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/controller/UploadFileLogController.java

@@ -102,7 +102,7 @@ public class UploadFileLogController {
 
   @PostMapping("/cleanCache")
   public ResponseVO cleanCache(@RequestBody UploadFileLog uploadFileLog){
-    uploadFileLogService.cleanCache(uploadFileLog);
+//    uploadFileLogService.cleanCache(uploadFileLog);
     return ResponseVO.success(1);
   }
 

+ 1 - 4
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/controller/UploadFileOpenInterfaceController.java

@@ -2,8 +2,8 @@ package com.jiayue.ipfcst.fileupload.controller;
 
 import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
 import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
+import com.jiayue.ipfcst.console.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.service.UploadFileLogService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -38,9 +38,6 @@ public class UploadFileOpenInterfaceController {
   public ResponseVO getFileCache() {
     log.info("访问上报缓存。。。。。。。");
     List list = new ArrayList<>();
-    for(Map.Entry<String, UploadFileLog> vo : FileConstant.readyUploadFileMap.entrySet()){
-      list.add(vo.getValue());
-    }
     return ResponseVO.success(list);
   }
 

+ 0 - 17
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/dto/UploadFileTypeDto.java

@@ -1,17 +0,0 @@
-package com.jiayue.ipfcst.fileupload.dto;
-
-import lombok.Data;
-
-/**
- * 文件类型DTO
- *
- * @author xsl
- * @version 3.0
- */
-@Data
-public class UploadFileTypeDto {
-  // 文件类型
-  private String fileType;
-  // 类型名称
-  private String typeName;
-}

+ 0 - 17
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/dto/Validate102Dto.java

@@ -1,17 +0,0 @@
-package com.jiayue.ipfcst.fileupload.dto;
-
-import lombok.Data;
-
-/**
- * 校验102Dto
- *
- * @author xsl
- * @version 3.0
- */
-@Data
-public class Validate102Dto {
-  // 接收到报文帧第一个字节
-  public String messageFirst;
-  // 报文对应的判断码,10帧存第二个字节,68帧存传输原因
-  public String messageReason;
-}

+ 0 - 30
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/FtpClientUploadJob.java

@@ -1,30 +0,0 @@
-package com.jiayue.ipfcst.fileupload.job;
-
-import com.jiayue.ipfcst.fileupload.service.FtpUploadService;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-
-/**
- * ftp客户端上报定时
- *
- * @author xsl
- * @version 3.0
- * @since 2020/4/24 14:54
- */
-@Slf4j
-@Service
-@EnableScheduling
-public class FtpClientUploadJob{
-  @Autowired
-  FtpUploadService ftpUploadService;
-
-  @Scheduled(fixedDelay = 60000)
-  public void execute() {
-    log.info("FTP/SFTP上报定时任务执行开始");
-    ftpUploadService.startFtpUpload();
-    log.info("FTP/SFTP上报定时任务执行结束");
-  }
-}

+ 0 - 106
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/ListenUploadJob.java

@@ -1,106 +0,0 @@
-package com.jiayue.ipfcst.fileupload.job;
-
-import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.common.data.service.BaseService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadFileLogService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.mock.web.MockMultipartFile;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-import org.springframework.web.multipart.MultipartFile;
-
-import java.io.*;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-/**
- * 监听上报通道
- *
- * @author xsl
- * @version 3.0
- * @since 2020/12/3 9:51
- */
-@Slf4j
-@Service
-@EnableScheduling
-public class ListenUploadJob {
-  @Autowired
-  UploadObjectService uploadObjectService;
-  @Autowired
-  UploadFileChannelService uploadFileChannelService;
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  @Autowired
-  BaseService baseService;
-
-  @Scheduled(initialDelay = 300000,fixedDelay = 60000)
-  public void execute() {
-    // 获取参数是否执行监听上报长时间不交互重启console
-    String jtsb = baseService.getSysParameter("jtsb","0");
-    if ("1".equals(jtsb)){
-      List<UploadObject> uploadObjectList = uploadObjectService.get();
-      // 过滤出102的
-      List<UploadObject> uploadObjects = uploadObjectList.stream().filter(s -> !"ftp".equals(s.getUploadProtocolEnum().getCode()) && !"sftp".equals(s.getUploadProtocolEnum().getCode())).collect(Collectors.toList());
-      // 拼装上报通道状态
-      Map<String, String> objectStatusMap = new HashMap<String, String>();
-      for (Map.Entry<String, String> entry : FileConstant.channelStatusMap.entrySet()) {
-        String[] statusKeys = entry.getKey().toString().split("-");
-        if ("1".equals(entry.getValue().toString())) {
-          // 将正常的通道获取
-          objectStatusMap.put(statusKeys[0], "1");
-        }
-      }
-
-      for (UploadObject o : uploadObjects) {
-        if (objectStatusMap.get(o.getId())==null || "0".equals(objectStatusMap.get(o.getId()+""))){
-          if (FileConstant.channelTimeMap.get(o.getId()+"")!=null){
-            if (System.currentTimeMillis() - FileConstant.channelTimeMap.get(o.getId()+"")>600000){
-              SimpleDateFormat formatter = new SimpleDateFormat("mm");
-              int a =  Integer.parseInt(formatter.format(new Date(System.currentTimeMillis())));
-              if (a % 5 == 0) {
-                FileConstant.channelTimeMap.put(o.getId()+"",System.currentTimeMillis());
-              }
-              else{
-                log.info("监听上报对象:"+o.getUploadObjectName()+",在10分钟内没有通讯,重启console");
-                try {
-                  Process process = Runtime.getRuntime().exec("service console restart");
-                  process.getInputStream().close();
-                  process.getOutputStream().close();
-                  process.destroy();
-                } catch (IOException e) {
-                  log.error("重启console执行失败",e);
-                }
-              }
-            }
-          }
-          else{
-            FileConstant.channelTimeMap.put(o.getId()+"",System.currentTimeMillis());
-          }
-        }
-        else{
-          FileConstant.channelTimeMap.remove(o.getId()+"");
-        }
-      }
-    }
-  }
-}

+ 0 - 85
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/MengXiClientJob.java

@@ -1,85 +0,0 @@
-package com.jiayue.ipfcst.fileupload.job;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.date.DateUtil;
-import cn.hutool.core.map.MapUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.job.BaseJob;
-import com.jiayue.ipfcst.fileupload.IEC102.mengxi.MengXiClient;
-import com.jiayue.ipfcst.fileupload.IEC102.zhejiang.ZheJiangClient;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import org.quartz.JobDataMap;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Service;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 蒙西102定时任务
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-@EnableScheduling
-public class MengXiClientJob{
-  @Autowired
-  AppenderFactory appenderFactory;
-  @Autowired
-  UploadFileChannelService uploadFileChannelService;
-  @Autowired
-  UploadObjectService uploadObjectService;
-
-
-  @Scheduled(fixedDelay = 10000)
-  public void execute() {
-    if (FileConstant.uploadSuccessTime!=null){
-      Calendar calendar = Calendar.getInstance();
-      calendar.setTime(FileConstant.uploadSuccessTime);
-      calendar.add(Calendar.MINUTE,1);
-      if (new Date().after(calendar.getTime())){
-        executeUpload();
-      }
-    }
-    else{
-      executeUpload();
-    }
-  }
-
-  public void executeUpload(){
-    // 获取浙江地调102的所有通道
-    List<UploadFileChannel> uploadFileChannels = uploadFileChannelService.get();
-    // 取通道状态正常并且是102s的类型
-    List<UploadFileChannel> useChannelList = uploadFileChannels.stream().filter(s -> s.getChannelStatusEnum().equals(ChannelStatusEnum.E1)).collect(Collectors.toList());
-    for (UploadFileChannel u : useChannelList) {
-      // 获取上报对象协议类型
-      List<UploadObject> uploadObjectList = uploadObjectService.get();
-      UploadObject uploadObject = uploadObjectList.stream().filter(s -> s.getId().equals(u.getUploadObjectId())).collect(Collectors.toList()).get(0);
-      if ("102mx".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-        Logger logger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-        if (FileConstant.nettyInstanceMap.get(u.getId() + "")!=null){
-          logger.info("通道:"+u.getChannelName()+",定时上报实例正在进行,此次定时不进行");
-        }
-        else{
-          // 是否有文件
-          if (FileConstant.readyUploadFileMap.size()>0){
-            logger.info("通道:"+u.getChannelName()+"有文件,准备交互报文.....");
-            MengXiClient instance = new MengXiClient(u.getRemoteIp(), Integer.parseInt(u.getRemotePort()), logger,uploadObject,u);
-            FileConstant.nettyInstanceMap.put(u.getId() + "", instance);
-            instance.start();
-            logger.info("通道:"+u.getChannelName()+",任务执行结束");
-          }
-        }
-      }
-    }
-  }
-}

+ 0 - 76
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/job/ZheJiang102ClientJob.java

@@ -1,76 +0,0 @@
-package com.jiayue.ipfcst.fileupload.job;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.map.MapUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.job.BaseJob;
-import com.jiayue.ipfcst.fileupload.IEC102.zhejiang.ZheJiangClient;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import org.quartz.JobDataMap;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-/**
- * 浙江丽水地调102定时任务
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class ZheJiang102ClientJob extends BaseJob {
-  @Autowired
-  AppenderFactory appenderFactory;
-  @Autowired
-  UploadFileChannelService uploadFileChannelService;
-  @Autowired
-  UploadObjectService uploadObjectService;
-
-
-  @Override
-  public boolean execute(JobDataMap jobDataMap) {
-    // 获取浙江地调102的所有通道
-    List<UploadFileChannel> uploadFileChannels = uploadFileChannelService.get();
-    // 取通道状态正常并且是102s的类型
-    List<UploadFileChannel> useChannelList = uploadFileChannels.stream().filter(s -> s.getChannelStatusEnum().equals(ChannelStatusEnum.E1)).collect(Collectors.toList());
-    for (UploadFileChannel u : useChannelList) {
-      // 获取上报对象协议类型
-      List<UploadObject> uploadObjectList = uploadObjectService.get();
-      UploadObject uploadObject = uploadObjectList.stream().filter(s -> s.getId().equals(u.getUploadObjectId())).collect(Collectors.toList()).get(0);
-      if ("zj102_client".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-        Logger logger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-        if (FileConstant.nettyInstanceMap.get(u.getId() + "")!=null){
-          logger.info("通道:"+u.getChannelName()+",定时上报实例正在进行,此次定时不进行");
-        }
-        else{
-          logger.info("通道:"+u.getChannelName()+",定时任务执行开始");
-          // 缓存中有通道下的文件则开启client客户端
-          Map<String, UploadFileLog> filterMap = FileConstant.readyUploadFileMap.entrySet().stream().filter(r -> uploadObject.getObjectNo().equals(r.getKey().substring(0, r.getKey().indexOf("@"))))
-            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
-              (oldValue, newValue) -> oldValue, LinkedHashMap::new));
-          if (MapUtil.isNotEmpty(filterMap)) {
-            // 缓存中有文件,开启netty客户端
-            ZheJiangClient instance = new ZheJiangClient(u.getRemoteIp(), Integer.parseInt(u.getRemotePort()), logger,u);
-            FileConstant.nettyInstanceMap.put(u.getId() + "", instance);
-            instance.start();
-            logger.info("通道:"+u.getChannelName()+",定时任务执行结束");
-          }
-          else{
-            logger.info("通道:"+u.getChannelName()+",缓存中无文件");
-            logger.info("通道:"+u.getChannelName()+",定时任务执行结束");
-          }
-        }
-      }
-    }
-    return true;
-  }
-}

+ 1 - 5
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/AnalyticFeedback/AnalysisFeedbackFileService.java

@@ -8,14 +8,13 @@ import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
 import com.jiayue.ipfcst.common.data.constant.enums.*;
 import com.jiayue.ipfcst.common.data.entity.*;
 import com.jiayue.ipfcst.common.data.repository.FeedbackFileLogRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadFileChannelRepository;
 import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
 import com.jiayue.ipfcst.common.data.repository.UploadURLRepository;
 import com.jiayue.ipfcst.common.data.service.BaseService;
 import com.jiayue.ipfcst.console.service.ElectricFieldService;
+import com.jiayue.ipfcst.console.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
 import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import lombok.AllArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang.time.DateFormatUtils;
@@ -24,9 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.io.*;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;

+ 0 - 11
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/BaseUploadFileService.java

@@ -4,7 +4,6 @@ import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
 import com.jiayue.ipfcst.common.data.constant.enums.*;
 import com.jiayue.ipfcst.common.data.entity.*;
 import com.jiayue.ipfcst.common.data.repository.ReportWindTowerStatusDataRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadWindTowerStatusDataRepository;
 import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
 import com.jiayue.ipfcst.common.data.service.BaseService;
 
@@ -12,7 +11,6 @@ import com.jiayue.ipfcst.dataexchange.container.DataPackerContainer;
 import com.jiayue.ipfcst.dataexchange.dataprocesser.datapacker.AbstractDataPacker;
 import com.jiayue.ipfcst.dataexchange.service.EnvironmentDataAnyTimeGenerator;
 import com.jiayue.ipfcst.dataexchange.service.equipmentstatusdata.WindTowerStatusDataService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.util.FileUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.FileUtils;
@@ -108,11 +106,6 @@ public abstract class BaseUploadFileService extends BaseService {
                   uploadFileLog.setUploadFileEndTime(uploadFileEndTime);
 
                   uploadFileLog = this.uploadFileLogRepository.save(uploadFileLog);
-
-                  String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getName();
-                  FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
-                  FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
-
                   log.debug("文件生成存入缓存:" + file.getName());
                   log.info("上报对象编号:" + uploadObject.getObjectNo() + ",生成文件" + file.getName() + "成功");
                 } else {
@@ -199,10 +192,6 @@ public abstract class BaseUploadFileService extends BaseService {
                   uploadFileLog.setBackupA(format);
                   uploadFileLog = this.uploadFileLogRepository.save(uploadFileLog);
 
-                  String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getName();
-                  FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
-                  FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
-
                   log.debug("文件生成存入缓存:" + file.getName());
                   log.info("上报对象编号:" + uploadObject.getObjectNo() + ",生成文件" + file.getName() + "成功");
                 } else {

+ 1 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E37/E37UploadFileService.java

@@ -17,13 +17,13 @@ import com.jiayue.ipfcst.console.service.ForecastPowerShortTermService;
 import com.jiayue.ipfcst.console.service.ForecastPowerUltraShortTermService;
 import com.jiayue.ipfcst.console.service.InverterInfoService;
 import com.jiayue.ipfcst.console.service.NwpService;
+import com.jiayue.ipfcst.console.util.FileConstant;
 import com.jiayue.ipfcst.dataexchange.container.ProtocolTunnelContainer;
 import com.jiayue.ipfcst.dataexchange.repository.gathertunnelrepository.Gather104TcpTunnelRepository;
 import com.jiayue.ipfcst.dataexchange.service.FileParseTunnelService;
 import com.jiayue.ipfcst.fileupload.service.BaseUploadFileService;
 import com.jiayue.ipfcst.fileupload.service.IUploadFileService;
 import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.util.FileUtil;
 import com.sun.istack.internal.NotNull;
 import com.sun.management.OperatingSystemMXBean;

+ 1 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E43/E43UploadFileService.java

@@ -9,12 +9,12 @@ import com.jiayue.ipfcst.common.data.entity.*;
 import com.jiayue.ipfcst.common.data.repository.*;
 import com.jiayue.ipfcst.common.data.service.uploadfilerule.E43UploadFileRuleService;
 import com.jiayue.ipfcst.console.service.*;
+import com.jiayue.ipfcst.console.util.FileConstant;
 import com.jiayue.ipfcst.dataexchange.container.ProtocolTunnelContainer;
 import com.jiayue.ipfcst.dataexchange.service.FileParseTunnelService;
 import com.jiayue.ipfcst.fileupload.dto.FileUploadJsonDto;
 import com.jiayue.ipfcst.fileupload.service.BaseUploadFileService;
 import com.jiayue.ipfcst.fileupload.service.IUploadFileService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.util.FileUtil;
 import com.sun.management.OperatingSystemMXBean;
 import lombok.extern.slf4j.Slf4j;

+ 0 - 3
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E46/E46UploadFileService.java

@@ -17,7 +17,6 @@ import com.jiayue.ipfcst.fileupload.service.BaseUploadFileService;
 import com.jiayue.ipfcst.fileupload.service.IUploadFileService;
 import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
 import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.util.FileUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.io.FileUtils;
@@ -1797,8 +1796,6 @@ public class E46UploadFileService extends BaseUploadFileService implements IUplo
                   // 记录日志
 
                   uploadFileLog = this.uploadFileLogRepository.save(uploadFileLog);
-                  String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getName();
-                  FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
                   log.info("上报对象编号:" + uploadObject.getObjectNo() + ",生成文件" + file.getName() + "成功");
                   break;
                 }

+ 0 - 290
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/FtpUploadService.java

@@ -1,290 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.io.IoUtil;
-import cn.hutool.core.util.CharsetUtil;
-import cn.hutool.extra.ftp.Ftp;
-import cn.hutool.extra.ftp.FtpConfig;
-import cn.hutool.extra.ftp.FtpMode;
-import cn.hutool.extra.ssh.JschUtil;
-import cn.hutool.extra.ssh.Sftp;
-import com.jcraft.jsch.ChannelSftp;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.Session;
-import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.common.data.entity.UploadURL;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogDetailRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadURLRepository;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.io.File;
-import java.lang.reflect.Field;
-import java.nio.charset.Charset;
-import java.util.*;
-import java.util.stream.Collectors;
-
-@Service
-@Slf4j
-public class FtpUploadService {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService;
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  @Autowired
-  UploadFileLogDetailRepository uploadFileLogDetailRepository;
-  @Autowired
-  UploadObjectService uploadObjectService;
-  @Autowired
-  FtpUploadTransactionService ftpUploadTransactionService;
-  @Autowired
-  AppenderFactory appenderFactory;
-  @Autowired
-  UploadURLRepository uploadURLRepository;
-
-  /**
-   * 开启FTP客户端上报文件
-   */
-  public void startFtpUpload() {
-    Date d = new Date();
-    List<UploadObject> uploadObjectList = uploadObjectService.get();
-    // 过滤出ftp/sftp的上报对象
-    uploadObjectList = uploadObjectList.stream().filter(s -> s.getUploadProtocolEnum().toString().equals("E4") || s.getUploadProtocolEnum().toString().equals("E5")).collect(Collectors.toList());
-    if (uploadObjectList.size() > 0) {
-      // 获取通道信息
-      List<UploadFileChannel> uploadFileChannels = uploadFileChannelService.get();
-      // 遍历ftp的上报对象
-      for (UploadObject uploadObject : uploadObjectList) {
-        //找出可用的ftp通道
-        List<UploadFileChannel> uploadFileChannelList = uploadFileChannels.stream().filter(s -> s.getChannelStatusEnum().equals(ChannelStatusEnum.E1) && s.getUploadObjectId().equals(uploadObject.getId())).collect(Collectors.toList());
-        // 创建通道对应的日志
-        Logger logger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-
-        for (UploadFileChannel uploadFileChannel : uploadFileChannelList) {
-          List<UploadURL> uploadURLList = uploadURLRepository.findByUploadChannelId(uploadFileChannel.getId());
-
-          if (uploadObject.getUploadProtocolEnum().toString().equals("E4")) {
-            // FTP方式上报
-            Ftp ftp = null;
-            try {
-              FtpMode mode = null;
-              if ("E1".equals(uploadFileChannel.getFtpPassiveModeEnum().toString())) {
-                // 主动模式
-                mode = FtpMode.Active;
-              } else {
-                // 被动模式
-                mode = FtpMode.Passive;
-              }
-
-              FtpConfig ftpConfig = new FtpConfig();
-              ftpConfig.setHost(uploadFileChannel.getRemoteIp());
-              ftpConfig.setPort(Integer.parseInt(uploadFileChannel.getRemotePort()));
-              ftpConfig.setPassword(uploadFileChannel.getUploadPassword());
-              ftpConfig.setUser(uploadFileChannel.getUploadUserName());
-              ftpConfig.setCharset(Charset.forName(uploadObject.getUploadFileCharSetEnum().getMessage()));
-              ftpConfig.setConnectionTimeout(60 * 1000L);
-              ftpConfig.setSoTimeout(60 * 1000L);
-              try {
-                ftp = new Ftp(ftpConfig, mode);
-                logger.info(uploadFileChannel.getChannelName() + "ftp客户端连接成功");
-                // 连接成功,设置通道状态
-                FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-              } catch (Exception e) {
-                // 连接失败,设置通道状态
-                FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-                throw e;
-              }
-
-              // 获取缓存中的上报文件
-              logger.debug("上报文件缓存数量:" + FileConstant.readyUploadFileMap.size());
-              Map<String, UploadFileLog> fileMap = new HashMap<>();
-              fileMap.putAll(FileConstant.readyUploadFileMap);
-              for (Map.Entry<String, UploadFileLog> entry : fileMap.entrySet()) {
-                String[] keys = entry.getKey().split("@");
-                if (keys[0].equals(uploadObject.getObjectNo())) {
-                  // 获取缓存中对应的上报对象的文件
-                  logger.info("在缓存中找到通道[" + uploadFileChannel.getChannelName() + "]文件:" + keys[2]);
-                  ftpUploadTransactionService.singleUpload(uploadObject, uploadFileChannel, entry, ftp, null, keys, logger, uploadURLList);
-                }
-              }
-            } catch (Exception e) {
-              logger.error(uploadFileChannel.getChannelName() + "上报失败", e);
-//              try {
-//                Process process = Runtime.getRuntime().exec("ping "+uploadFileChannel.getRemoteIp() + " -c 2");
-//                InputStreamReader r = new InputStreamReader(process.getInputStream());
-//                LineNumberReader returnData = new LineNumberReader(r);
-//
-//                String returnMsg="";
-//                String line = "";
-//                while ((line = returnData.readLine()) != null) {
-//                  returnMsg += line;
-//                }
-//
-//                if(returnMsg.indexOf("100% loss")!=-1){
-//                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接不畅通.");
-//                }
-//                else{
-//                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接畅通.");
-//                }
-//
-//                returnData.close();
-//                r.close();
-//                process.getInputStream().close();
-//                process.getOutputStream().close();
-//                process.destroy();
-//
-//              } catch (IOException ex) {
-//                logger.error("ping对方ip执行失败",ex);
-//              }
-            } finally {
-              if (ftp != null) {
-                IoUtil.close(ftp);
-                logger.info(uploadFileChannel.getChannelName() + "ftp客户端关闭连接");
-              }
-            }
-          } else {
-            // SFTP方式上报
-            Sftp sftp = null;
-            JSch jsch = new JSch();
-            ChannelSftp channel = null;
-            Session sshSession = null;
-            try {
-              try {
-                sshSession = jsch.getSession(uploadFileChannel.getUploadUserName(), uploadFileChannel.getRemoteIp(), Integer.parseInt(uploadFileChannel.getRemotePort()));
-                sshSession.setPassword(uploadFileChannel.getUploadPassword());
-                sshSession.setTimeout(30000);
-                Properties sshConfig = new Properties();
-                sshConfig.put("StrictHostKeyChecking", "no");
-                sshSession.setConfig(sshConfig);
-                log.info("sftp开始连接...");
-                sshSession.connect();
-                channel = (ChannelSftp) sshSession.openChannel("sftp");
-                channel.connect();
-                Class cl = ChannelSftp.class;
-                Field f = cl.getDeclaredField("server_version");
-                f.setAccessible(true);
-                f.set(channel, 2);
-                channel.setFilenameEncoding(uploadObject.getUploadFileCharSetEnum().getMessage());
-              } catch (Exception e) {
-                log.error("sftp连接异常:" + e);
-              }
-              try {
-                //sftp = new Sftp(channel,CharsetUtil.CHARSET_GBK);
-                switch (uploadObject.getUploadFileCharSetEnum().getMessage()) {
-                  case "GBK":
-                    sftp = new Sftp(channel, CharsetUtil.CHARSET_GBK);
-                    break;
-                  case "UTF-8":
-                    sftp = new Sftp(channel, CharsetUtil.CHARSET_UTF_8);
-                    break;
-                  default:
-                    break;
-                }
-                /*FtpConfig ftpConfig = new FtpConfig(uploadFileChannel.getRemoteIp(), Integer.parseInt(uploadFileChannel.getRemotePort()), uploadFileChannel.getUploadUserName(), uploadFileChannel.getUploadPassword(), CharsetUtil.CHARSET_UTF_8);
-                ftpConfig.setConnectionTimeout(10000L);
-
-                sftp = new Sftp(ftpConfig);*/
-
-                logger.info(uploadFileChannel.getChannelName() + ":sftp连接创建成功");
-                // 连接成功,设置通道状态
-                FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-
-              } catch (Exception e) {
-                logger.error(uploadFileChannel.getChannelName() + ":sftp连接失败", e);
-                // 连接失败,设置通道状态
-                FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
-                throw e;
-              }
-              // 获取缓存中的上报文件
-              logger.debug("当前文件缓存数量:" + FileConstant.readyUploadFileMap.size());
-              Map<String, UploadFileLog> fileMap = new HashMap<>();
-              fileMap.putAll(FileConstant.readyUploadFileMap);
-              for (Map.Entry<String, UploadFileLog> entry : fileMap.entrySet()) {
-                String[] keys = entry.getKey().split("@");
-                UploadFileLog uploadFileLog = entry.getValue();
-                if (uploadFileLog.getUploadFileEndTime() == null) {
-                  if (keys[0].equals(uploadObject.getObjectNo())) {
-                    // 获取缓存中对应的上报对象的文件
-                    logger.info("在缓存中找到通道[" + uploadFileChannel.getChannelName() + "]文件:" + keys[2] + ",将文件送入到上报程序中。");
-                    ftpUploadTransactionService.singleUpload(uploadObject, uploadFileChannel, entry, null, sftp, keys, logger, uploadURLList);
-                  }
-                } else {
-                  if (d.getTime() <= uploadFileLog.getUploadFileEndTime()) {
-                    if (keys[0].equals(uploadObject.getObjectNo())) {
-                      // 获取缓存中对应的上报对象的文件
-                      logger.info("在缓存中找到通道[" + uploadFileChannel.getChannelName() + "]文件:" + keys[2] + ",将文件送入到上报程序中。");
-                      ftpUploadTransactionService.singleUpload(uploadObject, uploadFileChannel, entry, null, sftp, keys, logger, uploadURLList);
-                    }
-                  } else {
-                    String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-                    String targetPath = FileUtil.getFileUploadPath() + File.separator + "expire" + File.separator + keys[0] + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[1];
-                    try {
-                      FileUtil.move(srcPath, targetPath);
-                      log.info("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2]);
-                    } catch (Exception e) {
-                      log.error("上报对象编号:" + keys[0] + ",将过期的文件移到expire过期文件夹下:" + keys[2] + "失败", e);
-                    }
-                    // 清理缓存
-                    FileConstant.uploadCountMap.remove(entry.getKey());
-                    FileConstant.againUploadFileMap.remove(entry.getKey());
-                    FileConstant.readyUploadFileMap.remove(entry.getKey());
-                    FileConstant.fileShouldMomentMap.remove(entry.getKey());
-                    FileConstant.fileContentMap.remove(entry.getKey());
-                  }
-                }
-
-              }
-            } catch (Exception e) {
-              logger.error(uploadFileChannel.getChannelName() + "上报失败", e);
-//              try {
-//                Process process = Runtime.getRuntime().exec("ping "+uploadFileChannel.getRemoteIp() + " -c 2");
-//                InputStreamReader r = new InputStreamReader(process.getInputStream());
-//                LineNumberReader returnData = new LineNumberReader(r);
-//
-//                String returnMsg="";
-//                String line = "";
-//                while ((line = returnData.readLine()) != null) {
-//                  returnMsg += line;
-//                }
-//
-//                if(returnMsg.indexOf("100% loss")!=-1){
-//                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接不畅通.");
-//                }
-//                else{
-//                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接畅通.");
-//                }
-//
-//                returnData.close();
-//                r.close();
-//                process.getInputStream().close();
-//                process.getOutputStream().close();
-//                process.destroy();
-//
-//              } catch (IOException ex) {
-//                logger.error("ping对方ip执行失败",ex);
-//              }
-            } finally {
-              if (sftp != null) {
-                logger.info("sftp客户端关闭");
-                JschUtil.closeAll();
-                sftp.close();
-                channel.quit();
-                channel.disconnect();
-                sshSession.disconnect();
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-}

+ 0 - 321
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/FtpUploadTransactionService.java

@@ -1,321 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.util.StrUtil;
-import cn.hutool.extra.ftp.Ftp;
-import cn.hutool.extra.ssh.Sftp;
-import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.FileStatusEnum;
-import com.jiayue.ipfcst.common.data.constant.enums.ProvinceEnum;
-import com.jiayue.ipfcst.common.data.entity.*;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogDetailRepository;
-import com.jiayue.ipfcst.common.data.repository.UploadFileLogRepository;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
-import com.jiayue.ipfcst.fileupload.util.FileMutableInteger;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.apache.poi.ss.usermodel.Workbook;
-import org.apache.poi.ss.usermodel.WorkbookFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Propagation;
-import org.springframework.transaction.annotation.Transactional;
-
-import java.io.*;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-/**
- * FTP、SFTP上报类
- *
- * @author xsl
- * @version 3.0
- */
-@Service
-public class FtpUploadTransactionService extends BaseUploadFileService {
-  @Autowired
-  UploadFileLogRepository uploadFileLogRepository;
-  @Autowired
-  UploadFileLogDetailRepository uploadFileLogDetailRepository;
-
-
-  @Transactional(propagation = Propagation.REQUIRED)
-  public void singleUpload(UploadObject uploadObject, UploadFileChannel uploadFileChannel, Map.Entry<String, UploadFileLog> entry, Ftp ftp, Sftp sftp, String[] keys, Logger logger, List<UploadURL> uploadURLList) {
-
-    if (FileConstant.uploadCountMap.get(entry.getKey()) == null) {
-      FileMutableInteger fileMutableInteger = new FileMutableInteger(0);
-      FileConstant.uploadCountMap.put(entry.getKey(), fileMutableInteger);
-    }
-
-    // 上报次数
-    Integer fileUploadCount = FileConstant.uploadCountMap.get(entry.getKey()).getValue();
-    fileUploadCount++;
-    boolean isSuccess = false;
-    String srcPath = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + keys[0] + File.separator + keys[1] + File.separator + keys[2];
-    Long st = DateTimeUtil.getMillisecondsSubDay();
-    //明日凌晨
-    Long et = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24 - 1;
-    logger.info("准备上报:" + srcPath);
-    try {
-      if (ftp != null) {
-        InputStreamReader isr = null;
-        InputStream uploadFileIs = null;
-        try {
-          ftp = ftp.reconnectIfTimeout();
-          isr = new InputStreamReader(new FileInputStream(srcPath), "UTF-8");
-          StringBuffer sb = new StringBuffer("");
-          int len1 = 0;
-          while ((len1 = isr.read()) != -1) {
-            sb.append((char) len1);
-          }
-          isr.close();
-          String str = sb.toString();
-          uploadFileIs = new ByteArrayInputStream(str.getBytes(uploadObject.getUploadFileCharSetEnum().getMessage()));
-          String uploadFileName = new String(new File(srcPath).getName().getBytes(uploadObject.getUploadFileCharSetEnum().getMessage()), uploadObject.getUploadFileCharSetEnum().getMessage());
-          // 是否每个文件类型一个路径
-          if (StrUtil.hasBlank(uploadFileChannel.getBackupC()) || "0".equals(uploadFileChannel.getBackupC())) {
-            // 公用一个路径
-            isSuccess = ftp.upload(uploadFileChannel.getPathService(), uploadFileName, uploadFileIs);
-          } else {
-            // 多路径
-            UploadURL uploadURL = uploadURLList.stream().filter(c -> c.getFileTypeEnum().name().equals(keys[1])).collect(Collectors.toList()).get(0);
-            isSuccess = ftp.upload(uploadURL.getUploadURL(), uploadFileName, uploadFileIs);
-          }
-        } catch (Exception e) {
-          logger.error("ftp上传失败", e);
-          throw e;
-        } finally {
-          if (isr != null) {
-            isr.close();
-          }
-          if (uploadFileIs != null) {
-            uploadFileIs.close();
-          }
-        }
-      } else {
-        InputStreamReader isr = null;
-        InputStream uploadFileIs = null;
-        try {
-
-          //          sftp.getClient().setFilenameEncoding(uploadObject.getUploadFileCharSetEnum().getMessage());
-          String uploadFileName = new String(new File(srcPath).getName().getBytes(uploadObject.getUploadFileCharSetEnum().getMessage()), uploadObject.getUploadFileCharSetEnum().getMessage());
-
-          // 针对海南业务上报旧文件
-          ElectricField electricField = super.getElectricField();
-
-          if (electricField.getProvinceEnum().name().equals(ProvinceEnum.E13.name()) && uploadFileName.indexOf("CSV") > 0) {
-
-            FileInputStream inputStream = new FileInputStream(new File(srcPath));
-            ByteArrayOutputStream baos = new ByteArrayOutputStream();
-            Workbook workbook = WorkbookFactory.create(inputStream);
-            workbook.write(baos);// 临时存储流到内存
-
-            uploadFileIs = new ByteArrayInputStream(baos.toByteArray());
-            baos.flush();
-            workbook.close();
-            baos.close();
-            inputStream.close();
-
-          } else {
-            isr = new InputStreamReader(new FileInputStream(srcPath), "UTF-8");
-            StringBuffer sb = new StringBuffer("");
-            int len1 = 0;
-            while ((len1 = isr.read()) != -1) {
-              sb.append((char) len1);
-            }
-            isr.close();
-            String str = sb.toString();
-            uploadFileIs = new ByteArrayInputStream(str.getBytes(uploadObject.getUploadFileCharSetEnum().getMessage()));
-          }
-
-
-          if ("E46".equals(electricField.getProvinceEnum().toString())) {
-            // 海南自动生成日期路径需求
-            UploadURL uploadURL = uploadURLList.stream().filter(c -> c.getFileTypeEnum().name().equals(keys[1])).collect(Collectors.toList()).get(0);
-            String upPath = uploadURL.getUploadURL();
-//            String[] fileNameSplit = keys[2].substring(0, keys[2].indexOf(".")).split("_");
-//            String yearStr = fileNameSplit[2].substring(0, 4);
-//            String monthDayStr = fileNameSplit[2].substring(4);
-            // 用系统时间
-            Date systemDate = new Date();
-            String yearStr = DateFormatUtils.format(systemDate, "yyyy");
-            String monthDayStr = DateFormatUtils.format(systemDate, "MMdd");
-            upPath = upPath.replaceAll("DATE_YYYY", yearStr).replaceAll("DATE_MMDD", monthDayStr);
-            logger.info("final path:" + upPath);
-            upPath = yearStr + "/" + monthDayStr + "/" + upPath;
-            sftp.mkDirs(upPath);
-            sftp.getClient().put(uploadFileIs, upPath + "/" + uploadFileName);
-          } else {
-            if (StrUtil.hasBlank(uploadFileChannel.getBackupC()) || "0".equals(uploadFileChannel.getBackupC())) {
-
-              if (uploadFileChannel.getBackupD() != null && uploadFileChannel.getBackupD().equals("1")) {
-                String path = uploadFileChannel.getPathService() + "/" + DateFormatUtils.format(new Date(), "yyyyMMdd");
-                if (!sftp.exist(path)) {
-                  sftp.mkdir(path);
-                }
-                // 公用一个路径
-                sftp.getClient().put(uploadFileIs, path + "/" + uploadFileName);
-              } else {
-                // 公用一个路径
-                sftp.getClient().put(uploadFileIs, uploadFileChannel.getPathService() + "/" + uploadFileName);
-              }
-            } else {
-              // 多路径
-              UploadURL uploadURL = uploadURLList.stream().filter(c -> c.getFileTypeEnum().name().equals(keys[1])).collect(Collectors.toList()).get(0);
-              sftp.getClient().put(uploadFileIs, uploadURL.getUploadURL() + "/" + uploadFileName);
-            }
-          }
-          logger.info("上传远端put结束:" + keys[2]);
-          isSuccess = true;
-        } catch (Exception e) {
-          throw e;
-        } finally {
-          if (isr != null) {
-            isr.close();
-          }
-          if (uploadFileIs != null) {
-            uploadFileIs.close();
-          }
-        }
-      }
-    } catch (Exception e) {
-      isSuccess = false;
-      logger.error("上报通道:" + uploadFileChannel.getChannelName() + "," + keys[2] + "上报失败", e);
-      Integer id = FileConstant.fileShouldMomentMap.get(entry.getKey());
-      UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-      uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-      uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-      uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-      uploadFileLogDetail.setUploadFileLogId(id);
-      uploadFileLogDetail.setFileName(keys[2]);
-      uploadFileLogDetail.setUploadTime(new Date().getTime());
-      uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E3);
-      uploadFileLogDetail.setUploadFailureReason(e.getMessage());
-      uploadFileLogDetailRepository.save(uploadFileLogDetail);
-    } finally {
-      logger.info("上报通道:" + keys[0] + "," + keys[2] + "上报次数:" + fileUploadCount);
-      try {
-        if (isSuccess) {
-          // 更新日志表
-          FileStatusEnum fileStatusEnum = null;
-          if ("1".equals(uploadObject.getUploadD5000())) {
-            // 上报给D5000
-            fileStatusEnum = FileStatusEnum.E5;
-          } else {
-            fileStatusEnum = FileStatusEnum.E2;
-          }
-          Integer id = FileConstant.fileShouldMomentMap.get(entry.getKey());
-          uploadFileLogRepository.uploadFileUpdate(fileStatusEnum, fileUploadCount, id);
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "backups" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-          logger.info("移动文件至" + targetPath);
-          FileUtil.move(srcPath, targetPath);
-          logger.info("上报通道:" + keys[0] + ",文件:" + keys[0] + "上报成功,移动到backups目录");
-//          UploadFileLog uploadFileLog = uploadFileLogRepository.findById(id).get();
-          UploadFileLogDetail uploadFileLogDetail = new UploadFileLogDetail();
-          uploadFileLogDetail.setUploadObjectName(uploadObject.getUploadObjectName());
-          uploadFileLogDetail.setUploadFileLogId(id);
-          uploadFileLogDetail.setUploadTime(System.currentTimeMillis());
-          uploadFileLogDetail.setFileName(keys[2]);
-          uploadFileLogDetail.setUploadChanneId(uploadFileChannel.getId());
-          uploadFileLogDetail.setUploadChannelName(uploadFileChannel.getChannelName());
-          uploadFileLogDetail.setFileStatusEnum(fileStatusEnum);
-          uploadFileLogDetailRepository.save(uploadFileLogDetail);
-
-          // 上传成功,删除缓存里的文件
-          FileConstant.readyUploadFileMap.remove(entry.getKey());
-          FileConstant.uploadCountMap.remove(entry.getKey());
-          FileConstant.fileShouldMomentMap.remove(entry.getKey());
-        } else {
-          logger.info("上报失败。。。。。。。。。。。。。");
-//          try {
-//            Process process = Runtime.getRuntime().exec("ping "+uploadFileChannel.getRemoteIp() + " -c 2");
-//            InputStreamReader r = new InputStreamReader(process.getInputStream());
-//            LineNumberReader returnData = new LineNumberReader(r);
-//
-//            String returnMsg="";
-//            String line = "";
-//            while ((line = returnData.readLine()) != null) {
-//              returnMsg += line;
-//            }
-//
-//            if(returnMsg.indexOf("100% loss")!=-1){
-//              logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接不畅通.");
-//            }
-//            else{
-//              logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接畅通.");
-//            }
-//
-//            returnData.close();
-//            r.close();
-//            process.getInputStream().close();
-//            process.getOutputStream().close();
-//            process.destroy();
-//
-//          } catch (IOException e) {
-//            logger.error("ping对方ip执行失败",e);
-//          }
-          // 更新日志表
-          FileStatusEnum fileStatusEnum = null;
-          if ("1".equals(uploadObject.getUploadD5000())) {
-            // 上报给D5000
-            fileStatusEnum = FileStatusEnum.E6;
-          } else {
-            fileStatusEnum = FileStatusEnum.E3;
-          }
-          Integer id = FileConstant.fileShouldMomentMap.get(entry.getKey());
-          uploadFileLogRepository.uploadFileUpdate(fileStatusEnum, fileUploadCount, id);
-//          uploadFileLogRepository.updateFileUploadCount(fileStatusEnum, fileUploadCount, uploadObject.getId(), keys[2]);
-//          String fileMaxCount = super.getSysParameter("FILE_MAX_COUNT", "3");
-//          // 上报失败
-//          if (fileUploadCount >= Integer.parseInt(fileMaxCount)) {
-          logger.info("上报通道:" + keys[0] + "," + "移动到error目录");
-          String targetPath = FileUtil.getFileUploadPath() + File.separator + "error" + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[0] + File.separator + keys[1];
-          FileUtil.move(srcPath, targetPath);
-          FileConstant.readyUploadFileMap.remove(entry.getKey());
-          FileConstant.fileShouldMomentMap.remove(entry.getKey());
-          FileConstant.uploadCountMap.remove(entry.getKey());
-//          } else {
-//            FileMutableInteger fileMutableInteger = new FileMutableInteger(fileUploadCount);
-//            FileConstant.uploadCountMap.put(entry.getKey(), fileMutableInteger);
-//          }
-        }
-      } catch (Exception e) {
-        logger.error("sftp上报后finally里异常", e);
-      }
-    }
-  }
-
-  public void mkdirDir(String[] dirs, String tempPath, int length, int index, Sftp sftp) {
-    // 以"/a/b/c/d"为例按"/"分隔后,第0位是"";顾下标从1开始
-    index++;
-    if (index < length) {
-      // 目录不存在,则创建文件夹
-      tempPath += "/" + dirs[index];
-    }
-    try {
-      if (sftp.exist(tempPath)) {
-        if (index < length) {
-          mkdirDir(dirs, tempPath, length, index, sftp);
-        }
-      } else {
-        try {
-          sftp.mkdir(tempPath);
-          sftp.cd(tempPath);
-        } catch (Exception e) {
-          e.printStackTrace();
-        }
-        mkdirDir(dirs, tempPath, length, index, sftp);
-      }
-    } catch (Exception ex) {
-      try {
-        sftp.mkdir(tempPath);
-        sftp.cd(tempPath);
-      } catch (Exception e) {
-        e.printStackTrace();
-      }
-      mkdirDir(dirs, tempPath, length, index, sftp);
-    }
-  }
-}

+ 4 - 199
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/UploadFileChannelService.java

@@ -1,38 +1,18 @@
 package com.jiayue.ipfcst.fileupload.service;
 
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.util.StrUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
+
 import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
 import com.jiayue.ipfcst.common.data.repository.UploadFileChannelRepository;
 import com.jiayue.ipfcst.common.data.repository.UploadURLRepository;
-import com.jiayue.ipfcst.fileupload.IEC102.UploadFileNettyServer;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongClient;
-import com.jiayue.ipfcst.fileupload.IEC102.shandong.ShanDongServer;
-import com.jiayue.ipfcst.fileupload.IEC102.zhejiang.ZheJiangClient;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import lombok.extern.slf4j.Slf4j;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.search.Attribute;
-import net.sf.ehcache.search.Query;
-import net.sf.ehcache.search.Result;
-import net.sf.ehcache.search.Results;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.cache.ehcache.EhCacheCacheManager;
-import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
-
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
-import java.util.stream.Collectors;
 
 /**
  * 上报通道业务层
@@ -48,8 +28,6 @@ public class UploadFileChannelService {
   @Autowired
   EhCacheCacheManager ehCacheCacheManager;
   @Autowired
-  AppenderFactory appenderFactory;
-  @Autowired
   UploadObjectService uploadObjectService;
   @Autowired
   UploadURLRepository uploadURLRepository;
@@ -65,57 +43,8 @@ public class UploadFileChannelService {
   @Transactional(propagation = Propagation.SUPPORTS)
   public UploadFileChannel save(UploadFileChannel uploadFileChannel) {
     // 获取上报对象协议类型
-    List<UploadObject> uploadObjectList = uploadObjectService.get();
-    UploadObject uploadObject = uploadObjectList.stream().filter(s -> s.getId().equals(uploadFileChannel.getUploadObjectId())).collect(Collectors.toList()).get(0);
-    if (!"ftp".equals(uploadObject.getUploadProtocolEnum().getCode()) && !"sftp".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-      if (uploadFileChannel.getId() != null) {
-        if ("102s".equals(uploadObject.getUploadProtocolEnum().getCode())){
-          if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort()) != null){
-            FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort()).destroy();
-            FileConstant.nettyInstanceMap.remove(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort());
-          }
-        }
-        else{
-          // 102服务端,将原有的服务先销毁掉
-          if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getId()) != null) {
-            FileConstant.nettyInstanceMap.get(uploadFileChannel.getId()).destroy();
-            FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId());
-          }
-        }
-      }
-    }
-
-    UploadFileChannel uploadFileChannel1 = uploadFileChannelRepository.saveAndFlush(uploadFileChannel);
-
-    // 创建通道对应的日志
-    Logger logger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-
-    String protocol = uploadObject.getUploadProtocolEnum().getCode();
-
-    if ("102s".equals(protocol)) {
-      if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort()) == null) {
-        // 创建netty服务
-        UploadFileNettyServer uploadFileNettyServer = new UploadFileNettyServer(new InetSocketAddress(uploadFileChannel.getLocalIp(), Integer.parseInt(uploadFileChannel.getLocalPort())), Integer.parseInt(readerIdleTime));
-        // 开启102服务端
-        uploadFileNettyServer.start();
-        // 将netty服务端实例保存到缓存变量,用于关闭通道时用。
-        FileConstant.nettyInstanceMap.put(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort(), uploadFileNettyServer);
-      }
-    } else if ("102m_sd_client".equals(protocol)) {
-      ShanDongClient instance = new ShanDongClient(uploadFileChannel.getRemoteIp(), Integer.parseInt(uploadFileChannel.getRemotePort()), logger);
-      instance.start();
-      FileConstant.nettyInstanceMap.put(uploadFileChannel.getId() + "", instance);
-    } else if ("102m_sd_server".equals(protocol)) {
-      ShanDongServer instance = new ShanDongServer(new InetSocketAddress(uploadFileChannel.getLocalIp(), Integer.parseInt(uploadFileChannel.getLocalPort())), logger);
-      instance.start();
-      FileConstant.nettyInstanceMap.put(uploadFileChannel.getId() + "", instance);
-    } else if ("zj102_client".equals(protocol)) {
-      // 浙江丽水102特殊性,定时调用客户端短连接,所以将通道设置永远绿色=1
-      FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-    }
-
-    clearChannelCache();
-    return uploadFileChannel1;
+    uploadFileChannelRepository.saveAndFlush(uploadFileChannel);
+    return uploadFileChannel;
   }
   @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
   public void saveCloud(UploadFileChannel bean) {
@@ -136,46 +65,6 @@ public class UploadFileChannelService {
    */
   @Transactional(propagation = Propagation.SUPPORTS)
   public void delete(UploadFileChannel uploadFileChannel) {
-    // 获取上报对象协议类型
-    List<UploadObject> tempObjectList = uploadObjectService.get();
-    List<UploadObject> uploadObjectList = tempObjectList.stream().filter(s -> s.getId().equals(uploadFileChannel.getUploadObjectId())).collect(Collectors.toList());
-    if (uploadObjectList.size()>0){
-      UploadObject uploadObject = uploadObjectList.get(0);
-      if (!"ftp".equals(uploadObject.getUploadProtocolEnum().getCode()) && !"sftp".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-        String protocol = uploadObject.getUploadProtocolEnum().getCode();
-        if ("102s".equals(protocol)) {
-          String tempLocalPort = uploadFileChannel.getLocalPort();
-          String tempLocalIp = uploadFileChannel.getLocalIp();
-          List<UploadFileChannel> tempList = uploadFileChannelRepository.findAll();
-          List<UploadFileChannel> ufList = new ArrayList<>();
-          for (UploadFileChannel uf:tempList){
-            if (uf.getRemoteIp()!=null && uf.getLocalPort()!=null){
-              ufList.add(uf);
-            }
-          }
-
-          // 过滤出是否存在多个IP和端口相同的102服务通道
-          List<UploadFileChannel> filterList = ufList.stream().filter(s -> s.getLocalIp().equals(tempLocalIp) && s.getLocalPort().equals(tempLocalPort) && StrUtil.hasEmpty(s.getUploadUserName())).collect(Collectors.toList());
-          if (filterList.size() == 1) {
-            // 将netty服务端实例保存到缓存变量,用于关闭通道时用。
-            if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort()) != null) {
-              FileConstant.nettyInstanceMap.get(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort()).destroy();
-              FileConstant.nettyInstanceMap.remove(uploadFileChannel.getLocalIp() + ":" + uploadFileChannel.getLocalPort());
-            }
-          }
-        } else if ("102m_sd_client".equals(protocol) || "102m_sd_server".equals(protocol)) {
-          // 102服务端,将原有的服务先销毁掉
-          if (FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "") != null) {
-            FileConstant.nettyInstanceMap.get(uploadFileChannel.getId() + "").destroy();
-            FileConstant.nettyInstanceMap.remove(uploadFileChannel.getId() + "");
-          }
-        } else if ("zj102_client".equals(protocol)) {
-          FileConstant.channelStatusMap.remove(uploadObject.getId() + "-" + uploadFileChannel.getId());
-        }
-      }
-    }
-
-    clearChannelCache();
     uploadFileChannelRepository.delete(uploadFileChannel);
   }
 
@@ -186,18 +75,6 @@ public class UploadFileChannelService {
   public void deleteByObjId(Integer objId) {
     uploadFileChannelRepository.deleteAllByUploadObjectId(objId);
     uploadURLRepository.deleteByUploadObjectId(objId);
-    this.clearChannelCache();
-  }
-
-  /**
-   * 移除缓存中的通道信息
-   */
-  public void clearChannelCache() {
-    List<UploadFileChannel> uploadFileChannelList = this.get();
-    Cache cache = ehCacheCacheManager.getCacheManager().getCache("searchablecache");
-    for (UploadFileChannel uploadFileChannel : uploadFileChannelList) {
-      cache.remove("ufc" + uploadFileChannel.getId());
-    }
   }
 
   public List<UploadFileChannel> getByObjectId(Integer id) {
@@ -216,79 +93,7 @@ public class UploadFileChannelService {
    * @return 通道信息
    */
   public List<UploadFileChannel> get() {
-    Cache cache = ehCacheCacheManager.getCacheManager().getCache("searchablecache");
-    Query query = cache.createQuery();
-    //查询结果中包含Key和value
-    query.includeKeys().includeValues();
-    Attribute<String> keyName = cache.getSearchAttribute("key");
-    query.addCriteria(keyName.ilike("*ufc*"));
-    Results results = query.execute();
-    List<Result> resultList = results.all();
-
-    List<UploadFileChannel> list = new ArrayList();
-    if (resultList != null && !resultList.isEmpty()) {
-      for (Result result : resultList) {
-        UploadFileChannel e = (UploadFileChannel) result.getValue();
-        list.add(e);
-      }
-      results.discard();
-    } else {
-      //查询数据库
-      list = uploadFileChannelRepository.findAll();
-      for (UploadFileChannel uploadFileChannel : list) {
-        //将结果存入缓存
-        cache.put(new Element("ufc" + uploadFileChannel.getId(), uploadFileChannel));
-      }
-    }
+    List<UploadFileChannel> list = uploadFileChannelRepository.findAll();
     return list;
   }
-
-  /**
-   * 开启102所有服务端
-   */
-  @Scheduled(fixedDelay = 300000l)
-  public synchronized void startAllChannel() {
-    List<UploadFileChannel> uploadFileChannels = get();
-    // 取通道状态正常并且是102s的类型
-    List<UploadFileChannel> useChannelList = uploadFileChannels.stream().filter(s -> s.getChannelStatusEnum().equals(ChannelStatusEnum.E1)).collect(Collectors.toList());
-    for (UploadFileChannel u : useChannelList) {
-      // 获取上报对象协议类型
-      List<UploadObject> uploadObjectList = uploadObjectService.get();
-      UploadObject uploadObject = uploadObjectList.stream().filter(s -> s.getId().equals(u.getUploadObjectId())).collect(Collectors.toList()).get(0);
-
-      if (!"ftp".equals(uploadObject.getUploadProtocolEnum().getCode()) && !"sftp".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-        // 创建通道对应的日志
-        Logger logger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
-        if (FileConstant.nettyInstanceMap.get(u.getId()) != null) {
-          FileConstant.nettyInstanceMap.remove(u.getId());
-        }
-
-        if ("102s".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-          if (FileConstant.nettyInstanceMap.get(u.getLocalIp() + ":" + u.getLocalPort()) == null) {
-            // 创建netty服务
-            UploadFileNettyServer uploadFileNettyServer = new UploadFileNettyServer(new InetSocketAddress(u.getLocalIp(), Integer.parseInt(u.getLocalPort())), Integer.parseInt(readerIdleTime));
-            log.info(u.getChannelName()+"准备开启102服务.....");
-            // 开启102服务端
-            uploadFileNettyServer.start();
-            if(uploadFileNettyServer.future != null){
-              // 将netty服务端实例保存到缓存变量,用于关闭通道时用。
-              FileConstant.nettyInstanceMap.put(u.getLocalIp() + ":" + u.getLocalPort(), uploadFileNettyServer);
-            }
-
-          }
-        } else if ("102m_sd_client".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-          ShanDongClient instance = new ShanDongClient(u.getRemoteIp(), Integer.parseInt(u.getRemotePort()), logger);
-          instance.start();
-          FileConstant.nettyInstanceMap.put(u.getId() + "", instance);
-        } else if ("102m_sd_server".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-          ShanDongServer instance = new ShanDongServer(new InetSocketAddress(u.getLocalIp(), Integer.parseInt(u.getLocalPort())), logger);
-          instance.start();
-          FileConstant.nettyInstanceMap.put(u.getId() + "", instance);
-        } else if ("zj102_client".equals(uploadObject.getUploadProtocolEnum().getCode())) {
-          // 浙江丽水102特殊性,定时调用客户端短连接,所以将通道设置永远绿色=1
-          FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + u.getId(), "1");
-        }
-      }
-    }
-  }
 }

+ 0 - 31
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/UploadFileLogService.java

@@ -9,7 +9,6 @@ import com.jiayue.ipfcst.common.data.repository.*;
 import com.jiayue.ipfcst.common.data.service.uploadfilerule.IUploadFileRuleService;
 import com.jiayue.ipfcst.console.service.ElectricFieldService;
 import com.jiayue.ipfcst.console.service.SysParameterService;
-import com.jiayue.ipfcst.fileupload.util.FileConstant;
 import com.jiayue.ipfcst.fileupload.util.FileUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang.StringUtils;
@@ -292,15 +291,9 @@ public class UploadFileLogService {
         newUploadFileLog.setUploadFileEndTime(null);
         newUploadFileLog.setFileRemarks("手动上传文件");
         uploadFileLog = this.uploadFileLogRepository.save(newUploadFileLog);
-        String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getOriginalFilename();
-        FileConstant.readyUploadFileMap.put(readyFileKey, newUploadFileLog);
-        FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
         log.info("上报对象编号:" + uploadObject.getObjectNo() + ",上传文件" + file.getOriginalFilename() + "成功");
       } else {
         uploadFileLog.setUploadCounter(0);
-        String readyFileKey = uploadObject.getObjectNo() + "@" + fileType + "@" + file.getOriginalFilename();
-        FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
-        FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
         log.info("上报对象编号:" + uploadObject.getObjectNo() + ",覆盖上传文件" + file.getOriginalFilename() + "成功");
       }
       ManualUploadLog manualUploadLog = new ManualUploadLog();
@@ -403,30 +396,6 @@ public class UploadFileLogService {
   }
 
   /*
-   * 清理缓存
-   */
-  public void cleanCache(UploadFileLog uploadFileLog) {
-    try {
-      String key = uploadFileLog.getUploadObjectNo() + "@" + uploadFileLog.getFileTypeEnum() + "@" + uploadFileLog.getFileName();
-      /*待上报文件的缓存变量*/
-      FileConstant.readyUploadFileMap.remove(key);
-      FileConstant.fileShouldMomentMap.remove(key);
-      /*文件上报次数累计的缓存变量*/
-      FileConstant.uploadCountMap.remove(key);
-      /*文件内容缓存变量*/
-      FileConstant.fileContentMap.remove(key);
-      /*文件内容及内容位置缓存变量*/
-      FileConstant.fileContentByIdxMap.remove(key);
-      /*遇到不正常回复时,将文件暂时放入再次上报变量*/
-      FileConstant.againUploadFileMap.remove(key);
-    } catch (Exception e) {
-      log.info("上报日志清除缓存异常:" + e);
-    }
-
-  }
-
-
-  /*
    * 文件补报
    */
   public void report(UploadFileLog uploadFileLog) {

+ 0 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/UploadURLService.java

@@ -1,6 +1,5 @@
 package com.jiayue.ipfcst.fileupload.service;
 
-import com.jiayue.ipfcst.common.data.entity.UploadFileCode;
 import com.jiayue.ipfcst.common.data.entity.UploadURL;
 import com.jiayue.ipfcst.common.data.repository.UploadURLRepository;
 import org.springframework.beans.factory.annotation.Autowired;

+ 0 - 72
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/util/FileConstant.java

@@ -1,72 +0,0 @@
-package com.jiayue.ipfcst.fileupload.util;
-
-import ch.qos.logback.classic.Logger;
-import cn.hutool.core.date.DateTime;
-import com.jiayue.ipfcst.common.data.entity.UploadFileLog;
-import com.jiayue.ipfcst.fileupload.IEC102.NettyParent;
-import com.jiayue.ipfcst.fileupload.dto.Validate102Dto;
-import lombok.extern.slf4j.Slf4j;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * 上报文件公用变量
- *
- * @author xsl
- * @version 3.0
- */
-@Slf4j
-public class FileConstant {
-  /*待上报文件的缓存变量,Map<上报对象编号-文件类型-文件名,文件本地路径及文件名>*/
-  public static ConcurrentMap<String, UploadFileLog> readyUploadFileMap = new ConcurrentHashMap<String, UploadFileLog>();
-  /*文件上报次数累计的缓存变量,Map<上报对象编号-文件类型-文件名,上报次数>*/
-  public static ConcurrentMap<String, FileMutableInteger> uploadCountMap = new ConcurrentHashMap<String, FileMutableInteger>();
-  /*文件上报次数累计的缓存变量,山东专用>*/
-  public static ConcurrentMap<String, FileMutableInteger> sdUploadCountMap = new ConcurrentHashMap<String, FileMutableInteger>();
-  /*文件内容缓存变量,Map<上报对象编号-文件类型-文件名,16进制文件内容>*/
-  public static ConcurrentMap<String, String> fileContentMap = new ConcurrentHashMap<String, String>();
-  /*文件内容及内容位置缓存变量,Map<上报对象编号-文件类型-文件名,map<16进制文件内容,内容在原来来文件的位置>>*/
-  public static ConcurrentMap<String, Map<String,String>> fileContentByIdxMap = new ConcurrentHashMap<String, Map<String,String>>();
-  /*netty服务实例集合<通道主键ID,netty服务端实例>*/
-  public static ConcurrentMap<String, NettyParent> nettyInstanceMap = new ConcurrentHashMap<String,NettyParent>();
-  /*通道状态集合<上报对象id-通道id,通讯状态> 通讯状态:1通0不通*/
-  public static ConcurrentMap<String,String> channelStatusMap = new ConcurrentHashMap<String,String>();
-  /*下载文件内容缓存变量,Map<上报对象编号-文件类型,16进制文件内容>*/
-  public static ConcurrentMap<String, String> downLoadFileContentMap = new ConcurrentHashMap<String, String>();
-  public static ConcurrentMap<String, Logger> uploadLogMap = new ConcurrentHashMap<>();
-  /*验证对方报文回复正确性<通道主键ID,下一次交互的传输原因>*/
-  public static ConcurrentMap<String,Validate102Dto> validateMessage = new ConcurrentHashMap<>();
-  /*遇到不正常回复时,将文件暂时放入再次上报变量,Map<上报对象编号-文件类型-文件名,"">*/
-  public static ConcurrentMap<String, String> againUploadFileMap = new ConcurrentHashMap<String, String>();
-  /*文件对应的生成时间,Map<上报对象编号-文件类型-文件名,日志表主键ID>*/
-  public static ConcurrentMap<String, Integer> fileShouldMomentMap = new ConcurrentHashMap<String, Integer>();
-  /*文件包次数Map<上报对象编号-文件类型-文件名,包次数>*/
-  public static ConcurrentMap<String, String> filePackageNumMap = new ConcurrentHashMap<String, String>();
-  /*保存102哪个通道在连接Map<Ip,端口>*/
-  public static ConcurrentMap<String, Integer> channelIpPortMap = new ConcurrentHashMap<String, Integer>();
-  /*通道状态集合<上报对象id,状态> 通讯状态:1通0不通*/
-  public static ConcurrentMap<String,Long> channelTimeMap = new ConcurrentHashMap<String,Long>();
-  /*通道上报对象状态集合<上报对象id,通讯状态> 通讯状态:1通0不通*/
-  public static ConcurrentMap<Integer,String> objectStatusMap = new ConcurrentHashMap<Integer, String>();
-
-  /**
-   * 蒙西发送68帧开关
-   */
-  public static boolean mengxiSend68 = false;
-  /**
-   * 蒙西文件内容计数器 -1结束、0开始
-   */
-  public static int fileContentCounter = -1;
-
-  public static String mxCurrentFileName = "";
-
-  public static String controlReversal = "53";
-
-  public static boolean mxstatus = false;
-
-  public static Date uploadSuccessTime = null;
-
-  public static boolean isSendVisitPath = true;
-}

+ 0 - 39
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/util/FileUploadMonitor.java

@@ -1,39 +0,0 @@
-package com.jiayue.ipfcst.fileupload.util;
-
-import org.apache.commons.io.monitor.FileAlterationListener;
-import org.apache.commons.io.monitor.FileAlterationMonitor;
-import org.apache.commons.io.monitor.FileAlterationObserver;
-
-import java.io.File;
-
-/**
- * 上报文件目录监控
- *
- * @author xsl
- * @version 3.0
- * @since 2020/4/13 19:00
- */
-public class FileUploadMonitor {
-  FileAlterationMonitor monitor = null;
-
-  public FileUploadMonitor(long interval) throws Exception {
-    monitor = new FileAlterationMonitor(interval);
-  }
-
-  //监控方法
-  public void monitor(String path, FileAlterationListener listener) {
-    FileAlterationObserver observer = new FileAlterationObserver(new File(path));
-    monitor.addObserver(observer);
-    observer.addListener(listener);
-  }
-
-  //监控停止
-  public void stop() throws Exception {
-    monitor.stop();
-  }
-
-  //监控开始
-  public void start() throws Exception {
-    monitor.start();
-  }
-}

+ 0 - 41
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/IEC102/shandong/ShanDongClientTest.java

@@ -1,41 +0,0 @@
-package com.jiayue.ipfcst.fileupload.IEC102.shandong;
-
-import ch.qos.logback.classic.Logger;
-import ch.qos.logback.classic.LoggerContext;
-import ch.qos.logback.core.rolling.RollingFileAppender;
-import com.jiayue.ipfcst.BaseTest;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-/**
- * 山东102客户端测试
- *
- * @author xsl
- * @version 3.0
- */
-class ShanDongClientTest extends BaseTest {
-  @Autowired
-  AppenderFactory appenderFactory;
-
-  @Test
-  void connect() {
-    // 创建通道对应的日志
-    Logger logger = appenderFactory.getLogger("testNo", "山东102客户端测试","1");
-    ShanDongClient instance = new ShanDongClient("192.168.240.1",3001,logger);
-    instance.start();
-//    try {
-//      Thread.sleep(60000L);
-//    } catch (InterruptedException e) {
-//      e.printStackTrace();
-//    }
-//
-//    instance.destroy();
-
-    while (true){
-
-    }
-  }
-}

+ 0 - 43
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/TestUploadFileType.java

@@ -1,43 +0,0 @@
-package com.jiayue.ipfcst.fileupload;
-
-import java.sql.*;
-
-/**
- * TODO
- *
- * @author xsl
- * @version 3.0
- */
-public class TestUploadFileType {
-  public static void main(String[] args) throws Exception{
-    String driver = "com.mysql.cj.jdbc.Driver";
-    String url = "jdbc:mysql://localhost:3306/ipfcst-v3?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&characterSetResults=UTF-8&autoReconnect=true&rewriteBatchedStatements=true";
-    String username = "root";
-    String password = "!QAZ2root";
-    Class.forName(driver);
-    Connection conn = DriverManager.getConnection(url,username, password);
-    Statement stmt = conn.createStatement();
-    ResultSet rs = stmt.executeQuery("select * from t_upload_file_type");
-    while(rs.next()) {
-      int id = rs.getInt(1)-1;
-      String pname = rs.getString(2);
-      String penum = rs.getString(3);
-      String fname = rs.getString(4);
-      String fenum = rs.getString(5);
-      String code = rs.getString(6);
-
-      String str = "INSERT INTO t_upload_file_type (C_ID, C_PROVINCE_NAME, C_PROVINCE_ENUM, C_FILE_TYPE_NAME, C_FILE_TYPE_ENUM, C_UPLOAD_CODE) select "+ id+",'"+pname+"','"+penum+"','"+fname+"','"+fenum+"',"+code+" from dual where not exists (select C_ID from t_upload_file_type where C_ID = "+id+")" ;
-
-      System.out.println(str);
-
-    }
-    try {
-      if (stmt != null)
-        stmt.close();
-      if (conn != null)
-        conn.close();
-    } catch (SQLException e) {
-      throw new RuntimeException(e);
-    }
-  }
-}

+ 0 - 20
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/job/UploadFileShortTermTypeJobTest.java

@@ -1,20 +0,0 @@
-package com.jiayue.ipfcst.fileupload.job;
-
-import com.jiayue.ipfcst.BaseTest;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import org.junit.jupiter.api.Test;
-import org.quartz.JobDataMap;
-import org.springframework.beans.factory.annotation.Autowired;
-
-
-class UploadFileShortTermTypeJobTest extends BaseTest {
-
-  @Autowired
-  private UploadFileE1Job uploadFileShortTermTypeJob;
-
-  @Test
-  void getFileType() {
-    JobDataMap jobDataMap = null;
-    uploadFileShortTermTypeJob.execute(jobDataMap);
-  }
-}

+ 0 - 73
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/E42/E42UploadFileServiceTest.java

@@ -1,73 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service.E42;
-
-import com.jiayue.ipfcst.BaseTest;
-import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.ElectricField;
-import com.jiayue.ipfcst.common.data.entity.Quartz;
-import com.jiayue.ipfcst.common.data.repository.QuartzRepository;
-import com.jiayue.ipfcst.common.data.service.BaseService;
-import com.jiayue.ipfcst.common.data.service.uploadfilerule.E15UploadFileRuleService;
-import com.jiayue.ipfcst.common.data.service.uploadfilerule.E23UploadFileRuleService;
-import com.jiayue.ipfcst.common.data.service.uploadfilerule.E33UploadFileRuleService;
-import com.jiayue.ipfcst.common.data.service.uploadfilerule.E37UploadFileRuleService;
-import com.jiayue.ipfcst.fileupload.service.E13.E13UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.E14.E14UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.E21.E21UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.E33.E33UploadFileService;
-import com.jiayue.ipfcst.fileupload.service.E65.TestE65UploadFileService;
-import org.hibernate.service.spi.ServiceException;
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-import static org.junit.jupiter.api.Assertions.*;
-
-class E42UploadFileServiceTest extends BaseTest {
-  @Autowired
-  E42UploadFileService e42UploadFileService;
-  @Autowired
-  E21UploadFileService e21UploadFileService;
-  @Autowired
-  E13UploadFileService e13UploadFileService;
-  @Autowired
-  E15UploadFileRuleService e15UploadFileRuleService;
-  @Autowired
-  QuartzRepository quartzRepository;
-  @Autowired
-  E23UploadFileRuleService e23UploadFileRuleService;
-  @Autowired
-  BaseService baseService;
-  @Autowired
-  E37UploadFileRuleService e37UploadFileRuleService;
-  @Autowired
-  E14UploadFileService e14UploadFileService;
-  @Autowired
-  TestE65UploadFileService testE65UploadFileService;
-
-  @Test
-  void generateFile() throws Exception {
-//    DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
-//    Date myDate1 = dateFormat1.parse("2020-10-30");
-//
-//    Quartz quartz = quartzRepository.findByExecuteClass("com.jiayue.ipfcst.fileupload.job.UploadFileE2Job");
-//    List<String> list = e15UploadFileRuleService.getShouldFile(e21UploadFileService.getElectricField(), new Date(), "E2",quartz.getCronExpression());
-//    System.out.println("一共需要:" + list.size());
-//    for (int i = 0; i < list.size(); i++) {
-//      System.out.println(list.get(i));
-//    }
-    // 短期默认天数
-//    e13UploadFileService.generateFile("E1");
-//    List<String> list = e33UploadFileRuleService.getShouldFile(baseService.getElectricField(),new Date(),"E2","59 0/1 * * * ?");
-//    for (String str:list) {
-//      System.out.println(str);
-//    }
-
-      e21UploadFileService.generateFile("E159",null);
-//    testE65UploadFileService.generateFile("E2");
-  }
-}

+ 0 - 257
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/E65/TestE65UploadFileService.java

@@ -1,257 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service.E65;
-
-import cn.hutool.core.date.DateUtil;
-import com.jiayue.ipfcst.common.core.exception.BusinessException;
-import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
-import com.jiayue.ipfcst.common.data.entity.ElectricField;
-import com.jiayue.ipfcst.common.data.entity.ForecastPowerShortTerm;
-import com.jiayue.ipfcst.common.data.entity.ForecastPowerShortTermHis;
-import com.jiayue.ipfcst.common.data.entity.ForecastPowerUltraShortTermHis;
-import com.jiayue.ipfcst.common.data.repository.ForecastPowerShortTermRepository;
-import com.jiayue.ipfcst.fileupload.service.BaseUploadFileService;
-import com.jiayue.ipfcst.fileupload.service.IUploadFileService;
-import com.jiayue.ipfcst.fileupload.util.FileUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.time.DateFormatUtils;
-import org.apache.commons.lang.time.DateUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.springframework.stereotype.Service;
-import org.springframework.util.ResourceUtils;
-
-import java.io.*;
-import java.math.BigDecimal;
-import java.util.*;
-import java.util.stream.Collectors;
-
-/**
- * 新疆上报文件生成
- *
- * @author tl
- * @version 3.0
- */
-@Service
-@Slf4j
-public class TestE65UploadFileService extends BaseUploadFileService implements IUploadFileService {
-
-  private String vmsPath = FileUtil.getResourceBasePath() + "/vms/E65";
-
-  private final VelocityEngine velocityEngine;
-
-  private final ForecastPowerShortTermRepository forecastPowerShortTermRepository;
-
-  public TestE65UploadFileService(VelocityEngine velocityEngine, ForecastPowerShortTermRepository forecastPowerShortTermRepository) {
-    this.velocityEngine = velocityEngine;
-    this.forecastPowerShortTermRepository = forecastPowerShortTermRepository;
-  }
-
-
-  @Override
-  public Map<String,String> getUploadFileType() {
-    Map<String,String> uploadFileTypeMap = new HashMap<>();
-    uploadFileTypeMap.put(FileTypeEnum.E2.toString(),FileTypeEnum.E2.getMessage());
-    return uploadFileTypeMap;
-  }
-
-  @Override
-  public void generateFile(String fileType,Date date) {
-    switch (fileType) {
-      case "E1":
-        // 可用超短期
-        this.generateE1File(null);
-        break;
-      case "E2":
-        // 可用超短期
-        this.generateE2File(null);
-        break;
-      default:
-        break;
-    }
-  }
-
-  /**
-   * 生成短期预测上报文件。
-   */
-  private void generateE1File(Date date) {
-    // 获取短期模板
-    Template template = this.velocityEngine.getTemplate(this.vmsPath + "/DQ.vm");
-    if (template != null) {
-      VelocityContext velocityContext;
-      StringWriter writer;
-      String fileName;
-      File file;
-
-      // 短期默认天数
-      int dqDays = 3;
-      // 场站标识
-      String sign = "ZLTHG3";
-      // 装机容量
-      String cap = "40.0";
-      // 文件生成路径
-      String filePath = "d:\\test\\ZLTHG3\\dq\\";
-
-      try {
-        // 开始时间
-        String[] startTimeStr = {"2021-04-06","2021-04-07","2021-04-08","2021-04-09","2021-04-10"};
-
-        // 文件个数
-        for (int i=0;i<startTimeStr.length;i++){
-          Date startDate = DateUtil.parse(startTimeStr[i]);
-          // 数据开始天数
-          Long startTime = DateMomentUtil.getDayStartTime(DateUtils.addDays(startDate, 1).getTime());
-          Long endTime = DateMomentUtil.getDayLastTime(DateUtils.addDays(startDate, 3).getTime()) - 1000;
-          List<ForecastPowerShortTerm> forecastPowerShortTermList = forecastPowerShortTermRepository.findByForecastTimeBetween(startTime,endTime);
-          if (forecastPowerShortTermList.size()!=288){
-            System.out.println("================不是288个退出startTime:"+startTime);
-            break;
-          }
-          forecastPowerShortTermList.sort(Comparator.comparing(ForecastPowerShortTerm::getForecastTime));
-          // 生成上报文件名格式
-          fileName = sign+"_"+DateFormatUtils.format(startTime, "yyyyMMdd")+"_0000_DQ.WPD";
-          // 创建上报文件
-          file = new File(filePath+fileName);
-          // 根据模板生成文件内容
-          velocityContext = new VelocityContext();
-          velocityContext.put("vList", forecastPowerShortTermList);
-          //场站标识
-          velocityContext.put("sign", sign);
-          //场站装机容量
-          velocityContext.put("capacity", cap);
-          //系统当前日期
-          velocityContext.put("currentTime", DateFormatUtils.format(startDate, "yyyy-MM-dd_" + "00:00:00"));
-          //上报数据开始日期
-          velocityContext.put("uploadTime", DateFormatUtils.format(startTime, "yyyy-MM-dd_") + "00:00");
-          writer = new StringWriter();
-          template.merge(velocityContext, writer);
-          FileOutputStream os = null;
-          try {
-            os = new FileOutputStream(file);
-            // 采用UTF-8字符集
-            os.write(writer.toString().getBytes("GBK"));
-            os.flush();
-          } catch (IOException e) {
-            throw new RuntimeException(e);
-          } finally {
-            if (os != null) {
-              try {
-                os.close();
-              } catch (IOException e) {
-                log.error("文件生成关闭流失败", e);
-              }
-            }
-          }
-        }
-      } catch (Exception e) {
-        log.error("文件生成失败", e);
-      }
-    } else {
-      log.error("短期上报模板不存在!");
-    }
-  }
-
-
-  /**
-   * 生成超短期预测上报文件。
-   */
-  private void generateE2File(Date date) {
-    // 获取超短期模板
-    File file1 = null;
-    try {
-      file1 = ResourceUtils.getFile(this.vmsPath + "/CDQ.vm");
-    } catch (FileNotFoundException e) {
-      e.printStackTrace();
-    }
-    Template template = this.velocityEngine.getTemplate(file1.getPath());
-    if (template != null) {
-      VelocityContext velocityContext;
-      StringWriter writer;
-      File file;
-
-      // 获取当前系统时间
-      Date systemDate = new Date();
-      // 短期默认天数
-      int cdqPoint = 16;
-      // 场站标识
-      String sign = "ZLTHG3";
-      // 装机容量
-      String cap = "40.0";
-      // 文件生成路径
-      String filePath = "d:\\test\\ZLTHG3\\cdq\\";
-      // 开始时间
-      String startTimeStr = "2021-04-06 23:45:00";
-      Long startLongTime = DateUtil.parse(startTimeStr).getTime();
-      // 结束时间
-      String endTimeStr = "2021-04-12 03:45:00";
-      Long endLongTime = DateUtil.parse(endTimeStr).getTime();
-
-      try {
-        List<ForecastPowerShortTerm> forecastPowerShortTermList = forecastPowerShortTermRepository.findByForecastTimeBetween(startLongTime,endLongTime);
-        System.out.println(forecastPowerShortTermList.size());
-
-        for (Long tempDateTime = startLongTime; tempDateTime <= endLongTime; tempDateTime = tempDateTime + 15 * 60 * 1000) {
-          // 数据开始时间
-          Long dateStartTime = tempDateTime + 15 * 60 * 1000;
-          // 数据结束时间
-          Long dateEndTime = tempDateTime + 16 * 15 * 60 * 1000;
-
-          List<ForecastPowerShortTerm> filterList = forecastPowerShortTermList.stream().filter(p -> p.getForecastTime().longValue()>=dateStartTime && p.getForecastTime().longValue()<=dateEndTime).collect(Collectors.toList());
-
-          if (filterList.size()!=16){
-            System.out.println("================不是16个退出dateStartTime:"+dateStartTime);
-            break;
-          }
-
-          // 生成超短期数据
-          List<ForecastPowerUltraShortTermHis> cdqList = new ArrayList<ForecastPowerUltraShortTermHis>();
-          for (ForecastPowerShortTerm forecastPowerShortTerm:filterList){
-            ForecastPowerUltraShortTermHis forecastPowerUltraShortTermHis = new ForecastPowerUltraShortTermHis();
-            forecastPowerUltraShortTermHis.setAbleValue(forecastPowerShortTerm.getFpValue().multiply(new BigDecimal("1.05")).setScale(2,BigDecimal.ROUND_HALF_UP));
-            cdqList.add(forecastPowerUltraShortTermHis);
-          }
-
-          String fileName =  sign+"_"+DateFormatUtils.format(dateStartTime, "yyyyMMdd_HHmm")+"_CDQ.WPD";
-          // 创建上报文件
-          file = new File(filePath+fileName);
-          // 根据模板生成文件内容
-          velocityContext = new VelocityContext();
-          velocityContext.put("vList", cdqList);
-          // 场站标识
-          velocityContext.put("sign", sign);
-          // 场站装机容量
-          velocityContext.put("capacity", cap);
-          // 系统当前日期
-          velocityContext.put("currentTime", DateFormatUtils.format(tempDateTime, "yyyy-MM-dd_HH:mm") + ":00");
-          // 上报数据开始日期
-          velocityContext.put("uploadTime", DateFormatUtils.format(dateStartTime, "yyyy-MM-dd_HH:mm"));
-          writer = new StringWriter();
-          template.merge(velocityContext, writer);
-
-          FileOutputStream os = null;
-          try {
-            os = new FileOutputStream(file);
-            // 采用UTF-8字符集
-            os.write(writer.toString().getBytes("GBK"));
-            os.flush();
-          } catch (IOException e) {
-            throw new RuntimeException(e);
-          } finally {
-            if (os != null) {
-              try {
-                os.close();
-              } catch (IOException e) {
-                log.error("文件生成关闭流失败", e);
-              }
-            }
-          }
-        }
-      } catch (Exception e) {
-        log.error("文件生成失败", e);
-      }
-    } else {
-      log.error("超短期上报模板不存在!");
-    }
-  }
-}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 0 - 12
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseCreateFile.java


+ 0 - 66
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseMxCreateFile.java

@@ -1,66 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service;
-
-import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
-
-/**
- * 标准102上报报文反生成文件
- *
- * @author xsl
- * @version 3.0
- */
-public class InverseMxCreateFile {
-  public static void main(String[] args) throws Exception {
-    // 报文用逗号分隔
-    String messageStr = "68 3a 01 68 53 ff ff ac 01 0d ff ff 00 00 00 00 00 00 00 29 01 2f 2f 20 32 30 32 33 2d 31 32 2d 31 31 20 31 34 3a 31 35 3a 30 30 0a 3c 21 20 45 6e 74 69 74 79 3d 66 6f 72 65 63 61 73 74 64 61 74 61 20 74 79 70 65 3d 47 44 54 58 48 20 74 69 6d 65 3d 27 32 30 32 33 2d 31 32 2d 31 31 5f 31 34 3a 31 35 27 20 21 3e 0a 3c 66 6f 72 65 63 61 73 74 64 61 74 61 3a 3a 47 44 54 58 48 3e 0a 40 69 64 09 d4 a4 b2 e2 d6 b5 0a 23 31 09 35 37 2e 39 36 0a 23 32 09 35 33 2e 31 36 0a 23 33 09 35 30 2e 33 33 0a 23 34 09 34 37 2e 38 36 0a 23 35 09 34 38 2e 35 36 0a 23 36 09 34 31 2e 37 30 0a 23 37 09 33 39 2e 34 37 0a 23 38 09 33 35 2e 36 34 0a 23 39 09 33 31 2e 37 31 0a 23 31 30 09 32 38 2e 32 37 0a 23 31 31 09 32 37 2e 34 35 0a 23 31 32 09 31 38 2e 34 39 0a 23 31 33 09 31 36 2e 30 33 0a 23 31 34 09 30 2e 30 30 0a 23 31 35 09 30 2e 30 30 0a 23 31 36 09 30 2e 30 30 0a 23 31 37 09 30 2e 30 30 0a 3c 2f 66 6f 72 65 63 61 73 74 64 61 74 61 3a 3a 47 44 54 58 48 3e 0a 99 16";
-    // 文件名称长度
-    Integer fileNameLength = 120;
-    // 生成文件编码格式
-    String charset = "gb2312";
-    messageStr = messageStr.replace(" ", "");
-    String[] tempMessage = messageStr.split(",");
-    String fileNameHex = "";
-    StringBuffer sb = new StringBuffer("");
-    for (int i = 0; i < tempMessage.length; i++) {
-      // 循环每一帧的报文
-      String m = tempMessage[i];
-      // 获取文件内容帧
-//      if ("".equals(fileNameHex)) {
-//        fileNameHex = m.substring(42, 42 + fileNameLength * 2);
-//      }
-      // 拼接文件内容
-      sb.append(m.substring(24, m.length() - 4));
-    }
-//    // 文件名去掉尾部占位的0
-//    fileNameHex = fileNameHex.replaceAll("0*$", "");
-//    int fileNameHexLength = fileNameHex.length();
-//    byte[] fnData = new byte[fileNameHexLength / 2];
-//    for (
-//      int k = 0;
-//      k < fileNameHexLength; k += 2) {
-//      fnData[k / 2] = (byte) ((Character.digit(fileNameHex.charAt(k), 16) << 4)
-//        + Character.digit(fileNameHex.charAt(k + 1), 16));
-//    }
-//    String filename = new String(fnData, charset);
-//    System.out.println("文件名:"+filename);
-//    filename = filename.substring(filename.lastIndexOf("/"));
-
-    // 生成文件内容
-    String contentStr = messageStr.substring(42, messageStr.length() - 4);
-
-    System.out.println(contentStr);
-
-    int fileContentHexLength = contentStr.length();
-    byte[] data = new byte[fileContentHexLength / 2];
-    for (
-      int i = 0;
-      i < fileContentHexLength; i += 2) {
-      data[i / 2] = (byte) ((Character.digit(contentStr.charAt(i), 16) << 4)
-        + Character.digit(contentStr.charAt(i + 1), 16));
-    }
-    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\test.ppd" ), charset);
-    String res = new String(data, charset);
-    osw.write(res);
-    osw.close();
-  }
-}

+ 0 - 56
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseNMCreateFile.java

@@ -1,56 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service;
-import java.io.*;
-
-/**
- * 蒙东102上报报文反生成文件
- *
- * @author xsl
- * @version 3.0
- */
-public class InverseNMCreateFile {
-  public static void main(String[] args) throws Exception {
-    // 文件基本信息报文
-    String fileBaseInfo = "68 5E 00 68 28 FF FF C6 01 06 FF FF 00 42 5A 51 4C 53 5F 32 30 32 30 31 31 30 36 30 34 34 35 5F 43 44 51 2E 57 50 44 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 22 1B 01 00 00 21 D7 B2 D5 20 72 2F 52 DA 46 2E 3D 2A 9A 3C A3 83 16";
-    fileBaseInfo = fileBaseInfo.replace(" ", "");
-    // 报文内容用逗号分隔
-    String messageStr = "68 2A 01 68 08 FF FF C7 01 08 FF FF 00 00 00 00 00 1B 01 2F 2F 31 35 0A 2F 2F 20 32 30 32 30 2D 31 31 2D 30 36 5F 30 34 3A 33 30 3A 30 30 0A 3C 21 20 45 6E 74 69 74 79 3D 66 6F 72 65 63 61 73 74 64 61 74 61 20 74 79 70 65 3D 42 5A 51 4C 53 20 74 69 6D 65 3D 27 32 30 32 30 2D 31 31 2D 30 36 5F 30 34 3A 34 35 3A 30 30 27 20 21 3E 0A 3C 66 6F 72 65 63 61 73 74 64 61 74 61 3A 3A 42 5A 51 4C 53 3E 0A 40 69 64 20 D4 A4 B2 E2 D6 B5 0A 23 31 09 30 2E 30 30 0A 23 32 09 30 2E 30 30 0A 23 33 09 30 2E 30 30 0A 23 34 09 30 2E 30 30 0A 23 35 09 30 2E 30 30 0A 23 36 09 30 2E 30 30 0A 23 37 09 30 2E 30 30 0A 23 38 09 30 2E 30 30 0A 23 39 09 30 2E 30 30 0A 23 31 30 09 30 2E 30 30 0A 23 31 31 09 31 2E 32 35 0A 23 31 32 09 32 2E 34 36 0A 23 31 33 09 33 2E 36 34 0A 23 31 34 09 34 2E 39 37 0A 23 31 35 09 36 2E 36 31 0A 23 31 36 09 38 2E 34 36 0A 3C 2F 66 6F 72 65 63 61 73 74 64 61 74 61 3A 3A 42 5A 51 4C 53 3E 0A D6 16 ";
-    // 文件名称长度
-    Integer fileNameLength = 64;
-    // 生成文件编码格式
-    String charset = "GBK";
-    messageStr = messageStr.replace(" ", "");
-    String[] tempMessage = messageStr.split(",");
-    StringBuffer sb = new StringBuffer("");
-    for (int i = 0; i < tempMessage.length; i++) {
-      // 循环每一帧的报文
-      String m = tempMessage[i];
-      // 拼接文件内容
-      sb.append(m.substring(38, m.length() - 4));
-    }
-    // 文件名去掉尾部占位的0
-    String fileNameHex = fileBaseInfo.substring(26,26 + fileNameLength * 2).replaceAll("0*$", "");
-    int fileNameHexLength = fileNameHex.length();
-    byte[] fnData = new byte[fileNameHexLength / 2];
-    for (
-      int k = 0;
-      k < fileNameHexLength; k += 2) {
-      fnData[k / 2] = (byte) ((Character.digit(fileNameHex.charAt(k), 16) << 4)
-        + Character.digit(fileNameHex.charAt(k + 1), 16));
-    }
-    String filename = new String(fnData, charset);
-    // 生成文件内容
-    String contentStr = sb.toString();
-    int fileContentHexLength = contentStr.length();
-    byte[] data = new byte[fileContentHexLength / 2];
-    for (
-      int i = 0;
-      i < fileContentHexLength; i += 2) {
-      data[i / 2] = (byte) ((Character.digit(contentStr.charAt(i), 16) << 4)
-        + Character.digit(contentStr.charAt(i + 1), 16));
-    }
-    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\" + filename), charset);
-    String res = new String(data, charset);
-    osw.write(res);
-    osw.close();
-  }
-}

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 0 - 12
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/InverseSDCreateFile.java


+ 0 - 16
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/Test.java

@@ -1,16 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service;
-
-import cn.hutool.core.util.RuntimeUtil;
-
-/**
- * TODO
- *
- * @author xsl
- * @version 3.0
- */
-public class Test {
-  public static void main(String[] args) {
-    String str = RuntimeUtil.execForStr("ping 192.168.9.103 -c 4");
-    System.out.println(str);
-  }
-}

+ 0 - 147
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/service/UploadFileChannelServiceTest.java

@@ -1,147 +0,0 @@
-package com.jiayue.ipfcst.fileupload.service;
-
-import com.jiayue.ipfcst.BaseTest;
-import com.jiayue.ipfcst.common.data.constant.enums.ChannelStatusEnum;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.fileupload.IEC102.UploadFileNettyServer;
-import org.junit.jupiter.api.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-import javax.xml.bind.DatatypeConverter;
-import java.io.*;
-import java.net.InetSocketAddress;
-import java.util.List;
-
-class UploadFileChannelServiceTest  extends BaseTest {
-  @Autowired
-  UploadFileChannelService uploadFileChannelService;
-  @Autowired
-  FtpUploadService ftpUploadService;
-
-  @Test
-  void testFtpUploadService() {
-    ftpUploadService.startFtpUpload();
-  }
-
-  @Test
-  void testUploadChannel() {
-    Authentication auth = new UsernamePasswordAuthenticationToken("test", null);
-    SecurityContextHolder.getContext().setAuthentication(auth);
-    UploadFileChannel uploadFileChannel = new UploadFileChannel();
-    uploadFileChannel.setChannelName("集控文件上报通道");
-//    uploadFileChannel.setChannelNo("3");
-    uploadFileChannel.setChannelStatusEnum(ChannelStatusEnum.E1);
-//    uploadFileChannel.setUploadFileType("E1");
-    uploadFileChannelService.save(uploadFileChannel);
-    System.out.println("保存成功");
-
-    try {
-      List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.get();
-      for (UploadFileChannel u:uploadFileChannelList) {
-        System.out.println("缓存中通道名称:"+u.getChannelName());
-      }
-    } catch (Exception e) {
-      e.printStackTrace();
-    }
-  }
-
-  @Test
-  void testStartIec102Server() {
-    // 创建netty服务
-//    String ip="";
-//    for (int i=0;i<1;i++){
-//      if (i==0){
-//        ip="192.168.9.110";
-//      }
-//      else{
-//        ip="1192.168.9.110";
-//      }
-//      UploadFileNettyServer uploadFileNettyServer = new UploadFileNettyServer(new InetSocketAddress(ip, 3000), null,10);
-//      // 开启102服务端
-//      uploadFileNettyServer.start();
-//      System.out.println("开启"+i);
-//    }
-
-    UploadFileNettyServer uploadFileNettyServer = new UploadFileNettyServer(new InetSocketAddress("127.0.0.1", 7803),10);
-    // 开启102服务端
-    uploadFileNettyServer.start();
-    try {
-      Thread.sleep(300000);
-    } catch (InterruptedException e) {
-      e.printStackTrace();
-    }
-  }
-
-  @Test
-  /**
-   * 测试文件编码
-   */
-  void fileCharset() throws Exception{
-    InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\GDDYY_cft_202002201650.rb"),"UTF-8");
-//    BufferedReader reader = new BufferedReader(isr);
-//    String s = null;
-    StringBuffer sb = new StringBuffer("");
-//    while((s = reader.readLine())!=null){//使用readLine方法,一次读一行
-//      sb.append(s.getBytes("UTF-8"));
-//    }
-//    reader.close();
-
-    int len1 = 0;
-    while((len1 = isr.read())!=-1){
-      sb.append((char)len1);
-    }
-    isr.close();
-//    System.out.println(System.getProperty("file.encoding"));
-//    System.out.println(Charset.defaultCharset().name());
-//
-//    String str = FileUtils.readFileToString(new File("D:\\GDDYY_cft_202002201650.rb"));
-//
-    String str = sb.toString();
-    String a = DatatypeConverter.printHexBinary(str.getBytes("UTF-8"));
-//    System.out.println(a);
-//
-//    System.out.println(new String(DatatypeConverter.parseHexBinary(a)));
-//    System.out.println(new String(DatatypeConverter.parseHexBinary(a),"GBK"));
-    a = a.replaceAll(" ", "");
-    int len = a.length();
-    byte[] data = new byte[len / 2];
-    for (
-      int i = 0;
-      i < len; i += 2) {
-      data[i / 2] = (byte) ((Character.digit(a.charAt(i), 16) << 4)
-        + Character.digit(a.charAt(i + 1), 16));
-    }
-
-    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\qaz.PVD"),"UTF-8");
-    String res = new String(data);
-    osw.write(res);
-    osw.close();
-
-//    String message = "你好2019,Hello2019!<>&*^()#@$_=+-;;";
-//    String charsetName = "UTF-8";
-//    System.out.println("使用字符集:" + charsetName);
-//    System.out.println("被转换十进制字符串:" + message);
-//    byte[] b = message.getBytes(charsetName);
-//    System.out.println("十进制字符串转二进制数组(由高到低):" + Arrays.toString(b));
-//    String hexString = DataTypeConverter.bytesToHexStringFromHighToLow(b);
-//    System.out.println("十六进制字符串(由高到低)" + hexString);
-//    b = DataTypeConverter.hexStringToBytesFromHighToLow(hexString);
-//    System.out.println("十六进制字符串转二进制数组(由高到低):" + Arrays.toString(b));
-//    message = new String(b, charsetName);
-//    System.out.println("二进制转十进制字符串(由高到低):" + message);
-//
-//    b = DataTypeConverter.bytesFlipping(message.getBytes(charsetName));
-//    System.out.println("十进制字符串转二进制数组(由低到高):" + Arrays.toString(b));
-//    hexString = DataTypeConverter.bytesToHexStringFromLowToHigh(b);
-//    System.out.println("十六进制字符串(由低到高)" + hexString);
-//    b = DataTypeConverter.hexStringToBytesFromLowToHigh(hexString);
-//    System.out.println("十六进制字符串转二进制数组(由低到高):" + Arrays.toString(b));
-//    message = new String(DataTypeConverter.bytesFlipping(b), charsetName);
-//    System.out.println("二进制转十进制字符串(由低到高):" + message);
-  }
-
-
-}

+ 0 - 68
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiang102.java

@@ -1,68 +0,0 @@
-package com.jiayue.ipfcst.fileupload.zhejiang;
-
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.*;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-
-
-/**
- * TODO
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiang102 {
-  private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
-  private final EventLoopGroup workerGroup = new NioEventLoopGroup(1);
-
-  public static void main(String[] args) {
-    //1.定义server启动类
-    ServerBootstrap serverBootstrap = new ServerBootstrap();
-
-    //2.定义工作组:boss分发请求给各个worker:boss负责监听端口请求,worker负责处理请求(读写)
-    EventLoopGroup boss = new NioEventLoopGroup();
-    EventLoopGroup worker = new NioEventLoopGroup();
-
-    //3.定义工作组
-    serverBootstrap.group(boss,worker);
-
-    //4.设置通道channel
-    serverBootstrap.channel(NioServerSocketChannel.class);//A
-    //serverBootstrap.channelFactory(new ReflectiveChannelFactory(NioServerSocketChannel.class));//旧版本的写法,但是此过程在A中有同样过程
-
-    //5.添加handler,管道中的处理器,通过ChannelInitializer来构造
-    serverBootstrap.childHandler(new ChannelInitializer<Channel>() {
-      @Override
-      protected void initChannel(Channel channel) throws Exception {
-        //此方法每次客户端连接都会调用,是为通道初始化的方法
-
-        //获得通道channel中的管道链(执行链、handler链)
-        ChannelPipeline pipeline = channel.pipeline();
-        pipeline.addLast("decoder",new ZheJiangFor102Decoder());
-        pipeline.addLast("encoder",new ZheJiangFor102Encoder());
-        pipeline.addLast(new ZheJiangHandler());
-      }
-    });
-
-    //6.设置参数
-    //设置参数,TCP参数
-    serverBootstrap.option(ChannelOption.SO_BACKLOG, 2048);         //连接缓冲池的大小
-    serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);//维持链接的活跃,清除死链接
-    serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);//关闭延迟发送
-
-    //7.绑定ip和port
-    try {
-      ChannelFuture channelFuture = serverBootstrap.bind("192.168.9.110", 9800).sync();//Future模式的channel对象
-      //7.5.监听关闭
-      channelFuture.channel().closeFuture().sync();  //等待服务关闭,关闭后应该释放资源
-    } catch (InterruptedException e) {
-      System.out.println("server start got exception!");
-      e.printStackTrace();
-    }finally {
-      //8.优雅的关闭资源
-      boss.shutdownGracefully();
-      worker.shutdownGracefully();
-    }
-  }
-}

+ 0 - 180
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiangFor102Decoder.java

@@ -1,180 +0,0 @@
-package com.jiayue.ipfcst.fileupload.zhejiang;
-
-import ch.qos.logback.classic.Logger;
-import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
-import com.jiayue.ipfcst.common.data.entity.UploadFileChannel;
-import com.jiayue.ipfcst.common.data.entity.UploadObject;
-import com.jiayue.ipfcst.fileupload.config.AppenderFactory;
-import com.jiayue.ipfcst.fileupload.service.UploadFileChannelService;
-import com.jiayue.ipfcst.fileupload.service.UploadObjectService;
-import com.jiayue.ipfcst.fileupload.util.ByteUtil;
-import io.netty.buffer.ByteBuf;
-import io.netty.buffer.Unpooled;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.util.ReferenceCountUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import javax.xml.bind.DatatypeConverter;
-import java.net.InetSocketAddress;
-import java.util.List;
-import java.util.stream.Collectors;
-
-/**
- * 102解码器
- *
- * @author xsl
- * @version 3.0
- */
-@Slf4j
-public class ZheJiangFor102Decoder extends SimpleChannelInboundHandler {
-  //记录上次未读完的字节
-  ByteBuf tempMessage = Unpooled.buffer();
-
-  @Override
-  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
-    ByteBuf msgCopy = (ByteBuf) msg;
-    int inSize = msgCopy.readableBytes();
-
-    if (inSize > 0) {
-      // tempMessage为缓存区,在此缓存解码报文
-      if (tempMessage.readableBytes() == 0) {
-        tempMessage = msgCopy.copy(0, inSize);
-      } else {
-        tempMessage.writeBytes(msgCopy);
-      }
-      if (log.isDebugEnabled()){
-        // 显示当前缓存里的内容
-        if (tempMessage.readableBytes() > 0) {
-          byte[] tempByte = new byte[tempMessage.readableBytes()];
-          tempMessage.readBytes(tempByte);
-          String tempByteInfo = DatatypeConverter.printHexBinary(tempByte);
-        }
-      }
-
-      // 读下标重置
-      tempMessage.resetReaderIndex();
-      // 6个以上字节才报文解码
-      if (tempMessage.readableBytes() >= 6) {
-        // 此变量为了一串报文能继续往下解码
-        int i = 0;
-        while (true) {
-          String message = "";
-          // 检查10和68的下标位置
-          int s10 = tempMessage.indexOf(i, tempMessage.readableBytes(), (byte) 16);
-          int s68 = tempMessage.indexOf(i, tempMessage.readableBytes(), (byte) 104);
-          if (s10 == -1 && s68 == -1) {
-            // 10和68的都不存在,也就是都是-1,报文里没有关键字退出循环,等待接收下次内容
-            break;
-          } else if ((s10 > -1 && s68 > -1 && s10 < s68) || (s10 > -1 && s68 == -1)) {
-            // 调用10固定帧解码规则
-            message = handlerMessage10(s10, tempMessage);
-            if ("".equals(message)) {
-              i = s10 + 1;
-            }
-          } else if ((s10 > -1 && s68 > -1 && s68 < s10) || (s68 > -1 && s10 == -1)) {
-            // 调用68可变帧解码规则
-            message = handlerMessage68(s68, tempMessage);
-            if ("".equals(message)) {
-              i = s68 + 1;
-            }
-          }
-          if (!"".equals(message)) {
-            // 解码成功将下标重置0为了继续下一个解码循环
-            i = 0;
-            ctx.fireChannelRead(message);
-          }
-        }
-      }
-      tempMessage.resetReaderIndex();
-    }
-  }
-
-  /**
-   * 10固定帧报文处理
-   *
-   * @param s10       10所在缓存字节下标位置
-   * @param inMessage 缓存内容
-   * @return 符合固定帧规则的十六进制报文字符串
-   */
-  private String handlerMessage10(int s10, ByteBuf inMessage) {
-    int inMessageLength = inMessage.readableBytes();
-    String message = "";
-    // 调用10固定帧规则
-    if (s10 + 5 <= inMessageLength) {
-      byte e16 = inMessage.getByte(s10 + 5);
-      if (e16 == (byte) 22) {
-        // 找到了10开头并且16结尾的固定报文
-        ByteBuf gd10 = inMessage.copy(s10, 6);
-        byte[] kdst = new byte[gd10.readableBytes()];
-        gd10.readBytes(kdst);
-        message = DatatypeConverter.printHexBinary(kdst);
-        handlerLoseMessage(s10, inMessage);
-        inMessage.readerIndex(s10 + 6);
-        // 删除报文到解码成功最后一位
-        inMessage.discardReadBytes();
-        ReferenceCountUtil.release(gd10);
-      }
-    }
-    return message;
-  }
-
-  /**
-   * 68可变帧报文处理
-   *
-   * @param s68       68所在缓存字节下标位置
-   * @param inMessage 缓存内容
-   * @return 符合固定帧规则的十六进制报文字符串
-   */
-  private String handlerMessage68(int s68, ByteBuf inMessage) {
-    int inMessageLength = inMessage.readableBytes();
-    String message = "";
-    // 判断第二个68
-    int second68 = inMessage.indexOf(s68 + 3, inMessageLength, (byte) 104);
-    if (second68 == s68 + 3) {
-      // 获取2个68之间的报文长度低高位
-      ByteBuf b = inMessage.copy(s68 + 1, 2);
-      byte[] dst = new byte[b.readableBytes()];
-      b.readBytes(dst);
-      // 将低高位反转
-      String messageLength = DatatypeConverter.printHexBinary(ByteUtil.bytesFlipping(dst));
-      // 算出第二个68后面数据段长度
-      int tempLength = ByteUtil.hexToDec(messageLength);
-      int end16 = second68 + tempLength + 2;
-      if (inMessageLength - 1 >= end16) {
-        // 满足长度,再判断是否以16结尾
-        if (inMessage.indexOf(end16, end16 + 1, (byte) 22) > -1) {
-          // 合法可变报文,将可变报文转成16进制给业务
-          ByteBuf kb = inMessage.copy(s68, 4 + tempLength + 2);
-          byte[] kdst = new byte[kb.readableBytes()];
-          kb.readBytes(kdst);
-          message = DatatypeConverter.printHexBinary(kdst);
-          handlerLoseMessage(s68, inMessage);
-          inMessage.readerIndex(end16 + 1);
-          inMessage.discardReadBytes();
-          ReferenceCountUtil.release(kb);
-        }
-      }
-      ReferenceCountUtil.release(b);
-    }
-    return message;
-  }
-
-  /**
-   * 显示头之前没用的报文
-   *
-   * @param useHeadIndex
-   * @param inMessage
-   */
-  private void handlerLoseMessage(int useHeadIndex, ByteBuf inMessage) {
-    if (useHeadIndex > 0) {
-      // 舍弃的报文
-      ByteBuf loseMessage = inMessage.copy(0, useHeadIndex);
-      byte[] loseByte = new byte[loseMessage.readableBytes()];
-      loseMessage.readBytes(loseByte);
-      String loseInfo = DatatypeConverter.printHexBinary(loseByte);
-      ReferenceCountUtil.release(loseMessage);
-    }
-  }
-}

+ 0 - 21
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiangFor102Encoder.java

@@ -1,21 +0,0 @@
-package com.jiayue.ipfcst.fileupload.zhejiang;
-
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.MessageToByteEncoder;
-
-import java.math.BigInteger;
-
-/**
- * 102编码器
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiangFor102Encoder extends MessageToByteEncoder<String> {
-    @Override
-    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
-      BigInteger bigint=new BigInteger(msg, 16);
-      out.writeBytes(bigint.toByteArray());
-    }
-}

+ 0 - 103
ipfcst-console/src/test/java/com/jiayue/ipfcst/fileupload/zhejiang/ZheJiangHandler.java

@@ -1,103 +0,0 @@
-package com.jiayue.ipfcst.fileupload.zhejiang;
-import com.jiayue.ipfcst.fileupload.util.IEC102Uitl;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-
-import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
-
-/**
- * TODO
- *
- * @author xsl
- * @version 3.0
- */
-public class ZheJiangHandler extends ChannelInboundHandlerAdapter {
-  /**
-   * 客户端连接会触发
-   */
-  @Override
-  public void channelActive(ChannelHandlerContext ctx) throws Exception {
-    System.out.println("连接服务端");
-  }
-
-  /**
-   * 客户端发消息会触发
-   */
-  @Override
-  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
-    System.out.println("接收到内容:"+msg);
-    String receiveMessage = "";
-    if ("1040FFFF3E16".equals(msg)){
-      receiveMessage = "100BFFFF0916";
-    }
-    else{
-      // 文件名称长度
-      Integer fileNameLength = 64;
-      // 生成文件编码格式
-      String charset = "GBK";
-      String jsbw = (String)(msg);
-      jsbw = jsbw.replace(" ", "");
-      String[] tempMessage = jsbw.split(",");
-      String fileNameHex = "";
-      String yfileName = "";
-      StringBuffer sb = new StringBuffer("");
-      for (int i = 0; i < tempMessage.length; i++) {
-        // 循环每一帧的报文
-        String m = tempMessage[i];
-        // 获取文件内容帧
-        if ("".equals(fileNameHex)) {
-          fileNameHex = m.substring(30, 30 + fileNameLength * 2);
-        }
-        // 拼接文件内容
-        sb.append(m.substring(30 + fileNameLength * 2, m.length() - 4));
-      }
-      // 文件名去掉尾部占位的0
-      yfileName = fileNameHex;
-      fileNameHex = fileNameHex.replaceAll("0*$", "");
-      int fileNameHexLength = fileNameHex.length();
-      byte[] fnData = new byte[fileNameHexLength / 2];
-      for (
-        int k = 0;
-        k < fileNameHexLength; k += 2) {
-        fnData[k / 2] = (byte) ((Character.digit(fileNameHex.charAt(k), 16) << 4)
-          + Character.digit(fileNameHex.charAt(k + 1), 16));
-      }
-      String filename = new String(fnData, charset);
-      // 生成文件内容
-      String contentStr = sb.toString();
-      int fileContentHexLength = contentStr.length();
-      byte[] data = new byte[fileContentHexLength / 2];
-      for (
-        int i = 0;
-        i < fileContentHexLength; i += 2) {
-        data[i / 2] = (byte) ((Character.digit(contentStr.charAt(i), 16) << 4)
-          + Character.digit(contentStr.charAt(i + 1), 16));
-      }
-      OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\test\\zj\\" + filename), charset);
-      String res = new String(data, charset);
-      osw.write(res);
-      osw.close();
-      receiveMessage = "684D0068530B070001960B0700AD010000"+yfileName+"D016";
-    }
-    ctx.channel().writeAndFlush(receiveMessage);
-  }
-
-  /**
-   * 发生异常触发
-   */
-  @Override
-  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-    System.out.println("发生异常:"+cause);
-    ctx.close();
-  }
-
-  /**
-   * 通道断开触发
-   */
-  @Override
-  public void channelInactive(ChannelHandlerContext ctx) throws Exception {
-    System.out.println(ctx.channel().remoteAddress() + "通道断开");
-    super.channelInactive(ctx);
-  }
-}

+ 182 - 40
ipfcst-upload/pom.xml

@@ -54,6 +54,11 @@
 
     <dependencies>
         <dependency>
+            <groupId>com.jiayue.ipfcst</groupId>
+            <artifactId>ipfcst-common-data</artifactId>
+            <version>3.0.0</version>
+        </dependency>
+        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-actuator</artifactId>
         </dependency>
@@ -63,12 +68,6 @@
             <artifactId>spring-boot-configuration-processor</artifactId>
             <optional>true</optional>
         </dependency>
-        <!--jasypt配置文件加解密-->
-        <dependency>
-            <groupId>com.github.ulisesbocchio</groupId>
-            <artifactId>jasypt-spring-boot-starter</artifactId>
-            <version>${jasypt-boot.version}</version>
-        </dependency>
         <!--Lombok-->
         <dependency>
             <groupId>org.projectlombok</groupId>
@@ -98,7 +97,20 @@
             <artifactId>fastjson</artifactId>
             <version>${fastjson.version}</version>
         </dependency>
-
+<!--        <dependency>-->
+<!--            <groupId>org.apache.commons</groupId>-->
+<!--            <artifactId>commons-lang3</artifactId>-->
+<!--        </dependency>-->
+<!--        <dependency>-->
+<!--            <groupId>org.apache.commons</groupId>-->
+<!--            <artifactId>commons-dbcp2</artifactId>-->
+<!--            <version>${commons-dbcp2.version}</version>-->
+<!--        </dependency>-->
+        <dependency>
+            <groupId>commons-fileupload</groupId>
+            <artifactId>commons-fileupload</artifactId>
+            <version>${commons.fileupload.version}</version>
+        </dependency>
         <dependency>
             <groupId>org.reflections</groupId>
             <artifactId>reflections</artifactId>
@@ -110,23 +122,17 @@
                 </exclusion>
             </exclusions>
         </dependency>
-
         <dependency>
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-websocket</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-undertow</artifactId>
         </dependency>
         <dependency>
-            <groupId>commons-fileupload</groupId>
-            <artifactId>commons-fileupload</artifactId>
-            <version>${commons.fileupload.version}</version>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.velocity</groupId>
@@ -149,17 +155,6 @@
             <artifactId>commons-net</artifactId>
             <version>${commons.net.version}</version>
         </dependency>
-
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-aop</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>net.sourceforge.jexcelapi</groupId>
-            <artifactId>jxl</artifactId>
-            <version>2.6.10</version>
-        </dependency>
-
         <!-- SSH安全连接所使用的类库 -->
         <dependency>
             <groupId>com.jcraft</groupId>
@@ -176,11 +171,9 @@
             <properties>
                 <npm>npm.cmd</npm>
             </properties>
-
             <activation>
                 <activeByDefault>true</activeByDefault>
             </activation>
-
         </profile>
         <profile>
             <id>linux</id>
@@ -238,23 +231,172 @@
                     <skipTests>true</skipTests>
                 </configuration>
             </plugin>
-            <!-- 插件maven-clean-plugin,用于在编译前,清除之前编译的文件、文件夹等,避免残留之前的内容 -->
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>2.1.7.RELEASE</version>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+            <!--////////////////////////////////////////////////////小包配置开始//////////////////////////////////////-->
+            <!--拷贝依赖jar文件到ipfcst-lib目录下-->
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-clean-plugin</artifactId>
+                <artifactId>maven-dependency-plugin</artifactId>
+                <version>2.10</version>
+                <executions>
+                    <execution>
+                        <id>copy-dependencies</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>copy-dependencies</goal>
+                        </goals>
+                        <configuration>
+                            <excludeArtifactIds>ipfcst-common-data</excludeArtifactIds>
+                            <outputDirectory>../syjy/ipfcstV3/ipfcst-lib</outputDirectory>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <!--////////////////////////////////////////////////////小包配置结束//////////////////////////////////////-->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-resources-plugin</artifactId>
                 <version>3.1.0</version>
                 <configuration>
-                    <filesets>
-                        <fileset>
-                            <!-- 前端资源目录,即:存放前端包目录-->
-                            <directory>src/main/resources/static</directory>
-                        </fileset>
-                        <fileset>
-                            <!-- Vue项目打包自动生成的dist目录 -->
-                            <directory>${basedir}/dist</directory>
-                        </fileset>
-                    </filesets>
+                    <nonFilteredFileExtensions>
+                        <nonFilteredFileExtension>woff</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>ttf</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>woff2</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>eot</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>swf</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>ico</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>png</nonFilteredFileExtension>
+                    </nonFilteredFileExtensions>
+                    <includeEmptyDirs>true</includeEmptyDirs>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>copy config</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>copy-resources</goal>
+                        </goals>
+                        <configuration>
+                            <resources>
+                                <resource>
+                                    <directory>src/main/resources</directory>
+                                    <includes>
+                                        <include>application.yml</include>
+                                        <include>vms/**</include>
+                                    </includes>
+                                </resource>
+                            </resources>
+                            <outputDirectory>../syjy/ipfcstV3/produce/upload/${project.version}</outputDirectory>
+                        </configuration>
+                    </execution>
+                    <execution>
+                        <id>copy-start-upload.sh</id>
+                        <!-- here the phase you need -->
+                        <phase>compile</phase>
+                        <goals>
+                            <goal>copy-resources</goal>
+                        </goals>
+                        <configuration>
+                            <outputDirectory>../syjy/ipfcstV3/bin</outputDirectory>
+                            <resources>
+                                <resource>
+                                    <directory>target/classes</directory>
+                                    <includes>
+                                        <include>start-upload.sh</include>
+                                    </includes>
+                                </resource>
+                            </resources>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-jar-plugin</artifactId>
+                <version>2.6</version>
+                <configuration>
+                    <excludes>
+                        <exclude>application.yml</exclude>
+                        <exclude>logback-upload.xml</exclude>
+                    </excludes>
+                    <!--////////////////////////////////////////////////////小包配置开始//////////////////////////////////////-->
+                    <archive>
+                        <manifest>
+                            <addClasspath>true</addClasspath>
+                            <classpathPrefix>/home/syjy/ipfcstV3/ipfcst-lib/</classpathPrefix>
+                            <mainClass>com.jiayue.ipfcst.upload.UploadApplication</mainClass>
+                        </manifest>
+                        <!-- 用maven在MANIFEST.MF资料中的Class-Path中增加当前目录(.)  -->
+                        <manifestEntries>
+                            <Class-Path>/home/syjy/ipfcstV3/ipfcst-lib</Class-Path>
+                        </manifestEntries>
+                    </archive>
+                    <!--////////////////////////////////////////////////////小包配置结束//////////////////////////////////////-->
+                </configuration>
+            </plugin>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>2.1.7.RELEASE</version>
+                <configuration>
+                    <outputDirectory>../syjy/ipfcstV3/produce/upload/${project.version}</outputDirectory>
+                    <!--////////////////////////////////////////////////////小包配置开始//////////////////////////////////////-->
+                    <includes>
+                        <include>
+                            <groupId>nothing</groupId>
+                            <artifactId>nothing</artifactId>
+                        </include>
+                        <include>
+                            <groupId>com.jiayue.ipfcst</groupId>
+                            <artifactId>ipfcst-common-data</artifactId>
+                        </include>
+                    </includes>
+                    <!--////////////////////////////////////////////////////小包配置结束//////////////////////////////////////-->
+                    <!--控制是否启用支持Linux下service方式运行-->
+                    <executable>false</executable>
+                </configuration>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>build-info</goal>
+                            <goal>repackage</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <artifactId>maven-assembly-plugin</artifactId>
+                <version>2.2.1</version>
+                <configuration>
+                    <!-- 定义压缩包存放位置 -->
+                    <outputDirectory>../syjy/ipfcstV3/produce/upload/${project.version}</outputDirectory>
+                    <!-- 定义压缩包文件名 -->
+                    <finalName>${project.artifactId}-${project.version}</finalName>
+                    <appendAssemblyId>false</appendAssemblyId>
+                    <descriptors>
+                        <descriptor>src/main/resources/assembly_base.xml</descriptor>
+                    </descriptors>
                 </configuration>
+                <executions>
+                    <execution>
+                        <id>make-assembly</id>
+                        <phase>package</phase>
+                        <goals>
+                            <goal>single</goal>
+                        </goals>
+                    </execution>
+                </executions>
             </plugin>
         </plugins>
     </build>

+ 1 - 1
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/util/IEC102Uitl.java → ipfcst-upload/src/main/java/com/jiayue/ipfcst/upload/util/IEC102Uitl.java

@@ -1,4 +1,4 @@
-package com.jiayue.ipfcst.fileupload.util;
+package com.jiayue.ipfcst.upload.util;
 
 import java.util.ArrayList;
 import java.util.List;

+ 11 - 1
ipfcst-upload/src/main/resources/application.yml

@@ -1,9 +1,19 @@
 server:
   port: 9002
-
+spring:
+  main:
+    web-application-type: none
 logging:
   config: classpath:logback-upload.xml
 
+fileupload:
+  # 文件上报动态日志配置
+  log:
+    level: info
+    totalSizeCap: 20480MB
+    maxFileSize: 50MB
+    maxHistory: 90
+
 mengxi:
   uploadpath:
     E1: /WIND_DQ/

+ 18 - 0
ipfcst-upload/src/main/resources/assembly_base.xml

@@ -0,0 +1,18 @@
+<assembly>
+  <id>bin</id>
+  <formats>
+    <!-- zip,tar,tar.gz,tar.bz2,jar,dir,war -->
+    <format>zip</format>
+  </formats>
+  <includeBaseDirectory>false</includeBaseDirectory>
+  <fileSets>
+    <fileSet>
+      <directory>../syjy/ipfcstV3/produce/upload/${project.version}</directory>
+      <includes>
+        <include>*.jar</include>
+        <include>application.yml</include>
+      </includes>
+      <outputDirectory>/</outputDirectory>
+    </fileSet>
+  </fileSets>
+</assembly>

+ 32 - 0
ipfcst-upload/src/main/resources/start-upload.vm

@@ -0,0 +1,32 @@
+#!/bin/sh
+
+export basedir=/home/syjy/ipfcstV3
+export producedir=$basedir/produce
+
+export start_app_log=$basedir/logs/ipfcst_upload.log
+
+export version="${version}"
+
+export app_path=$producedir/upload/$version
+
+export JAVA_HOME=/home/syjy/ipfcstV3/jdk/jdk1.8.0_261
+export JRE_HOME=$JAVA_HOME/jre
+export CLASSPATH=.:$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATH
+export PATH=$JAVA_HOME/bin:$JRE_HOME/bin:$PATH
+
+export LANG="zh_CN.UTF-8"
+export LC_ALL="zh_CN.UTF-8"
+
+#set($tempvar = '$!')
+
+cd $app_path
+echo "Starting upload"
+if test -x $app_path/ipfcst-upload.jar
+  then
+	java -jar $app_path/ipfcst-upload.jar >$start_app_log &
+	echo "upload started, PID is ${tempvar}" | sed -e "s/\b\(.\)/\u\1/g"
+  else
+	echo "Couldn't find upload server($app_path/ipfcst-upload.jar)"
+fi
+
+exit 0

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä