xusl 3 лет назад
Родитель
Сommit
f6826f3daa

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

@@ -20,6 +20,7 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
 import java.util.*;
 import java.util.stream.Collectors;
 
@@ -59,11 +60,11 @@ public class Base102Service {
     }
     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);
+    log.info("UploadNums操作文件:" + tempFileName);
+    keys[0] = tempFileName.substring(0, tempFileName.indexOf("@"));
+    tempFileName = tempFileName.substring(tempFileName.indexOf("@") + 1);
+    keys[1] = tempFileName.substring(0, tempFileName.indexOf("@"));
+    keys[2] = tempFileName.substring(tempFileName.indexOf("@") + 1);
 
     // 找到文件日志记录
     //今日凌晨
@@ -107,7 +108,7 @@ public class Base102Service {
       // 上报成功保存数据库,更新上报表,上报明细
 //      uploadFileLogRepository.updateFileUploadCount(FileStatusEnum.E2, fileMutableInteger.getValue(), uploadObject.getId(), keys[2]);
       uploadFileLog.setFileStatusEnum(FileStatusEnum.E2);
-      uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter()+1);
+      uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter() + 1);
       uploadFileLogRepository.save(uploadFileLog);
       uploadFileLogDetailRepository.save(uploadFileLogDetail);
       // 将文件移动到成功目录
@@ -117,7 +118,7 @@ public class Base102Service {
       try {
         FileUtil.move(srcPath, targetPath);
       } catch (Exception e) {
-        log.error("上报成功移动文件失败",e);
+        log.error("上报成功移动文件失败", e);
       }
       // 清理缓存
       FileConstant.uploadCountMap.remove(fileNameKey);
@@ -139,23 +140,22 @@ public class Base102Service {
       uploadFileLogDetail.setFileStatusEnum(FileStatusEnum.E3);
       uploadFileLogDetail.setUploadFailureReason(faileReason);
       uploadFileLog.setFileStatusEnum(FileStatusEnum.E3);
-      uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter()+1);
+      uploadFileLog.setUploadCounter(uploadFileLog.getUploadCounter() + 1);
       uploadFileLogRepository.save(uploadFileLog);
       uploadFileLogDetailRepository.save(uploadFileLogDetail);
 
-      if (FileConstant.againUploadFileMap.get(fileNameKey)==null){
+      if (FileConstant.againUploadFileMap.get(fileNameKey) == null) {
         // 遇到失败,再给这个文件一次上报的机会
-        FileConstant.againUploadFileMap.put(fileNameKey,"");
-        log.info(fileNameKey+"上报结果失败,再报一次变量中存入");
-      }
-      else{
+        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 + keys[0] + File.separator + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd") + File.separator + keys[1];
         try {
           FileUtil.move(srcPath, targetPath);
         } catch (Exception e) {
-          log.error("将文件移动到失败目录",e);
+          log.error("将文件移动到失败目录", e);
         }
         FileConstant.readyUploadFileMap.remove(fileNameKey);
         FileConstant.fileShouldMomentMap.remove(fileNameKey);
@@ -180,9 +180,9 @@ public class Base102Service {
     InputStreamReader isr = null;
     String fileMessageHex = "";
     try {
-      isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
-      StringBuffer sb = new StringBuffer("");
-      int len1 = 0;
+      isr = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
+      StringBuilder sb = new StringBuilder();
+      int len1;
       while ((len1 = isr.read()) != -1) {
         sb.append((char) len1);
       }
@@ -245,9 +245,9 @@ public class Base102Service {
         } 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("@"));
+          keys[1] = entry.getKey().substring(entry.getKey().indexOf("@", 1) + 1, entry.getKey().indexOf("@", 2));
+          keys[2] = entry.getKey().substring(entry.getKey().indexOf("@", 2) + 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 {

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

@@ -13,7 +13,7 @@ import java.util.concurrent.TimeUnit;
  * @version 3.0
  */
 public class ServerFor102InitChannel extends ChannelInitializer<SocketChannel> {
-  private int readerIdleTime;
+  private final int readerIdleTime;
 
   ServerFor102InitChannel(Integer readerIdleTime) {
     this.readerIdleTime = readerIdleTime;

+ 43 - 44
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102StandardService.java

@@ -3,7 +3,6 @@ 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;
@@ -37,13 +36,13 @@ public class ServerFor102StandardService extends Base102Service {
     String sendCtrlChinese = "";
     String receiveCtrlChinese = "";
 
-    if (FileConstant.validateMessage.get(uploadFileChannel.getId()+"")!=null){
+    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);
-        channelCloseConnect(ctx,uploadObject,uploadFileChannel);
+      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);
+        channelCloseConnect(ctx, uploadObject, uploadFileChannel);
         return "";
       }
     }
@@ -52,13 +51,13 @@ public class ServerFor102StandardService extends Base102Service {
       // 获取控制域,根据功能码判断业务流
       String fc = rmArray[1].substring(1);
 
-      if (FileConstant.validateMessage.get(uploadFileChannel.getId()+"")!=null){
+      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);
+        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 "";
           }
         }
@@ -79,7 +78,7 @@ public class ServerFor102StandardService extends Base102Service {
       } 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("@"))))
+        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));
         // 上报文件名
@@ -88,17 +87,17 @@ public class ServerFor102StandardService extends Base102Service {
           // 不是第一次要文件了
           for (Map.Entry<String, FileMutableInteger> entry : filterMap.entrySet()) {
             fileNameKey = entry.getKey();
-            log.info(ctx.channel().remoteAddress()+" - "+"上传文件===>"+entry.getKey());
+            log.info(ctx.channel().remoteAddress() + " - " + "上传文件===>" + entry.getKey());
             break;
           }
         } else {
           // 从待上报的缓存中取一个文件放入次数变量中
-          Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap,log);
+          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());
+            log.info(ctx.channel().remoteAddress() + " - " + "找到文件===>" + entry.getKey());
             fileNameKey = entry.getKey();
             break;
           }
@@ -106,16 +105,16 @@ public class ServerFor102StandardService extends Base102Service {
         if ("".equals(fileNameKey)) {
           sendCtrlChinese = "没有找到上报文件";
           sendMessage = makeMessage10("09");
-          FileConstant.validateMessage.remove(uploadFileChannel.getId()+"");
+          FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
         } else {
           // 生成传输文件的68帧
           sendMessage = uploadFile68(fileNameKey, uploadObject, uploadFileChannel, log);
-          sendCtrlChinese = "通道:"+uploadFileChannel.getChannelName()+"上报:"+fileNameKey;
+          sendCtrlChinese = "通道:" + uploadFileChannel.getChannelName() + "上报:" + fileNameKey;
         }
       } else if ("B".equals(fc)) {
         receiveCtrlChinese = "召唤二级数据";
         // 获取此通道下的上报文件
-        Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap,log);
+        Map<String, UploadFileLog> readyUploadFileMap = super.filterFileByObjectNo(uploadObject.getObjectNo(), FileConstant.readyUploadFileMap, log);
 
         if (MapUtil.isNotEmpty(readyUploadFileMap)) {
           // 文件缓存中有上报文件
@@ -124,7 +123,7 @@ public class ServerFor102StandardService extends Base102Service {
           Validate102Dto dto = new Validate102Dto();
           dto.setMessageFirst("10");
           dto.setMessageReason("A");
-          FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
+          FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
         } else {
           // 没有文件
           sendMessage = makeMessage10("09");
@@ -132,12 +131,12 @@ public class ServerFor102StandardService extends Base102Service {
           Validate102Dto dto = new Validate102Dto();
           dto.setMessageFirst("10");
           dto.setMessageReason("B");
-          FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
+          FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
         }
       } else if ("C".equals(fc)) {
         receiveCtrlChinese = "下发数据通知";
       }
-      log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
+      log.info(ctx.channel().remoteAddress() + " - " + "接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
     } else {// 68开头报文
       // 判断传输原因
       String cot = rmArray[9];
@@ -150,9 +149,9 @@ public class ServerFor102StandardService extends Base102Service {
         String crc = IEC102Uitl.makeChecksum(tempStr.substring(8, 34));
         send68Array[17] = crc;
         sendCtrlChinese = "确认文件传输结束";
-        log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
+        log.info(ctx.channel().remoteAddress() + " - " + "接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
         // 文件状态成功
-        super.totalFileUploadNums(uploadObject,uploadFileChannel, "", log);
+        super.totalFileUploadNums(uploadObject, uploadFileChannel, "", log);
         sendMessage = ArrayUtil.join(send68Array, "");
       } else {
         // 文件状态失败
@@ -192,16 +191,16 @@ public class ServerFor102StandardService extends Base102Service {
           receiveCtrlChinese = "接收的内容程序没做判断";
           sendCtrlChinese = "不是正常的报文回复内容";
         }
-        log.info(ctx.channel().remoteAddress()+" - "+"接收报文:[" + receiveCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(receiveMessage));
-        super.totalFileUploadNums(uploadObject,uploadFileChannel, sendCtrlChinese, log);
+        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);
+      FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
     }
-    log.info(ctx.channel().remoteAddress()+" - "+"发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage));
+    log.info(ctx.channel().remoteAddress() + " - " + "发送报文:[" + sendCtrlChinese + "]" + IEC102Uitl.delimiterStringBySpace(sendMessage));
     return sendMessage;
   }
 
@@ -233,10 +232,10 @@ public class ServerFor102StandardService extends Base102Service {
     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);
+    tempKey[0] = tempFileName.substring(0, tempFileName.indexOf("@"));
+    tempFileName = tempFileName.substring(tempFileName.indexOf("@") + 1);
+    tempKey[1] = tempFileName.substring(0, tempFileName.indexOf("@"));
+    tempKey[2] = tempFileName.substring(tempFileName.indexOf("@") + 1);
 
     // 生成文件名及内容
     String fileName = tempKey[2];
@@ -273,7 +272,7 @@ public class ServerFor102StandardService extends Base102Service {
       Validate102Dto dto = new Validate102Dto();
       dto.setMessageFirst("68");
       dto.setMessageReason("0A");
-      FileConstant.validateMessage.put(uploadFileChannel.getId()+"",dto);
+      FileConstant.validateMessage.put(uploadFileChannel.getId() + "", dto);
 
     } else {
       // 将剩余的文件内容报文存入缓存中
@@ -283,11 +282,11 @@ public class ServerFor102StandardService extends Base102Service {
 //      Validate102Dto dto = new Validate102Dto();
 //      dto.setMessageFirst("10");
 //      dto.setMessageReason("A");
-      FileConstant.validateMessage.remove(uploadFileChannel.getId()+"");
+      FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
     }
     // 生成类型标识
 //    List<UploadFileCode> uploadFileCodeList = uploadFileCodeService.get();
-    Map<String,Integer> codeMap = super.getFileCode();
+    Map<String, Integer> codeMap = super.getFileCode();
     String typeCode = Integer.toHexString(codeMap.get(tempKey[1]));
 
     returnMessage[4] = ctrl;
@@ -297,7 +296,7 @@ public class ServerFor102StandardService extends Base102Service {
     returnMessage[14] = fileContentByte;
 
     // 获取从[控制域]到[校验和]之前的报文
-    StringBuffer tempSB = new StringBuffer("");
+    StringBuffer tempSB = new StringBuffer();
     for (int i = 4; i <= 14; i++) {
       tempSB.append(returnMessage[i]);
     }
@@ -314,26 +313,26 @@ public class ServerFor102StandardService extends Base102Service {
     return sendMessage.toUpperCase();
   }
 
-  public void channelCloseConnect(ChannelHandlerContext ctx, UploadObject uploadObject, UploadFileChannel uploadFileChannel){
+  public void channelCloseConnect(ChannelHandlerContext ctx, UploadObject uploadObject, UploadFileChannel uploadFileChannel) {
     // 传输帧类型不对,断开通道重启
     Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
+    while (countMap.hasNext()) {
       Map.Entry<String, FileMutableInteger> entry = countMap.next();
       String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
+      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();
+    while (contentMap.hasNext()) {
+      Map.Entry<String, String> entry = contentMap.next();
       String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
+      if (key.contains(uploadObject.getObjectNo() + "@")) {
         contentMap.remove();
       }
     }
-    FileConstant.validateMessage.remove(uploadFileChannel.getId()+"");
+    FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
     ctx.close();
   }
 }

+ 47 - 55
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/IEC102/ServerFor102TransitHandler.java

@@ -3,7 +3,6 @@ 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.ChannelDisconLog;
-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;
@@ -31,6 +30,7 @@ import java.util.stream.Collectors;
  * @version 3.0
  */
 public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
+  private final int readerIdleTime;
   @Autowired
   UploadFileChannelService uploadFileChannelService = SpringContextHolder.getApplicationContext().getBean(UploadFileChannelService.class);
   @Autowired
@@ -43,19 +43,14 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
   ChannelDisconLogService channelDisconLogService = SpringContextHolder.getApplicationContext().getBean(ChannelDisconLogService.class);
   @Autowired
   AppenderFactory appenderFactory = SpringContextHolder.getApplicationContext().getBean(AppenderFactory.class);
-
-  private int readerIdleTime;
+  private UploadFileChannel uploadFileChannel = null;
+  private UploadObject uploadObject = null;
+  private Logger uploadLogger = null;
 
   ServerFor102TransitHandler(Integer readerIdleTime) {
     this.readerIdleTime = readerIdleTime;
   }
 
-  private UploadFileChannel uploadFileChannel = null;
-
-  private UploadObject uploadObject = null;
-
-  private Logger uploadLogger = null;
-
   /**
    * 客户端连接会触发
    */
@@ -70,29 +65,27 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
     uploadFileChannel = uploadFileChannels.get(0);
     List<UploadObject> uploadObjectList = uploadObjectService.get();
     uploadObject = uploadObjectList.stream().filter(s -> s.getId().equals(uploadFileChannel.getUploadObjectId())).collect(Collectors.toList()).get(0);
-    uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(),uploadObject.getObjectNo());
-    if (FileConstant.channelIpPortMap.get(remoteIP)!=null){
-      uploadLogger.info(remoteIP+":"+ FileConstant.channelIpPortMap.get(remoteIP) + "已在交互,新连接"+remoteIP+":"+insocket.getPort()+"不能再次连接");
+    uploadLogger = appenderFactory.getLogger(uploadObject.getUploadObjectName(), uploadObject.getUploadProtocolEnum().getMessage(), uploadObject.getObjectNo());
+    if (FileConstant.channelIpPortMap.get(remoteIP) != null) {
+      uploadLogger.info(remoteIP + ":" + FileConstant.channelIpPortMap.get(remoteIP) + "已在交互,新连接" + remoteIP + ":" + insocket.getPort() + "不能再次连接");
       ctx.close();
-    }
-    else{
+    } else {
       uploadLogger.info(ctx.channel().remoteAddress() + "接入通道");
       // 设置通道状态正常
       FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
       FileConstant.channelIpPortMap.put(remoteIP, insocket.getPort());
       List<ChannelDisconLog> channelDisconLogList = channelDisconLogService.get(String.valueOf(uploadFileChannel.getId()));
-      if (channelDisconLogList.size()>0){
+      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)+"秒");
+        long durationL = reconnectTime - channelDisconLog.getDisconnectTime();
+        if (durationL / 1000 >= 60) {
+          channelDisconLog.setDuration(durationL / (1000 * 60) + "分");
+        } else {
+          channelDisconLog.setDuration(durationL / 1000 + "秒");
         }
         channelDisconLogService.save(channelDisconLog);
       }
@@ -107,9 +100,9 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
     // 设置通道状态正常
     FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
     // 返回的报文
-    String receiveMessage = "";
+    String receiveMessage;
     // 标准102服务端
-    receiveMessage = serverFor102StandardService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, uploadLogger,ctx);
+    receiveMessage = serverFor102StandardService.handlerMessage(msg.toString(), uploadObject, uploadFileChannel, uploadLogger, ctx);
 
     ctx.channel().writeAndFlush(receiveMessage);
   }
@@ -119,21 +112,21 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
    */
   @Override
   public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
-    uploadLogger.error(ctx.channel().remoteAddress() +"102上报异常", cause);
+    uploadLogger.error(ctx.channel().remoteAddress() + "102上报异常", cause);
     Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
+    while (countMap.hasNext()) {
       Map.Entry<String, FileMutableInteger> entry = countMap.next();
       String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
+      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();
+    while (contentMap.hasNext()) {
+      Map.Entry<String, String> entry = contentMap.next();
       String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
+      if (key.contains(uploadObject.getObjectNo() + "@")) {
         contentMap.remove();
       }
     }
@@ -147,28 +140,27 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
   public void channelInactive(ChannelHandlerContext ctx) throws Exception {
     InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
     String remoteIP = insocket.getAddress().getHostAddress();
-    Integer remotePort = insocket.getPort();
-    if (FileConstant.channelIpPortMap.get(remoteIP)!=null){
-      if (FileConstant.channelIpPortMap.get(remoteIP).intValue() == remotePort.intValue()) {
+    int remotePort = insocket.getPort();
+    if (FileConstant.channelIpPortMap.get(remoteIP) != null) {
+      if (FileConstant.channelIpPortMap.get(remoteIP) == remotePort) {
         // 断开的连接是已经交互的连接
         uploadLogger.info(ctx.channel().remoteAddress() + "通道断开");
 
         try {
-          Process process = Runtime.getRuntime().exec("ping "+uploadFileChannel.getRemoteIp() + " -c 2");
+          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 = "";
+          StringBuilder returnMsg = new StringBuilder();
+          String line;
           while ((line = returnData.readLine()) != null) {
-            returnMsg += line;
+            returnMsg.append(line);
           }
 
-          if(returnMsg.indexOf("100% loss")!=-1){
-            uploadLogger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接不畅通.");
-          }
-          else{
-            uploadLogger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接畅通.");
+          if (returnMsg.indexOf("100% loss") != -1) {
+            uploadLogger.info("与 " + uploadFileChannel.getRemoteIp() + " 连接不畅通.");
+          } else {
+            uploadLogger.info("与 " + uploadFileChannel.getRemoteIp() + " 连接畅通.");
           }
 
           returnData.close();
@@ -178,22 +170,22 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
           process.destroy();
 
         } catch (IOException e) {
-          uploadLogger.error("ping对方ip执行失败",e);
+          uploadLogger.error("ping对方ip执行失败", e);
         }
 
         try {
-          String cmd = "netstat -anp | grep "+uploadFileChannel.getLocalPort();
+          String cmd = "netstat -anp | grep " + uploadFileChannel.getLocalPort();
           Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
           process.waitFor();
           InputStreamReader r = new InputStreamReader(process.getInputStream());
           LineNumberReader returnData = new LineNumberReader(r);
 
-          String returnMsg="";
-          String line = "";
+          StringBuilder returnMsg = new StringBuilder();
+          String line;
           while ((line = returnData.readLine()) != null) {
-            returnMsg += line;
+            returnMsg.append(line);
           }
-          uploadLogger.info("断开后监听本地端口"+uploadFileChannel.getLocalPort()+":"+returnMsg);
+          uploadLogger.info("断开后监听本地端口" + uploadFileChannel.getLocalPort() + ":" + returnMsg);
 
           returnData.close();
           r.close();
@@ -202,7 +194,7 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
           process.destroy();
 
         } catch (IOException e) {
-          uploadLogger.error("监听本地端口"+uploadFileChannel.getLocalPort()+"执行失败",e);
+          uploadLogger.error("监听本地端口" + uploadFileChannel.getLocalPort() + "执行失败", e);
         }
 
         // 设置通道状态不通
@@ -244,25 +236,25 @@ public class ServerFor102TransitHandler extends ChannelInboundHandlerAdapter {
     // 长时间没收到信息,服务端主动发送确认复位命令
 //    uploadLogger.info("发送报文:[{}秒没收到信息,从站主动发送确认复位]10 00 FF FF FE 16",readerIdleTime);
 //    ctx.channel().writeAndFlush("1000FFFFFE16");
-    uploadLogger.info(ctx.channel().remoteAddress() +"{}秒没收到信息,关闭通道",readerIdleTime);
+    uploadLogger.info(ctx.channel().remoteAddress() + "{}秒没收到信息,关闭通道", readerIdleTime);
     Iterator<Map.Entry<String, FileMutableInteger>> countMap = FileConstant.uploadCountMap.entrySet().iterator();
-    while (countMap.hasNext()){
+    while (countMap.hasNext()) {
       Map.Entry<String, FileMutableInteger> entry = countMap.next();
       String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
+      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();
+    while (contentMap.hasNext()) {
+      Map.Entry<String, String> entry = contentMap.next();
       String key = entry.getKey();
-      if (key.contains(uploadObject.getObjectNo() + "@")){
+      if (key.contains(uploadObject.getObjectNo() + "@")) {
         contentMap.remove();
       }
     }
-    FileConstant.validateMessage.remove(uploadFileChannel.getId()+"");
+    FileConstant.validateMessage.remove(uploadFileChannel.getId() + "");
     ctx.close();
   }
 }

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

@@ -18,15 +18,15 @@ import java.net.InetSocketAddress;
  */
 @Slf4j
 public class UploadFileNettyServer extends NettyParent {
-//  private Logger log;
-  private int readerIdleTime;
-  public ChannelFuture future = null;
+  //  private Logger log;
+  private final int readerIdleTime;
   private final EventLoopGroup bossGroup = new NioEventLoopGroup(1);
   private final EventLoopGroup workerGroup = new NioEventLoopGroup(1);
+  public ChannelFuture future = null;
   public String localPort = "";
-  InetSocketAddress socketAddress = null;
+  InetSocketAddress socketAddress;
 
-  public UploadFileNettyServer(InetSocketAddress socketAddress,Integer readerIdleTime){
+  public UploadFileNettyServer(InetSocketAddress socketAddress, Integer readerIdleTime) {
     this.socketAddress = socketAddress;
     this.readerIdleTime = readerIdleTime;
   }

+ 6 - 4
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/config/FileUploadConfig.java

@@ -35,6 +35,7 @@ public class FileUploadConfig {
   SysParameterService sysParameterService;
   @Autowired
   UploadFileLogRepository uploadFileLogRepository;
+
   /**
    * 开启102s服务端
    */
@@ -51,8 +52,8 @@ public class FileUploadConfig {
     // 查询文件日志数据库,将未上报成功的查询出来
     Specification<UploadFileLog> specification = this.getQuerySpecification();
     List<UploadFileLog> uploadFileLogList = uploadFileLogRepository.findAll(specification);
-    for (UploadFileLog uploadFileLog:uploadFileLogList){
-      String readyFileKey = uploadFileLog.getUploadObjectNo()+"@"+uploadFileLog.getFileTypeEnum().toString()+"@"+uploadFileLog.getFileName();
+    for (UploadFileLog uploadFileLog : uploadFileLogList) {
+      String readyFileKey = uploadFileLog.getUploadObjectNo() + "@" + uploadFileLog.getFileTypeEnum().toString() + "@" + uploadFileLog.getFileName();
       FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
       FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
     }
@@ -102,13 +103,14 @@ public class FileUploadConfig {
 
   /**
    * 封装文件日志查询条件
+   *
    * @return
    */
   private Specification<UploadFileLog> getQuerySpecification() {
     return (Specification<UploadFileLog>) (root, criteriaQuery, cb) -> {
-      Long startTime = DateMomentUtil.getDayStartTime(new Date().getTime());
+      long startTime = DateMomentUtil.getDayStartTime(new Date().getTime());
       // 结束时间(开始加24小时再减去1秒)
-      Long endTime = startTime + 1000 *60 * 60 *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"));

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

@@ -40,15 +40,15 @@ public class UploadFileLogController {
   @GetMapping("getFileLog/{uploadObjectId}/{createTime}/{fileType}/{fileStatus}/{stationCode}")
   public ResponseVO get(@PathVariable("uploadObjectId") Integer uploadObjectId, @PathVariable("createTime") String createTime,
                         @PathVariable("fileType") String fileType, @PathVariable("fileStatus") String fileStatus, @PathVariable("stationCode") String stationCode) {
-    List<UploadFileLog> list = uploadFileLogService.queryFileLog(uploadObjectId, createTime, fileType, fileStatus,stationCode);
+    List<UploadFileLog> list = uploadFileLogService.queryFileLog(uploadObjectId, createTime, fileType, fileStatus, stationCode);
     return ResponseVO.success(list);
   }
 
   @GetMapping("/getFileStatusEnum")
   public ResponseVO getFileStatusEnum() {
-    List list = new ArrayList<>();
+    List<Map> list = new ArrayList<>();
     for (FileStatusEnum fileStatusEnum : FileStatusEnum.values()) {
-      Map map = new HashMap();
+      Map<String, String> map = new HashMap<>();
       map.put("name", fileStatusEnum.name());
       map.put("message", fileStatusEnum.getMessage());
       list.add(map);
@@ -58,9 +58,9 @@ public class UploadFileLogController {
 
   @GetMapping("/getUploadProtocolEnum")
   public ResponseVO getUploadProtocolEnum() {
-    List list = new ArrayList<>();
+    List<Map> list = new ArrayList<>();
     for (UploadProtocolEnum uploadProtocolEnum : UploadProtocolEnum.values()) {
-      Map map = new HashMap();
+      Map<String, String> map = new HashMap<>();
       map.put("name", uploadProtocolEnum.name());
       map.put("message", uploadProtocolEnum.getMessage());
       list.add(map);
@@ -70,9 +70,9 @@ public class UploadFileLogController {
 
   @GetMapping("/getFileTypeEnum")
   public ResponseVO getFileTypeEnum() {
-    List list = new ArrayList<>();
+    List<Map> list = new ArrayList<>();
     for (FileTypeEnum fileTypeEnum : FileTypeEnum.values()) {
-      Map map = new HashMap();
+      Map<String, String> map = new HashMap<>();
       map.put("name", fileTypeEnum.name());
       map.put("message", fileTypeEnum.getMessage());
       list.add(map);
@@ -84,10 +84,10 @@ public class UploadFileLogController {
   public ResponseVO uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("uploadObject") String id, @RequestParam("FileTypeEnum") String fileType) {
     Integer objectId = Integer.parseInt(id);
 
-    Boolean b = uploadFileLogService.uploadFile(objectId, fileType, file);
-    if (b){
+    boolean b = uploadFileLogService.uploadFile(objectId, fileType, file);
+    if (b) {
       return ResponseVO.success("上传成功!");
-    }else {
+    } else {
       return ResponseVO.fail("上传失败!");
     }
 
@@ -95,13 +95,13 @@ public class UploadFileLogController {
   }
 
   @DeleteMapping("/{id}/{fileCreateDate}")
-  public ResponseVO deleteById(@PathVariable("id") Integer id,@PathVariable("fileCreateDate") String fileCreateDate){
-    uploadFileLogService.deleteById(id,fileCreateDate);
+  public ResponseVO deleteById(@PathVariable("id") Integer id, @PathVariable("fileCreateDate") String fileCreateDate) {
+    uploadFileLogService.deleteById(id, fileCreateDate);
     return ResponseVO.success(1);
   }
 
   @PostMapping("/cleanCache")
-  public ResponseVO cleanCache(@RequestBody UploadFileLog uploadFileLog){
+  public ResponseVO cleanCache(@RequestBody UploadFileLog uploadFileLog) {
     uploadFileLogService.cleanCache(uploadFileLog);
     return ResponseVO.success(1);
   }
@@ -109,11 +109,12 @@ public class UploadFileLogController {
 
   /**
    * 文件补报
+   *
    * @param uploadFileLog
    * @return
    */
   @PostMapping("/report")
-  public ResponseVO report(@RequestBody UploadFileLog uploadFileLog){
+  public ResponseVO report(@RequestBody UploadFileLog uploadFileLog) {
     uploadFileLogService.report(uploadFileLog);
     return ResponseVO.success(1);
   }

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

@@ -2,10 +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.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;
 import org.springframework.web.bind.annotation.RestController;
 
@@ -25,12 +23,13 @@ import java.util.Map;
 public class UploadFileOpenInterfaceController {
   /**
    * 查看上报缓存中的文件
+   *
    * @return
    */
   @RequestMapping(value = "/getFileCache")
   public ResponseVO getFileCache() {
-    List list = new ArrayList<>();
-    for(Map.Entry<String, UploadFileLog> vo : FileConstant.readyUploadFileMap.entrySet()){
+    List<UploadFileLog> list = new ArrayList<>();
+    for (Map.Entry<String, UploadFileLog> vo : FileConstant.readyUploadFileMap.entrySet()) {
       list.add(vo.getValue());
     }
     return ResponseVO.success(list);
@@ -38,12 +37,13 @@ public class UploadFileOpenInterfaceController {
 
   /**
    * 获取上报对象状态
+   *
    * @return
    */
   @RequestMapping(value = "/getUploadObjectStatus")
   public ResponseVO getUploadObjectStatus() {
     log.info("获取上报对象状态。。。。。。。");
-    List list = new ArrayList<>();
+    List<Map<String, String>> list = new ArrayList<>();
     list.add(FileConstant.channelStatusMap);
     return ResponseVO.success(list);
   }

+ 18 - 15
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/controller/UploadObjectController.java

@@ -25,13 +25,14 @@ public class UploadObjectController {
   @Autowired
   private final UploadObjectService uploadObjectService;
   private final UploadFileChannelService uploadFileChannelService;
+  @Autowired
+  UploadObjectRepository uploadObjectRepository;
 
   public UploadObjectController(UploadObjectService uploadObjectService, UploadFileChannelService uploadFileChannelService) {
     this.uploadObjectService = uploadObjectService;
     this.uploadFileChannelService = uploadFileChannelService;
   }
-  @Autowired
-  UploadObjectRepository uploadObjectRepository;
+
   /**
    * 获取通道对象
    *
@@ -39,7 +40,6 @@ public class UploadObjectController {
    */
   @GetMapping()
   public ResponseVO get() {
-    List list = new ArrayList();
     List<UploadObject> uploadObjectList = uploadObjectService.get();
     return ResponseVO.success(uploadObjectList);
   }
@@ -106,10 +106,10 @@ public class UploadObjectController {
    */
   @GetMapping("getFileType")
   public ResponseVO getFileType() {
-    List list = new ArrayList();
+    List<Map> list = new ArrayList<>();
     try {
       for (FileTypeEnum e : FileTypeEnum.values()) {
-        Map map = new HashMap();
+        Map<String, String> map = new HashMap<>();
         map.put("label", e.getMessage());
         map.put("key", e.name());
         map.put("value", e.name());
@@ -125,12 +125,14 @@ public class UploadObjectController {
 
   /**
    * 根据上报id来查询
+   *
    * @param uploadObjectId
    * @return UploadObject 上报对象
    */
+  @SuppressWarnings("OptionalGetWithoutIsPresent")
   @GetMapping("getByuploadObjectId/{uploadObjectId}")
-  public ResponseVO getFileTypeByupId(@PathVariable("uploadObjectId") Integer uploadObjectId){
-    List list = new ArrayList();
+  public ResponseVO getFileTypeByupId(@PathVariable("uploadObjectId") Integer uploadObjectId) {
+    List<UploadObject> list = new ArrayList<>();
     UploadObject uploadObject = uploadObjectRepository.findById(uploadObjectId).get();
     list.add(uploadObject);
     return ResponseVO.success(list);
@@ -138,12 +140,13 @@ public class UploadObjectController {
 
   /**
    * 根据场站编号查询上报对象
+   *
    * @param stationCode
    * @return
    */
   @GetMapping("getByStationCode/{stationCode}")
-  public ResponseVO getByStationCode(@PathVariable("stationCode") String stationCode){
-    List<UploadObject> list = new ArrayList();
+  public ResponseVO getByStationCode(@PathVariable("stationCode") String stationCode) {
+    List<UploadObject> list;
     list = uploadObjectRepository.findByStationCode(stationCode);
     return ResponseVO.success(list);
   }
@@ -152,7 +155,7 @@ public class UploadObjectController {
    * 获取对应省份的上报文件类型
    */
   @GetMapping("getFileTypeByProvince")
-  public ResponseVO getFileTypeByProvince(){
+  public ResponseVO getFileTypeByProvince() {
     Map<String, String> uploadFileType = uploadObjectService.getUploadFileType();
     List<Map<String, String>> list = new ArrayList<>();
     for (String key : uploadFileType.keySet()) {
@@ -172,7 +175,7 @@ public class UploadObjectController {
    * 获取所有FTPSFTP通道 whc
    */
   @GetMapping("getFtpSftpChannel")
-  public ResponseVO getAllFtpSftp(){
+  public ResponseVO getAllFtpSftp() {
     //获取所有上报对象
     List<UploadObject> uploadObjectList = uploadObjectService.get();
     List<UploadFileChannel> uploadFileChannelList = new ArrayList<>();
@@ -182,10 +185,10 @@ public class UploadObjectController {
       // 获取通道信息
       List<UploadFileChannel> uploadFileChannels = uploadFileChannelService.get();
       //获取FTP/SFTP通道
-      for(int i =0 ; i<uploadObjectList.size();i++){
-        for(int j = 0 ; j<uploadFileChannels.size() ; j++){
-          if(uploadObjectList.get(i).getId().equals(uploadFileChannels.get(j).getUploadObjectId())){
-            uploadFileChannelList.add(uploadFileChannels.get(j));
+      for (UploadObject uploadObject : uploadObjectList) {
+        for (UploadFileChannel uploadFileChannel : uploadFileChannels) {
+          if (uploadObject.getId().equals(uploadFileChannel.getUploadObjectId())) {
+            uploadFileChannelList.add(uploadFileChannel);
           }
         }
       }

+ 19 - 37
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/BaseUploadFileService.java

@@ -1,7 +1,6 @@
 package com.jiayue.ipfcst.fileupload.service;
 
 import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
-import com.jiayue.ipfcst.common.data.constant.enums.AlarmTypeEnum;
 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;
@@ -23,6 +22,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
 import java.util.Date;
 import java.util.List;
 import java.util.UUID;
@@ -53,16 +53,13 @@ public abstract class BaseUploadFileService extends BaseService {
    * @return
    */
   protected int getTranSysParameter(String key, String defaultValue, String stationCode) {
-    int returnValue = 0;
+    int returnValue;
     try {
       String value = super.getSysParameter(key, defaultValue, stationCode);
       returnValue = Integer.parseInt(value);
     } catch (RuntimeException e) {
       String errorInfo = "参数表" + key + "获取失败";
       log.error(errorInfo, e);
-      String name = "参数表" + key + "获取失败";
-      String describe = "参数表" + key + "获取失败";
-      String solution = "使用默认值" + defaultValue;
       returnValue = Integer.parseInt(defaultValue);
     }
     return returnValue;
@@ -78,15 +75,11 @@ public abstract class BaseUploadFileService extends BaseService {
   protected boolean getFileName(String fileName, String fileType, String stationCode) {
     int cdqUpMin = getTranSysParameter("CDQ_UP_MIN", "0", stationCode);
     //今日凌晨
-    Long jt = DateTimeUtil.getMillisecondsSubDay() - (15 * 60 * 1000 + cdqUpMin * 1000 * 60);
+    long jt = DateTimeUtil.getMillisecondsSubDay() - (15 * 60 * 1000 + (long) cdqUpMin * 1000 * 60);
     //明日凌晨
-    Long mt = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24;
+    long mt = DateTimeUtil.getMillisecondsSubDay() + 1000 * 60 * 60 * 24;
     List<UploadFileLog> list = this.uploadFileLogRepository.findByFileNameAndFileTypeEnumAndCreateTimeBetweenAndStationCode(fileName, FileTypeEnum.valueOf(fileType), new Date(jt), new Date(mt), stationCode);
-    if (null != list && list.size() > 0) {
-      return false;
-    } else {
-      return true;
-    }
+    return null == list || list.size() <= 0;
   }
 
   /**
@@ -121,15 +114,15 @@ public abstract class BaseUploadFileService extends BaseService {
    * @param fileType
    * @param uploadFileEndTime
    */
-  protected void copyUploadFile(StringWriter writer, File file, String fileType, Long uploadFileEndTime, Date createTime,String stationCode) {
+  protected void copyUploadFile(StringWriter writer, File file, String fileType, Long uploadFileEndTime, Date createTime, String stationCode) {
     FileOutputStream os = null;
     try {
       os = new FileOutputStream(file);
       // 采用UTF-8字符集
-      os.write(writer.toString().getBytes("UTF-8"));
+      os.write(writer.toString().getBytes(StandardCharsets.UTF_8));
       os.flush();
       // 将文件复制到上报路径中
-      copyFileToUploadDir(file, fileType, uploadFileEndTime, createTime,stationCode);
+      copyFileToUploadDir(file, fileType, uploadFileEndTime, createTime, stationCode);
     } catch (IOException e) {
       throw new RuntimeException(e);
     } finally {
@@ -156,38 +149,32 @@ public abstract class BaseUploadFileService extends BaseService {
    * @param uploadFileEndTime 上报文件截止时间
    */
   @Transactional(propagation = Propagation.REQUIRED)
-  protected void copyFileToUploadDir(File file, String fileType, Long uploadFileEndTime, Date createTime,String stationCode) {
+  protected void copyFileToUploadDir(File file, String fileType, Long uploadFileEndTime, Date createTime, String stationCode) {
     String destFileDir = null;
 
     try {
       // 获取上报对象
       List<UploadObject> uploadObjectList = uploadObjectService.get();
-      if (uploadObjectList.isEmpty()) {
-        // 没有有效上报通道进行告警
-        String errorInfo = "文件生成没有上报对象可用";
-        String name = file.getName() + "生成失败";
-        String describe = FileTypeEnum.valueOf(fileType).getMessage();
-        String solution = "请配置相关上报对象";
-      } else {
+      if (!uploadObjectList.isEmpty()) {
         // 遍历上报对象生成对应的文件
         for (UploadObject uploadObject : uploadObjectList) {
-          if (uploadObject.getStationCode().equals(stationCode)){
+          if (uploadObject.getStationCode().equals(stationCode)) {
             List<UploadFileChannel> uploadFileChannelList = uploadFileChannelService.getByObjectId(uploadObject.getId());
             // 找出对象下是否有可用的通道
             List<UploadFileChannel> filterUploadFileChannelList = uploadFileChannelList.stream().filter(s -> "E1".equals(s.getChannelStatusEnum().toString())).collect(Collectors.toList());
-            if (filterUploadFileChannelList.size()>0){
+            if (filterUploadFileChannelList.size() > 0) {
               String[] uploadFileType = uploadObject.getUploadFileType().split(",");
-              for (int k = 0; k < uploadFileType.length; k++) {
-                if (uploadFileType[k].equals(fileType)) {
+              for (String s : uploadFileType) {
+                if (s.equals(fileType)) {
                   // 上报文件目录
-                  destFileDir = FileUtil.getFileUploadPath() + File.separator +"process" + File.separator + uploadObject.getObjectNo() + File.separator + fileType;
+                  destFileDir = FileUtil.getFileUploadPath() + File.separator + "process" + File.separator + uploadObject.getObjectNo() + File.separator + fileType;
                   File destDir = new File(destFileDir);
                   if (!destDir.exists()) {// 如果目录不存在则创建uploadFileEndTime目录
                     boolean b = destDir.mkdirs();
                     if (!b) // 如果创建失败则抛出异常
                       throw new RuntimeException(destFileDir + " 目录创建失败");
                   }
-                  if (!new File(destDir+File.separator+file.getName()).exists()){
+                  if (!new File(destDir + File.separator + file.getName()).exists()) {
                     FileUtils.copyFileToDirectory(file, destDir);
                     UploadFileLog uploadFileLog = new UploadFileLog();
                     uploadFileLog.setUploadObjectId(uploadObject.getId());
@@ -203,7 +190,7 @@ public abstract class BaseUploadFileService extends BaseService {
 
                     uploadFileLog = this.uploadFileLogRepository.save(uploadFileLog);
 
-                    if(createTime!=null){
+                    if (createTime != null) {
                       uploadFileLog.setCreateTime(createTime);
                       Date date = new Date();
                       String format = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
@@ -214,10 +201,9 @@ public abstract class BaseUploadFileService extends BaseService {
                     FileConstant.fileShouldMomentMap.put(readyFileKey, uploadFileLog.getId());
                     FileConstant.readyUploadFileMap.put(readyFileKey, uploadFileLog);
 
-                    log.debug("文件生成存入缓存:"+file.getName());
+                    log.debug("文件生成存入缓存:" + file.getName());
                     log.info("上报对象编号:" + uploadObject.getObjectNo() + ",生成文件" + file.getName() + "成功");
-                  }
-                  else{
+                  } else {
                     log.info("本地文件已经生成,上报对象编号:" + uploadObject.getObjectNo() + "," + file.getName() + "不再生成了");
                   }
                   break;
@@ -231,10 +217,6 @@ public abstract class BaseUploadFileService extends BaseService {
       // 文件复制失败进行告警
       String errorInfo = "复制文件[" + file.getName() + "]到上报目录[" + destFileDir + "]失败";
       log.error(errorInfo, e);
-      // 进行告警
-      String name = file.getName() + "生成失败";
-      String describe = FileTypeEnum.valueOf(fileType).getMessage();
-      String solution = "请查看日志异常信息";
     }
   }
 }

+ 104 - 108
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/E63UploadFileService.java

@@ -3,6 +3,7 @@ package com.jiayue.ipfcst.fileupload.service;
 import cn.hutool.core.util.StrUtil;
 import com.jiayue.ipfcst.common.core.exception.BusinessException;
 import com.jiayue.ipfcst.common.core.util.DateMomentUtil;
+import com.jiayue.ipfcst.common.data.abst.equipmentinfo.AbstractEquipmentInfo;
 import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
 import com.jiayue.ipfcst.common.data.entity.*;
 import com.jiayue.ipfcst.common.data.repository.*;
@@ -23,6 +24,7 @@ import org.springframework.stereotype.Service;
 import java.io.File;
 import java.io.StringWriter;
 import java.math.BigDecimal;
+import java.math.RoundingMode;
 import java.text.DecimalFormat;
 import java.util.*;
 import java.util.stream.Collectors;
@@ -37,7 +39,7 @@ import java.util.stream.Collectors;
 @Slf4j
 public class E63UploadFileService extends BaseUploadFileService {
 
-  private String vmsPath = FileUtil.getResourceBasePath() + "/vms/E63";
+  private final String vmsPath = FileUtil.getResourceBasePath() + "/vms/E63";
 
   private final VelocityEngine velocityEngine;
 
@@ -91,7 +93,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成短期预测上报文件。
    */
   public void generateDqFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -102,7 +104,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     for (ElectricField electricFieldInfo : electricFieldList) {
       String stationCode = electricFieldInfo.getStationCode();
       try {
-        Template template = null;
+        Template template;
         // 获取短期模板
         if (electricFieldInfo.getElectricFieldTypeEnum().equals("E1")) {
           template = this.velocityEngine.getTemplate(this.vmsPath + "/DQ.vm");
@@ -111,10 +113,10 @@ public class E63UploadFileService extends BaseUploadFileService {
         }
 
         if (template != null) {
-          VelocityContext velocityContext = null;
-          StringWriter writer = null;
-          String fileName = null;
-          File file = null;
+          VelocityContext velocityContext;
+          StringWriter writer;
+          String fileName;
+          File file;
 
           // 获取当前系统时间
           Date systemDate = new Date();
@@ -171,7 +173,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成短期可用预测上报文件。
    */
   public void generateDqUseFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -182,7 +184,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     for (ElectricField electricFieldInfo : electricFieldList) {
       String stationCode = electricFieldInfo.getStationCode();
       try {
-        Template template = null;
+        Template template;
         // 获取短期模板
         if (electricFieldInfo.getElectricFieldTypeEnum().equals("E1")) {
           template = this.velocityEngine.getTemplate(this.vmsPath + "/DQ_USE.vm");
@@ -244,7 +246,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成超短期预测上报文件。
    */
   public void generateCdqFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -255,7 +257,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     for (ElectricField electricFieldInfo : electricFieldList) {
       String stationCode = electricFieldInfo.getStationCode();
       try {
-        Template template = null;
+        Template template;
         // 获取短期模板
         if (electricFieldInfo.getElectricFieldTypeEnum().equals("E1")) {
           template = this.velocityEngine.getTemplate(this.vmsPath + "/CDQ.vm");
@@ -277,9 +279,9 @@ public class E63UploadFileService extends BaseUploadFileService {
           // 获取提前几分钟生成超短期
           int cdqUpMin = super.getTranSysParameter("CDQ_UP_MIN", "0", stationCode);
           // 开始时间
-          Long startTime = DateMomentUtil.getMomentTime(systemDate.getTime() + 15 * 60 * 1000 + cdqUpMin * 1000 * 60, 1, 15 * 60 * 1000L);
+          long startTime = DateMomentUtil.getMomentTime(systemDate.getTime() + 15 * 60 * 1000 + (long) cdqUpMin * 1000 * 60, 1, 15 * 60 * 1000L);
           // 结束时间
-          Long endTime = startTime + cdqPoint * 15 * 60 * 1000 - 1000;
+          long endTime = startTime + (long) cdqPoint * 15 * 60 * 1000 - 1000;
           // 生成上报文件名格式
           fileName = e63UploadFileRuleService.getFileNameRule(electricFieldInfo, "E2", startTime);
 
@@ -324,7 +326,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成超短期可用预测上报文件。
    */
   public void generateCdqUseFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -335,7 +337,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     for (ElectricField electricFieldInfo : electricFieldList) {
       String stationCode = electricFieldInfo.getStationCode();
       try {
-        Template template = null;
+        Template template;
         // 获取短期模板
         if (electricFieldInfo.getElectricFieldTypeEnum().equals("E1")) {
           template = this.velocityEngine.getTemplate(this.vmsPath + "/CDQ_USE.vm");
@@ -358,9 +360,9 @@ public class E63UploadFileService extends BaseUploadFileService {
           int cdqUpMin = super.getTranSysParameter("CDQ_UP_MIN", "0", stationCode);
 
           // 开始时间
-          Long startTime = DateMomentUtil.getMomentTime(systemDate.getTime() + 15 * 60 * 1000 + cdqUpMin * 1000 * 60, 1, 15 * 60 * 1000L);
+          long startTime = DateMomentUtil.getMomentTime(systemDate.getTime() + 15 * 60 * 1000 + (long) cdqUpMin * 1000 * 60, 1, 15 * 60 * 1000L);
           // 结束时间
-          Long endTime = startTime + cdqPoint * 15 * 60 * 1000 - 1000;
+          long endTime = startTime + (long) cdqPoint * 15 * 60 * 1000 - 1000;
 
           // 生成上报文件名格式
           fileName = e63UploadFileRuleService.getFileNameRule(electricFieldInfo, "E27", startTime);
@@ -406,7 +408,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成气象站或者测风塔上报文件
    */
   public void generateQxzOrCftFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -426,8 +428,7 @@ public class E63UploadFileService extends BaseUploadFileService {
         Long endTime = DateMomentUtil.getMomentTime(systemDate.getTime(), 1, 5 * 60 * 1000L);
         Long startTime = endTime - 4 * 60 * 1000;
         // 生成上报文件名格式
-        Template template = null;
-        VelocityContext velocityContext = new VelocityContext();
+        Template template;
         if (electricFieldInfo.getElectricFieldTypeEnum().toString().equals("E1")) {
           // 获取气象站模板
           template = this.velocityEngine.getTemplate(this.vmsPath + "/QXZ.vm");
@@ -451,11 +452,11 @@ public class E63UploadFileService extends BaseUploadFileService {
   /**
    * 生成气象站上报文件
    */
-  private void generateQxzFile(String fileName, Template template, ElectricField electricFieldInfo, Date date, Long startTime, Long endTime) throws Exception {
+  private void generateQxzFile(String fileName, Template template, ElectricField electricFieldInfo, Date date, Long startTime, Long endTime) {
     // 获取气象站信息
     List<WeatherStationInfo> weatherStationInfoList = weatherStationInfoRepository.findAll();
     // 将气象站信息过滤出上报
-    List<WeatherStationInfo> weatherStationInfos = weatherStationInfoList.stream().filter(w -> w.getReport() == true).collect(Collectors.toList());
+    List<WeatherStationInfo> weatherStationInfos = weatherStationInfoList.stream().filter(AbstractEquipmentInfo::getReport).collect(Collectors.toList());
     if (!weatherStationInfos.isEmpty()) {
       String qxzId = String.valueOf(weatherStationInfos.get(0).getId());
       Map<String, String> qxzMap = redisUtils.hgetall("qxz-" + electricFieldInfo.getStationCode() + "-" + qxzId);
@@ -487,14 +488,14 @@ public class E63UploadFileService extends BaseUploadFileService {
             ws = qxzMap.get("ws") == null ? qxzRandomCreate("ws") : new BigDecimal(qxzMap.get("ws"));
             wd = qxzMap.get("wd") == null ? qxzRandomCreate("wd") : new BigDecimal(qxzMap.get("wd"));
             isUseRedis = true;
-            log.info(electricFieldInfo.getStationCode() + "生成气象站数据从redis获取:" + qxzMap.toString());
+            log.info(electricFieldInfo.getStationCode() + "生成气象站数据从redis获取:" + qxzMap);
           }
         }
       }
 
       if (!isUseRedis) {
-        List<WeatherStationStatusData> weatherStationStatusDataList = weatherStationStatusDataRepository.findByStationCodeAndTimeBetweenAndEquipmentId(electricFieldInfo.getStationCode(),new Date(startTime), new Date(endTime), qxzId);
-        if (weatherStationStatusDataList.isEmpty()){
+        List<WeatherStationStatusData> weatherStationStatusDataList = weatherStationStatusDataRepository.findByStationCodeAndTimeBetweenAndEquipmentId(electricFieldInfo.getStationCode(), new Date(startTime), new Date(endTime), qxzId);
+        if (weatherStationStatusDataList.isEmpty()) {
           // 总辐射产生500-1000随机数
           globalR = qxzRandomCreate("globalR");
           // 直辐射产生400-500随机数
@@ -508,8 +509,7 @@ public class E63UploadFileService extends BaseUploadFileService {
           ws = qxzRandomCreate("ws");
           wd = qxzRandomCreate("wd");
           log.info(electricFieldInfo.getStationCode() + "生成气象站数据用随机数");
-        }
-        else{
+        } else {
           weatherStationStatusDataList.stream().sorted(Comparator.comparing(WeatherStationStatusData::getTime).reversed()).collect(Collectors.toList());
           WeatherStationStatusData weatherStationStatusData = weatherStationStatusDataList.get(0);
           globalR = weatherStationStatusData.getGlobalR();
@@ -563,11 +563,11 @@ public class E63UploadFileService extends BaseUploadFileService {
   /**
    * 生成测风塔上报文件
    */
-  private void generateCftFile(String fileName, Template template, ElectricField electricFieldInfo, Date date, Long startTime, Long endTime) throws Exception {
+  private void generateCftFile(String fileName, Template template, ElectricField electricFieldInfo, Date date, Long startTime, Long endTime) {
     // 获取测风塔信息
     List<WindTowerInfo> windTowerInfoList = windTowerInfoRepository.findAll();
     // 将测风塔信息过滤出上报的塔
-    List<WindTowerInfo> filterWindTowerInfoList = windTowerInfoList.stream().filter(w -> w.getReport() == true).collect(Collectors.toList());
+    List<WindTowerInfo> filterWindTowerInfoList = windTowerInfoList.stream().filter(AbstractEquipmentInfo::getReport).collect(Collectors.toList());
     if (!filterWindTowerInfoList.isEmpty()) {
       String cftId = String.valueOf(filterWindTowerInfoList.get(0).getId());
       Map<String, String> cftMap = redisUtils.hgetall("cft-" + electricFieldInfo.getStationCode() + "-" + cftId);
@@ -623,15 +623,15 @@ public class E63UploadFileService extends BaseUploadFileService {
             p8 = cftMap.get("paInst") == null ? cftRandomCreate("paInst") : new BigDecimal(cftMap.get("paInst"));
             rh8 = cftMap.get("rhInst") == null ? cftRandomCreate("rhInst") : new BigDecimal(cftMap.get("rhInst"));
             isUseRedis = true;
-            log.info(electricFieldInfo.getStationCode() + "生成测风塔数据从redis获取:" + cftMap.toString());
+            log.info(electricFieldInfo.getStationCode() + "生成测风塔数据从redis获取:" + cftMap);
           }
         }
       }
       if (!isUseRedis) {
-        List<WindTowerStatusData> windTowerStatusDataList = windTowerStatusDataRepository.findByStationCodeAndEquipmentIdAndTimeBetween(electricFieldInfo.getStationCode(),cftId, new Date(startTime), new Date(endTime));
-        if (windTowerStatusDataList.isEmpty()){
+        List<WindTowerStatusData> windTowerStatusDataList = windTowerStatusDataRepository.findByStationCodeAndEquipmentIdAndTimeBetween(electricFieldInfo.getStationCode(), cftId, new Date(startTime), new Date(endTime));
+        if (windTowerStatusDataList.isEmpty()) {
           // 没有测风塔数据用nwp数据补
-          Long nwpTime;
+          long nwpTime;
           try {
             nwpTime = DateMomentUtil.getMomentTime(endTime, 1, 15 * 60 * 1000L);
           } catch (Exception e) {
@@ -643,45 +643,45 @@ public class E63UploadFileService extends BaseUploadFileService {
           if (nwpList.size() > 0) {
             Nwp nwpData = nwpList.get(0);
             ws10 = nwpData.getWs10();
-            ws10 = ws10.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws10 = ws10.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd10 = nwpData.getWd10();
-            wd10 = wd10.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd10 = wd10.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             ws30 = nwpData.getWs30();
-            ws30 = ws30.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws30 = ws30.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd30 = nwpData.getWd30();
-            wd30 = wd30.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd30 = wd30.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             ws50 = nwpData.getWs50();
-            ws50 = ws50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws50 = ws50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd50 = nwpData.getWd50();
-            wd50 = wd50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
-            ws60 = ws50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
-            wd60 = wd50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd50 = wd50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
+            ws60 = ws50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
+            wd60 = wd50.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             ws70 = nwpData.getWs70();
-            ws70 = ws70.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws70 = ws70.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd70 = nwpData.getWd70();
-            wd70 = wd70.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd70 = wd70.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             ws80 = nwpData.getWs80();
-            ws80 = ws80.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws80 = ws80.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd80 = nwpData.getWd80();
-            wd80 = wd80.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd80 = wd80.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             ws90 = nwpData.getWs90();
-            ws90 = ws90.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws90 = ws90.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd90 = nwpData.getWd90();
-            wd90 = wd90.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd90 = wd90.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             ws100 = nwpData.getWs100();
-            ws100 = ws100.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            ws100 = ws100.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wd100 = nwpData.getWd100();
-            wd100 = wd100.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wd100 = wd100.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wsHubHeight = nwpData.getWs170();
-            wsHubHeight = wsHubHeight.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wsHubHeight = wsHubHeight.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             wdHubHeight = nwpData.getWd170();
-            wdHubHeight = wdHubHeight.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            wdHubHeight = wdHubHeight.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             rh8 = nwpData.getRh();
-            rh8 = rh8.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            rh8 = rh8.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             t8 = nwpData.getT();
-            t8 = t8.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            t8 = t8.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             p8 = nwpData.getPressure();
-            p8 = p8.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, BigDecimal.ROUND_HALF_UP);
+            p8 = p8.add(new BigDecimal(df.format(Math.random() * 1 + 0.01))).setScale(2, RoundingMode.HALF_UP);
             log.info(electricFieldInfo.getStationCode() + "生成测风塔数据用nwp+随机数");
           } else {
             // 10米风速产生1-5随机数
@@ -726,70 +726,69 @@ public class E63UploadFileService extends BaseUploadFileService {
             p8 = cftRandomCreate("paInst");
             log.info(electricFieldInfo.getStationCode() + "生成测风塔数据用随机数");
           }
-        }
-        else{
+        } else {
           windTowerStatusDataList.stream().sorted(Comparator.comparing(WindTowerStatusData::getTime).reversed()).collect(Collectors.toList());
           WindTowerStatusData windTowerStatusData = windTowerStatusDataList.get(0);
           // 10米风速
-          if (windTowerStatusData.getWsInst10()!=null)
+          if (windTowerStatusData.getWsInst10() != null)
             ws10 = windTowerStatusData.getWsInst10();
           // 10米风向
-          if (windTowerStatusData.getWdInst10()!=null)
+          if (windTowerStatusData.getWdInst10() != null)
             wd10 = windTowerStatusData.getWdInst10();
           // 30米风速
-          if (windTowerStatusData.getWdInst30()!=null)
+          if (windTowerStatusData.getWdInst30() != null)
             ws30 = windTowerStatusData.getWsInst30();
           // 30米风向
-          if (windTowerStatusData.getWdInst30()!=null)
+          if (windTowerStatusData.getWdInst30() != null)
             wd30 = windTowerStatusData.getWdInst30();
           // 50米风速
-          if (windTowerStatusData.getWdInst50()!=null)
+          if (windTowerStatusData.getWdInst50() != null)
             ws50 = windTowerStatusData.getWsInst50();
           // 50米风向
-          if (windTowerStatusData.getWdInst50()!=null)
+          if (windTowerStatusData.getWdInst50() != null)
             wd50 = windTowerStatusData.getWdInst50();
           // 60米风速
-          if (windTowerStatusData.getWdInst60()!=null)
+          if (windTowerStatusData.getWdInst60() != null)
             ws60 = windTowerStatusData.getWsInst60();
           // 60米风向
-          if (windTowerStatusData.getWdInst60()!=null)
+          if (windTowerStatusData.getWdInst60() != null)
             wd60 = windTowerStatusData.getWdInst60();
           // 70米风速
-          if (windTowerStatusData.getWdInst70()!=null)
+          if (windTowerStatusData.getWdInst70() != null)
             ws70 = windTowerStatusData.getWsInst70();
           // 70米风向
-          if (windTowerStatusData.getWdInst70()!=null)
+          if (windTowerStatusData.getWdInst70() != null)
             wd70 = windTowerStatusData.getWdInst70();
           // 80米风速
-          if (windTowerStatusData.getWdInst80()!=null)
+          if (windTowerStatusData.getWdInst80() != null)
             ws80 = windTowerStatusData.getWsInst80();
           // 80米风向
-          if (windTowerStatusData.getWdInst80()!=null)
+          if (windTowerStatusData.getWdInst80() != null)
             wd80 = windTowerStatusData.getWdInst80();
           // 90米风速
-          if (windTowerStatusData.getWdInst90()!=null)
+          if (windTowerStatusData.getWdInst90() != null)
             ws90 = windTowerStatusData.getWsInst90();
           // 90米风向
-          if (windTowerStatusData.getWdInst90()!=null)
+          if (windTowerStatusData.getWdInst90() != null)
             wd90 = windTowerStatusData.getWdInst90();
           // 100米风速
-          if (windTowerStatusData.getWdInst100()!=null)
+          if (windTowerStatusData.getWdInst100() != null)
             ws100 = windTowerStatusData.getWsInst100();
           // 100米风向
-          if (windTowerStatusData.getWdInst100()!=null)
+          if (windTowerStatusData.getWdInst100() != null)
             wd100 = windTowerStatusData.getWdInst100();
-          if (windTowerStatusData.getWsInstHubHeight()!=null)
+          if (windTowerStatusData.getWsInstHubHeight() != null)
             wsHubHeight = windTowerStatusData.getWsInstHubHeight();
-          if (windTowerStatusData.getWdInstHubHeight()!=null)
+          if (windTowerStatusData.getWdInstHubHeight() != null)
             wdHubHeight = windTowerStatusData.getWdInstHubHeight();
           // 湿度产生
-          if (windTowerStatusData.getRhInst()!=null)
+          if (windTowerStatusData.getRhInst() != null)
             rh8 = windTowerStatusData.getRhInst();
           // 温度产生
-          if (windTowerStatusData.getTInst()!=null)
+          if (windTowerStatusData.getTInst() != null)
             t8 = windTowerStatusData.getTInst();
           // 气压产生
-          if (windTowerStatusData.getPaInst()!=null)
+          if (windTowerStatusData.getPaInst() != null)
             p8 = windTowerStatusData.getPaInst();
           log.info(electricFieldInfo.getStationCode() + "生成测风塔数据用数据表");
         }
@@ -835,7 +834,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成逆变器上报文件。
    */
   public void generateNbqOrFjFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -854,7 +853,7 @@ public class E63UploadFileService extends BaseUploadFileService {
         Long endTime = DateMomentUtil.getMomentTime(systemDate.getTime(), 1, 5 * 60 * 1000L);
         Long startTime = endTime - 4 * 60 * 1000;
         // 生成上报文件名格式
-        Template template = null;
+        Template template;
 
         if (electricFieldInfo.getElectricFieldTypeEnum().toString().equals("E1")) {
           // 获取逆变器模板
@@ -883,7 +882,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     // 获取风机信息
     List<WindTurbineInfo> windTurbineInfoList = windTurbineInfoRepository.findAll();
     // 将测风塔信息过滤出上报的塔
-    List<WindTurbineInfo> filterWindTurbineInfoList = windTurbineInfoList.stream().filter(w -> w.getReport() == true).collect(Collectors.toList());
+    List<WindTurbineInfo> filterWindTurbineInfoList = windTurbineInfoList.stream().filter(AbstractEquipmentInfo::getReport).collect(Collectors.toList());
     if (filterWindTurbineInfoList.size() > 0) {
       List<Map<String, Object>> fanList = new ArrayList<>();
       for (WindTurbineInfo windTurbineInfo : filterWindTurbineInfoList) {
@@ -892,9 +891,9 @@ public class E63UploadFileService extends BaseUploadFileService {
         map.put("dtaStatus", windTurbineInfo);
         map.put("sample", windTurbineInfo.getSample() ? "1" : "0");
         map.put("modelNumber", windTurbineInfo.getModelNumber());
-        map.put("RatedCapacity", div(new BigDecimal(windTurbineInfo.getMaxPower()),new BigDecimal("1000"),2));
-        map.put("elName",electricFieldInfo.getName());
-        map.put("collectorCircuit",windTurbineInfo.getCollectorCircuit());
+        map.put("RatedCapacity", div(BigDecimal.valueOf(windTurbineInfo.getMaxPower()), new BigDecimal("1000"), 2));
+        map.put("elName", electricFieldInfo.getName());
+        map.put("collectorCircuit", windTurbineInfo.getCollectorCircuit());
 
         String fjId = String.valueOf(windTurbineInfo.getId());
         Map<String, String> fjMap = redisUtils.hgetall("fj-" + electricFieldInfo.getStationCode() + "-" + fjId);
@@ -975,9 +974,9 @@ public class E63UploadFileService extends BaseUploadFileService {
             }
           }
         }
-        if (!isUseRedis){
-          List<WindTurbineStatusData> windTurbineStatusDataList = windTurbineStatusDataRepository.findByTimeBetweenAndEquipmentId(new Date(startTime), new Date(endTime),fjId);
-          if (!windTurbineStatusDataList.isEmpty()){
+        if (!isUseRedis) {
+          List<WindTurbineStatusData> windTurbineStatusDataList = windTurbineStatusDataRepository.findByTimeBetweenAndEquipmentId(new Date(startTime), new Date(endTime), fjId);
+          if (!windTurbineStatusDataList.isEmpty()) {
             windTurbineStatusDataList.stream().sorted(Comparator.comparing(WindTurbineStatusData::getTime).reversed()).collect(Collectors.toList());
             WindTurbineStatusData windTurbineStatusData = windTurbineStatusDataList.get(0);
             if (windTurbineStatusData.getStatus() != null) {
@@ -1020,8 +1019,7 @@ public class E63UploadFileService extends BaseUploadFileService {
               pitchAngle = windTurbineStatusData.getPitchAngle();
             }
             log.info(electricFieldInfo.getStationCode() + "生成风机数据用数据表");
-          }
-          else{
+          } else {
             log.info(electricFieldInfo.getStationCode() + "生成风机数据缓存和数据表都没有值,使用默认0");
           }
         }
@@ -1068,7 +1066,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     // 获取逆变器
     List<InverterInfo> inverterInfoList = inverterInfoRepository.findAll();
     // 过滤上报的逆变器
-    List<InverterInfo> filterInverterInfoList = inverterInfoList.stream().filter(w -> w.getReport() == true).collect(Collectors.toList());
+    List<InverterInfo> filterInverterInfoList = inverterInfoList.stream().filter(AbstractEquipmentInfo::getReport).collect(Collectors.toList());
     if (filterInverterInfoList.size() > 0) {
       List<Map<String, String>> dtaInverterList = new ArrayList<>();
       for (InverterInfo inverterInfo : filterInverterInfoList) {
@@ -1143,9 +1141,9 @@ public class E63UploadFileService extends BaseUploadFileService {
           }
         }
 
-        if (!isUseRedis){
-          List<InverterStatusData> inverterStatusDataList = inverterStatusDataRepository.findByTimeBetweenAndEquipmentId(new Date(startTime), new Date(endTime),nbqId);
-          if (!inverterStatusDataList.isEmpty()){
+        if (!isUseRedis) {
+          List<InverterStatusData> inverterStatusDataList = inverterStatusDataRepository.findByTimeBetweenAndEquipmentId(new Date(startTime), new Date(endTime), nbqId);
+          if (!inverterStatusDataList.isEmpty()) {
             inverterStatusDataList.stream().sorted(Comparator.comparing(InverterStatusData::getTime).reversed()).collect(Collectors.toList());
             InverterStatusData inverterStatusData = inverterStatusDataList.get(0);
             if (inverterStatusData.getStatus() != null) {
@@ -1180,8 +1178,7 @@ public class E63UploadFileService extends BaseUploadFileService {
               cumulativeGeneratedEnergy = inverterStatusData.getCumulativeGeneratedEnergy();
             }
             log.info(electricFieldInfo.getStationCode() + "生成逆变器数据用数据表");
-          }
-          else{
+          } else {
             log.info(electricFieldInfo.getStationCode() + "生成逆变器数据缓存和数据表都没有值,使用默认0");
           }
         }
@@ -1225,7 +1222,7 @@ public class E63UploadFileService extends BaseUploadFileService {
    * 生成理论功率上报文件
    */
   public void generateTheroyFile(Date date) {
-    List<ElectricField> electricFieldList = null;
+    List<ElectricField> electricFieldList = new ArrayList<>();
     try {
       electricFieldList = super.getMultipleStation();
     } catch (BusinessException e) {
@@ -1245,7 +1242,7 @@ public class E63UploadFileService extends BaseUploadFileService {
         Long endTime = DateMomentUtil.getMomentTime(systemDate.getTime(), 1, 5 * 60 * 1000L);
         Long startTime = endTime - 4 * 60 * 1000;
         // 生成上报文件名格式
-        Template template = null;
+        Template template;
         if (electricFieldInfo.getElectricFieldTypeEnum().toString().equals("E1")) {
           fileName = e63UploadFileRuleService.getFileNameRule(electricFieldInfo, "E3", endTime);
           if (getFileName(fileName, "E3", stationCode)) {
@@ -1281,7 +1278,6 @@ public class E63UploadFileService extends BaseUploadFileService {
       if (StrUtil.isNotBlank(time)) {
         if (Long.parseLong(time) >= startTime && Long.parseLong(time) <= endTime) {
           // 对预测值保留2位小数显示输出
-          DecimalFormat df = new DecimalFormat("0.00");
           if (powerMap.get("ableValue") != null) {
             ableValueAfter = Float.parseFloat(powerMap.get("ableValue"));
           }
@@ -1294,15 +1290,15 @@ public class E63UploadFileService extends BaseUploadFileService {
       }
     }
 
-    if (!isUseRedis){
+    if (!isUseRedis) {
       // 从数据表获取
-      List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataRepository.findByTimeBetweenAndStationCode(new Date(startTime), new Date(endTime),electricFieldInfo.getStationCode());
+      List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataRepository.findByTimeBetweenAndStationCode(new Date(startTime), new Date(endTime), electricFieldInfo.getStationCode());
       if (!powerStationStatusDataList.isEmpty()) {
         powerStationStatusDataList.stream().sorted(Comparator.comparing(PowerStationStatusData::getTime).reversed()).collect(Collectors.toList());
         PowerStationStatusData powerStationStatusData = powerStationStatusDataList.get(0);
-        if (powerStationStatusData.getAbleValue()!=null)
+        if (powerStationStatusData.getAbleValue() != null)
           ableValueAfter = powerStationStatusData.getAbleValue().floatValue();
-        if (powerStationStatusData.getTheoryValue()!=null)
+        if (powerStationStatusData.getTheoryValue() != null)
           theoryValueAfter = powerStationStatusData.getTheoryValue().floatValue();
         log.info(electricFieldInfo.getStationCode() + "生成理论功率使用数据表");
       }
@@ -1364,19 +1360,19 @@ public class E63UploadFileService extends BaseUploadFileService {
       }
     }
 
-    if (!isUseRedis){
+    if (!isUseRedis) {
       // 从数据表获取
-      List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataRepository.findByTimeBetweenAndStationCode(new Date(startTime), new Date(endTime),electricFieldInfo.getStationCode());
+      List<PowerStationStatusData> powerStationStatusDataList = powerStationStatusDataRepository.findByTimeBetweenAndStationCode(new Date(startTime), new Date(endTime), electricFieldInfo.getStationCode());
       if (!powerStationStatusDataList.isEmpty()) {
         powerStationStatusDataList.stream().sorted(Comparator.comparing(PowerStationStatusData::getTime).reversed()).collect(Collectors.toList());
         PowerStationStatusData powerStationStatusData = powerStationStatusDataList.get(0);
-        if (powerStationStatusData.getAbleValue()!=null)
+        if (powerStationStatusData.getAbleValue() != null)
           ableValueAfter = powerStationStatusData.getAbleValue().floatValue();
-        if (powerStationStatusData.getTheoryValue()!=null)
+        if (powerStationStatusData.getTheoryValue() != null)
           theoryValueAfter = powerStationStatusData.getTheoryValue().floatValue();
-        if (powerStationStatusData.getReferencePowerBySample()!=null)
+        if (powerStationStatusData.getReferencePowerBySample() != null)
           referencePowerBySampleAfter = powerStationStatusData.getReferencePowerBySample().floatValue();
-        if (powerStationStatusData.getReferencePowerByMeasuring()!=null)
+        if (powerStationStatusData.getReferencePowerByMeasuring() != null)
           referencePowerByMeasuringAfter = powerStationStatusData.getReferencePowerByMeasuring().floatValue();
         log.info(electricFieldInfo.getStationCode() + "生成理论功率使用数据表");
       }
@@ -1417,7 +1413,7 @@ public class E63UploadFileService extends BaseUploadFileService {
     if (scale < 0) {
       throw new IllegalArgumentException("The scale must be a positive integer or zero");
     }
-    return v1.divide(v2, scale, BigDecimal.ROUND_HALF_UP);
+    return v1.divide(v2, scale, RoundingMode.HALF_UP);
   }
 
   private BigDecimal qxzRandomCreate(String type) {

+ 48 - 60
ipfcst-console/src/main/java/com/jiayue/ipfcst/fileupload/service/FtpUploadService.java

@@ -31,7 +31,7 @@ import java.util.stream.Collectors;
 
 @Service
 @Slf4j
-public class FtpUploadService  {
+public class FtpUploadService {
   @Autowired
   UploadFileChannelService uploadFileChannelService;
   @Autowired
@@ -62,21 +62,20 @@ public class FtpUploadService  {
         //找出可用的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());
+        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")){
+          if (uploadObject.getUploadProtocolEnum().toString().equals("E4")) {
             // FTP方式上报
             Ftp ftp = null;
             try {
-              FtpMode mode = null;
-              if ("E1".equals(uploadFileChannel.getFtpPassiveModeEnum().toString())){
+              FtpMode mode;
+              if ("E1".equals(uploadFileChannel.getFtpPassiveModeEnum().toString())) {
                 // 主动模式
                 mode = FtpMode.Active;
-              }
-              else{
+              } else {
                 // 被动模式
                 mode = FtpMode.Passive;
               }
@@ -87,14 +86,13 @@ public class FtpUploadService  {
               ftpConfig.setPassword(uploadFileChannel.getUploadPassword());
               ftpConfig.setUser(uploadFileChannel.getUploadUserName());
               ftpConfig.setCharset(Charset.forName(uploadObject.getUploadFileCharSetEnum().getMessage()));
-              ftpConfig.setConnectionTimeout(5*1000L);
+              ftpConfig.setConnectionTimeout(5 * 1000L);
               try {
                 ftp = new Ftp(ftpConfig, mode);
-                logger.info(uploadFileChannel.getChannelName()+"ftp客户端连接成功");
+                logger.info(uploadFileChannel.getChannelName() + "ftp客户端连接成功");
                 // 连接成功,设置通道状态
                 FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-              }
-              catch (Exception e){
+              } catch (Exception e) {
                 // 连接失败,设置通道状态
                 FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "0");
                 throw e;
@@ -102,35 +100,32 @@ public class FtpUploadService  {
 
               // 获取缓存中的上报文件
               logger.debug("上报文件缓存数量:" + FileConstant.readyUploadFileMap.size());
-              Map<String, UploadFileLog> fileMap = new HashMap<>();
-              fileMap.putAll(FileConstant.readyUploadFileMap);
+              Map<String, UploadFileLog> fileMap = new HashMap<>(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);
+                  logger.info("在缓存中找到通道[" + uploadFileChannel.getChannelName() + "]文件:" + keys[2]);
+                  ftpUploadTransactionService.singleUpload(uploadObject, uploadFileChannel, entry, ftp, null, keys, logger, uploadURLList);
                 }
               }
-            }
-            catch (Exception e){
-              logger.error(uploadFileChannel.getChannelName()+"上报失败",e);
+            } catch (Exception e) {
+              logger.error(uploadFileChannel.getChannelName() + "上报失败", e);
               try {
-                Process process = Runtime.getRuntime().exec("ping "+uploadFileChannel.getRemoteIp() + " -c 2");
+                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 = "";
+                StringBuilder returnMsg = new StringBuilder();
+                String line;
                 while ((line = returnData.readLine()) != null) {
-                  returnMsg += line;
+                  returnMsg.append(line);
                 }
 
-                if(returnMsg.indexOf("100% loss")!=-1){
-                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接不畅通.");
-                }
-                else{
-                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接畅通.");
+                if (returnMsg.indexOf("100% loss") != -1) {
+                  logger.info("与 " + uploadFileChannel.getRemoteIp() + " 连接不畅通.");
+                } else {
+                  logger.info("与 " + uploadFileChannel.getRemoteIp() + " 连接畅通.");
                 }
 
                 returnData.close();
@@ -140,63 +135,57 @@ public class FtpUploadService  {
                 process.destroy();
 
               } catch (IOException ex) {
-                logger.error("ping对方ip执行失败",ex);
+                logger.error("ping对方ip执行失败", ex);
               }
-            }
-            finally {
-              if (ftp!=null){
+            } finally {
+              if (ftp != null) {
                 IoUtil.close(ftp);
-                logger.info(uploadFileChannel.getChannelName()+"ftp客户端关闭连接");
+                logger.info(uploadFileChannel.getChannelName() + "ftp客户端关闭连接");
               }
             }
-          }
-          else{
+          } else {
             // SFTP方式上报
             Sftp sftp = null;
-            try{
+            try {
               try {
-                sftp = new Sftp(uploadFileChannel.getRemoteIp(), Integer.parseInt(uploadFileChannel.getRemotePort()),uploadFileChannel.getUploadUserName(),uploadFileChannel.getUploadPassword());
-                logger.info(uploadFileChannel.getChannelName()+":sftp连接创建成功");
+                sftp = new Sftp(uploadFileChannel.getRemoteIp(), Integer.parseInt(uploadFileChannel.getRemotePort()), uploadFileChannel.getUploadUserName(), uploadFileChannel.getUploadPassword());
+                logger.info(uploadFileChannel.getChannelName() + ":sftp连接创建成功");
                 // 连接成功,设置通道状态
                 FileConstant.channelStatusMap.put(uploadObject.getId() + "-" + uploadFileChannel.getId(), "1");
-              }
-              catch (Exception e){
-                logger.error(uploadFileChannel.getChannelName()+":sftp连接失败",e);
+              } 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);
+              Map<String, UploadFileLog> fileMap = new HashMap<>(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,null,sftp,keys,logger,uploadURLList);
+                  logger.info("在缓存中找到通道[" + uploadFileChannel.getChannelName() + "]文件:" + keys[2] + ",将文件送入到上报程序中。");
+                  ftpUploadTransactionService.singleUpload(uploadObject, uploadFileChannel, entry, null, sftp, keys, logger, uploadURLList);
                 }
               }
-            }
-            catch (Exception e){
-              logger.error(uploadFileChannel.getChannelName()+"上报失败",e);
+            } catch (Exception e) {
+              logger.error(uploadFileChannel.getChannelName() + "上报失败", e);
               try {
-                Process process = Runtime.getRuntime().exec("ping "+uploadFileChannel.getRemoteIp() + " -c 2");
+                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 = "";
+                StringBuilder returnMsg = new StringBuilder();
+                String line;
                 while ((line = returnData.readLine()) != null) {
-                  returnMsg += line;
+                  returnMsg.append(line);
                 }
 
-                if(returnMsg.indexOf("100% loss")!=-1){
-                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接不畅通.");
-                }
-                else{
-                  logger.info("与 " +uploadFileChannel.getRemoteIp() +" 连接畅通.");
+                if (returnMsg.indexOf("100% loss") != -1) {
+                  logger.info("与 " + uploadFileChannel.getRemoteIp() + " 连接不畅通.");
+                } else {
+                  logger.info("与 " + uploadFileChannel.getRemoteIp() + " 连接畅通.");
                 }
 
                 returnData.close();
@@ -206,11 +195,10 @@ public class FtpUploadService  {
                 process.destroy();
 
               } catch (IOException ex) {
-                logger.error("ping对方ip执行失败",ex);
+                logger.error("ping对方ip执行失败", ex);
               }
-            }
-            finally {
-              if (sftp!=null){
+            } finally {
+              if (sftp != null) {
                 logger.info("sftp客户端关闭");
                 sftp.close();
               }