From 7126eab629d31beb5164b576a44b865a6a00f07c Mon Sep 17 00:00:00 2001 From: lyh <925863403@qq.com> Date: 星期三, 17 九月 2025 17:56:29 +0800 Subject: [PATCH] 420工控网修改回传 --- src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java | 316 ++++++++++++++++++++------------------------ src/main/java/com/lxzn/framework/utils/file/FileUtil.java | 77 +++++++--- 2 files changed, 194 insertions(+), 199 deletions(-) diff --git a/src/main/java/com/lxzn/framework/utils/file/FileUtil.java b/src/main/java/com/lxzn/framework/utils/file/FileUtil.java index 3d7beb6..704cf3c 100644 --- a/src/main/java/com/lxzn/framework/utils/file/FileUtil.java +++ b/src/main/java/com/lxzn/framework/utils/file/FileUtil.java @@ -23,6 +23,8 @@ import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -241,35 +243,58 @@ return result; } - public static boolean copyFileRec(String lastFile) { - String absolutePathSend = lastFile; - //瀛楃涓叉浛鎹� - String absolutePathSendNotFile = lastFile.replace("/REC/","/bak_rec/"); - String fileNameNoPath = (new File(lastFile)).getName(); - String suffix = getFileSuffix(fileNameNoPath); - Integer recNum = absolutePathSendNotFile.lastIndexOf(fileNameNoPath); - if (suffix == null) { - absolutePathSendNotFile = absolutePathSendNotFile.substring(0,recNum) + fileNameNoPath+ "-" + - DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL); + public static boolean copyFileRec(String sourceFilePath) { + // 楠岃瘉杈撳叆璺緞 + if (sourceFilePath == null || sourceFilePath.isEmpty()) { + System.err.println("Invalid source file path"); + return false; + } + + Path sourcePath = Paths.get(sourceFilePath); + + // 楠岃瘉婧愭枃浠跺瓨鍦� + if (!Files.exists(sourcePath)) { + System.err.println("Source file does not exist: " + sourceFilePath); + return false; + } + + // 鏋勫缓鐩爣鐩綍璺緞锛堟浛鎹�/REC/涓�/bak_rec/锛� + String targetDirPath = sourcePath.getParent().toString() + .replace("/REC/", "/bak_rec/") + .replace("\\REC\\", "\\bak_rec\\"); + + // 纭繚鏇挎崲鎴愬姛 - 濡傛灉鏈浛鎹㈠垯鎵嬪姩鏋勫缓璺緞 + if (targetDirPath.equals(sourcePath.getParent().toString())) { + targetDirPath = sourcePath.getParent().toString().replace("REC", "bak_rec"); + } + + Path targetDir = Paths.get(targetDirPath); + + // 鐢熸垚甯︽椂闂存埑鐨勬柊鏂囦欢鍚� + String fileName = sourcePath.getFileName().toString(); + String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); + String newFileName; + + int dotIndex = fileName.lastIndexOf('.'); + if (dotIndex > 0) { + String baseName = fileName.substring(0, dotIndex); + String extension = fileName.substring(dotIndex + 1); + newFileName = baseName + "-" + timestamp + "." + extension; } else { - String name = fileNameNoPath.replace("." + suffix,""); - absolutePathSendNotFile = absolutePathSendNotFile.substring(0,recNum) + name+ "-" + - DateUtil.format(DateUtil.getNow(),DateUtil.STR_DATE_TIME_FULL) + "." + suffix; + newFileName = fileName + "-" + timestamp; } - try{ - FileChannel in = new FileInputStream(absolutePathSend).getChannel(); - File file = new File(absolutePathSendNotFile); - if (!file.getParentFile().exists()){ - //鏂囦欢澶逛笉瀛樺湪 鐢熸垚 - file.getParentFile().mkdirs(); - } - FileChannel out = new FileOutputStream(absolutePathSendNotFile, true).getChannel(); - out.transferFrom(in, 0, in.size()); - in.close(); - out.close(); + + Path targetPath = targetDir.resolve(newFileName); + + try { + // 鍒涘缓鐩爣鐩綍锛堝寘鎷墍鏈変笉瀛樺湪鐨勭埗鐩綍锛� + Files.createDirectories(targetDir); + + // 浣跨敤NIO澶嶅埗鏂囦欢 + Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); return true; - } - catch (IOException e) { + } catch (IOException e) { + System.err.println("File copy failed: " + e.getMessage()); e.printStackTrace(); return false; } diff --git a/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java b/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java index ac02a61..b0dd5ed 100644 --- a/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java +++ b/src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java @@ -45,7 +45,10 @@ import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Date; @@ -177,209 +180,176 @@ } @Override - @Transactional(rollbackFor = {Exception.class}) - public boolean addDocInfoRec(String pathFile,File fileRec) { - // /dnc/NC/3140058/REC/ - if (StringUtils.isEmpty(pathFile)) { + @Transactional(rollbackFor = Exception.class) + public boolean addDocInfoRec(String pathFile, File fileRec) { + // 鍙傛暟鏍¢獙 + if (StringUtils.isEmpty(pathFile) || fileRec == null || !fileRec.exists()) { + log.error("Invalid parameters"); return false; } - SingleDictionary singleDictionary=dictionaryService.findListFromTypeCode("virtual_equipment_id").get(0); - MultipartFile file = FileUtil.fileToMultipartFile(fileRec); + // 鑾峰彇鏂囨。鍒嗙被 DocClassification docClass = docClassificationService.getByCode("REC"); - if(docClass == null) { + if (docClass == null) { ExceptionCast.cast(DocumentCode.DOC_CLASS_ERROR); - } - //鏍规嵁璁惧缂栧彿鏌ヨ鏁版嵁 - Integer recNum = pathFile.lastIndexOf("/REC/"); - if (recNum == -1) { return false; } - String recF = pathFile.substring(0,recNum);//灏嗚繑鍥瀌ef}ab - Integer equipmentId = recF.lastIndexOf("/"); - String deviceNo = recF.substring(equipmentId+1,recF.length()); + // 澧炲己璺緞瑙f瀽閫昏緫 + String deviceNo = extractDeviceNoFromPath(pathFile); if (StringUtils.isEmpty(deviceNo)) { - log.error("璁惧鍙蜂负绌�"); + log.error("Failed to extract deviceNo from path: {}", pathFile); return false; } - log.info("deviceNo ==== " + deviceNo); + // 鑾峰彇璁惧淇℃伅 DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(deviceNo); if (deviceInfo == null) { + log.error("Device not found: {}", deviceNo); return false; } - - String docEquipmentId = null; - if (singleDictionary != null) { - docEquipmentId= String.valueOf(singleDictionary.getDicValue()); + String originalSuffix = FileUtil.getFileSuffix(fileRec.getName()); + if (!"zip".equalsIgnoreCase(originalSuffix) && !"rar".equalsIgnoreCase(originalSuffix)) { + processNonArchiveFile(fileRec, deviceInfo, docClass, originalSuffix); } - List<String> strings = deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId()); - String fileSuffix = FileUtil.getFileSuffix(fileRec.getName()); - if ( !fileSuffix.equals("zip") && !fileSuffix.equals("rar") ) { - //澶勭悊鏂囦欢 璁板綍骞朵笂鎶� - //1銆� 鍒ゆ柇绔彛鏄惁鑳藉璁块棶 鏂囦欢璺緞鍔� -// boolean btelnetPort = TelnetUtil.telnetPort(serverIp,serverPort,10); -// if (!btelnetPort) { -// ExceptionCast.cast(ActivitiCode.ACT_DEVICE_DOC_FILELABLE); -// } - DncPassLog passInfoTxt = new DncPassLog(); + return processArchiveFile(fileRec, deviceInfo, docClass); + } - String path = org.apache.commons.lang3.StringUtils.join(strings.toArray(), "/"); - Date dateFirst = DateUtil.getNow(); - passInfoTxt.setDayTime(DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)); - - //浼戠湢 500姣 - DncPassLog dncPassLog = dncPassLogService.findDayTime(DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)); - Integer fileTxt = 0, fileNc =0; - if (dncPassLog !=null) { - fileTxt = dncPassLog.getSequenceNumber() + 1; - fileNc = fileTxt + 1; - } else { - fileTxt = 1; - fileNc = fileTxt + 1; - } - //澶勭悊鏂囦欢鍚嶇О 鏂囦欢璺緞 - String sequence = String.format("%06d",fileTxt); - String sequenceNc = String.format("%06d",fileNc); - passInfoTxt.setSequenceNumber(fileTxt); - passInfoTxt.setSequenceOrder(sequence); - passInfoTxt.setCreateTime(dateFirst); - System.out.println(DateUtil.format(dateFirst,DateUtil.STR_DATE_TIME)); - passInfoTxt.setPassType("01"); - dncPassLogService.save(passInfoTxt); - - DncPassLog passInfoNc = new DncPassLog(); - passInfoNc.setSequenceNumber(fileNc); - passInfoNc.setSequenceOrder(sequenceNc); - passInfoNc.setDayTime(DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)); - passInfoNc.setPassType("02"); - passInfoNc.setPassName(fileRec.getName()); - try { - Thread.sleep(1000); - Date date = new Date(); - passInfoNc.setCreateTime(date); - System.out.println(DateUtil.format(date,DateUtil.STR_DATE_TIME)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - dncPassLogService.save(passInfoNc); - - NcTxtFilePathInfo ncTxt = new NcTxtFilePathInfo(); - ncTxt.setEquipmentId(deviceInfo.getDeviceNo()); - if (deviceInfo.getDeviceNo().equals(docEquipmentId)) { - //鍘熸湁鍚嶇О鍔犳椂闂� - ncTxt.setFileNcName(fileRec.getName()+"_"+DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)); - }else { - ncTxt.setFileNcName("10B"+DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)+sequenceNc); - } - ncTxt.setFileTxtName("10B"+DateUtil.format(dateFirst,DateUtil.STR_YEARMONTHDAY)+sequence); - ncTxt.setFilePath(path + "/"+ deviceInfo.getDeviceNo() + "/" ); - ncTxt.setOrigFileName(fileRec.getName()); - ncTxt.setOrigFileSuffix(fileSuffix); - ncTxt.setFileAddOrDelete(1); - String loFilePath = localFilePath + ncTxt.getFileTxtName() + ".nc"; - String size = String.valueOf(fileRec.length()); - - try { - String allList = new String(); - allList=(ncTxt.getFileTxtName()+"\n"); - allList+=(ncTxt.getFileNcName()+"\n"); - allList+=(ncTxt.getOrigFileName()+"\n"); - allList+=(ncTxt.getOrigFileSuffix()+"\n"); - allList+=(ncTxt.getFilePath()+"\n"); - allList+=(ncTxt.getEquipmentId()+"\n"); - allList+=(ncTxt.getFileAddOrDelete().toString()+"\n"); - // 鏂囦欢澶у皬瀛楄妭 绗簩琛� 宸ユ帶缃戣繘琛屾枃浠跺垎鏋� - allList+= (size+"\n"); - - FileUtil.fileWriterSql(loFilePath,allList); - - //瀵规瘮璁惧缂栧彿 - if (deviceInfo.getDeviceNo().equals(docEquipmentId)) { - String originalFilename = fileRec.getName(); - File virtualDeviceDir = new File(localFilePath); - if (!virtualDeviceDir.exists() && !virtualDeviceDir.mkdirs()) { - log.error("鏃犳硶鍒涘缓铏氭嫙璁惧鐩綍: {}", virtualDeviceDir.getAbsolutePath()); - return false; - } - // 3. 鏋勫缓鐩爣鏂囦欢璺緞 - File targetFile = new File(virtualDeviceDir, originalFilename); - try { - // 4. 浣跨敤NIO澶嶅埗鏂囦欢锛屽苟鏇挎崲宸插瓨鍦ㄧ殑鏂囦欢 - //鏇存崲鏂囦欢鍚嶏紝鏇存崲涓簄cTxt.getFileNcName() - Files.copy( - fileRec.toPath(), - targetFile.toPath(), - StandardCopyOption.REPLACE_EXISTING - ); - log.info("铏氭嫙璁惧鏂囦欢宸蹭繚瀛樿嚦: {}", targetFile.getAbsolutePath()); - } catch (IOException e) { - log.error("铏氭嫙璁惧鏂囦欢淇濆瓨澶辫触", e); - return false; - } - return true; - }else { - //鏂囦欢瑙f瀽閲嶆柊瑙勫垝 - //娣诲姞鏂囦欢鍚嶅瓧锛岀涓�琛� - boolean copyFileNc = FileUtil.copyFileUpNameRec(fileRec, - localFilePath + ncTxt.getFileNcName(), - fileSuffix,"NC"); - if (!copyFileNc) { - FileUtil.deleteNcFile(loFilePath); - } - } - } catch (IOException e) { - e.printStackTrace(); + // 澧炲己璺緞瑙f瀽鏂规硶 + private String extractDeviceNoFromPath(String pathFile) { + // 缁熶竴澶勭悊璺緞鍒嗛殧绗� + String normalizedPath = pathFile.replace('\\', '/'); + // 鏌ユ壘"/REC/"浣嶇疆 + int recIndex = normalizedPath.lastIndexOf("/REC/"); + if (recIndex != -1) { + String prefix = normalizedPath.substring(0, recIndex); + int lastSlash = prefix.lastIndexOf('/'); + return (lastSlash != -1) ? prefix.substring(lastSlash + 1) : prefix; + } + // 澶勭悊娌℃湁缁撳熬鏂滄潬鐨勬儏鍐� + recIndex = normalizedPath.lastIndexOf("/REC"); + if (recIndex != -1 && (recIndex + 4 == normalizedPath.length() + || normalizedPath.charAt(recIndex + 4) == '/')) { + String prefix = normalizedPath.substring(0, recIndex); + int lastSlash = prefix.lastIndexOf('/'); + return (lastSlash != -1) ? prefix.substring(lastSlash + 1) : prefix; + } + // 灏濊瘯鍩轰簬璺緞娈佃В鏋� + String[] segments = normalizedPath.split("/"); + for (int i = 0; i < segments.length; i++) { + if ("REC".equalsIgnoreCase(segments[i]) && i > 0) { + return segments[i - 1]; } } - String fileName = FileUtil.getFilenameNonSuffix(file.getOriginalFilename()); - FileUploadResult fileUploadResult = FileUtil.uploadFile(file); - if(fileUploadResult == null) { + return null; + } + + // 闈炲帇缂╂枃浠跺鐞嗭紙浜嬪姟鍐咃級 + private boolean processNonArchiveFile(File fileRec, DeviceInfo deviceInfo, + DocClassification docClass, String originalSuffix) { + try { + Date currentDate = new Date(); + String dayTime = DateUtil.format(currentDate, DateUtil.STR_YEARMONTHDAY); + DncPassLog passLog = dncPassLogService.findDayTime(dayTime); + int newSequence = (passLog != null) ? passLog.getSequenceNumber() + 1 : 1; + DncPassLog txtLog = new DncPassLog(); + txtLog.setDayTime(dayTime); + txtLog.setSequenceNumber(newSequence); + txtLog.setSequenceOrder(String.format("%06d", newSequence)); + txtLog.setCreateTime(currentDate); + txtLog.setPassType("01"); + dncPassLogService.save(txtLog); + DncPassLog ncLog = new DncPassLog(); + ncLog.setDayTime(dayTime); + ncLog.setSequenceNumber(newSequence + 1); + ncLog.setSequenceOrder(String.format("%06d", newSequence + 1)); + ncLog.setPassType("02"); + ncLog.setPassName(fileRec.getName()); + ncLog.setCreateTime(currentDate); + dncPassLogService.save(ncLog); + NcTxtFilePathInfo fileInfo = new NcTxtFilePathInfo(); + fileInfo.setEquipmentId(deviceInfo.getDeviceNo()); + fileInfo.setOrigFileName(fileRec.getName()); + fileInfo.setOrigFileSuffix(originalSuffix); + fileInfo.setFileAddOrDelete(1); + List<String> groupPaths = deviceGroupService.findListParentTreeAll(deviceInfo.getGroupId()); + String storagePath = String.join("/", groupPaths) + "/" + deviceInfo.getDeviceNo() + "/"; + fileInfo.setFilePath(storagePath); + fileInfo.setFileTxtName("10B" + dayTime + String.format("%06d", newSequence)); + fileInfo.setFileNcName("10B" + dayTime + String.format("%06d", newSequence + 1)); + return savePhysicalDeviceFile(fileRec, fileInfo); + } catch (Exception e) { + log.error("Non-archive processing failed", e); + throw new RuntimeException(e); + } + } + + // 鍘嬬缉鏂囦欢澶勭悊锛堜簨鍔″唴锛� + private boolean processArchiveFile(File fileRec, DeviceInfo deviceInfo, DocClassification docClass) { + MultipartFile multipartFile = FileUtil.fileToMultipartFile(fileRec); + FileUploadResult uploadResult = FileUtil.uploadFile(multipartFile); + if (uploadResult == null) return false; + + // 妫�鏌ユ枃妗f槸鍚﹀凡瀛樺湪 + String fileName = FileUtil.getFilenameNonSuffix(multipartFile.getOriginalFilename()); + if (findByAttrAndDocName(fileName, 4, deviceInfo.getDeviceId()) != null) { + log.warn("Document already exists: {}", fileName); return false; } - DocInfo en = findByAttrAndDocName(fileName, 4, deviceInfo.getDeviceId()); - if(en != null) { - return false; - } - + // 淇濆瓨鏂囨。鍏崇郴 + DocRelative docRelative = new DocRelative(); + docRelative.setAttributionId(deviceInfo.getDeviceId()); + docRelative.setAttributionType(4); + docRelative.setClassificationId(docClass.getClassificationId()); + // 淇濆瓨鏂囨。淇℃伅锛堜娇鐢ㄤ笂浼犲悗鐨勬枃浠跺悕锛� DocInfo docInfo = new DocInfo(); String docId = IdWorker.getIdStr(); docInfo.setDocId(docId); - docInfo.setDocName(fileUploadResult.getFileName()); - docInfo.setDocSuffix(fileUploadResult.getFileSuffix()); + docInfo.setDocName(uploadResult.getFileName()); + docInfo.setDocSuffix(uploadResult.getFileSuffix()); docInfo.setDocStatus(2); - DocRelative dr = new DocRelative(); - dr.setAttributionId(deviceInfo.getDeviceId()); - dr.setDocId(docInfo.getDocId()); - dr.setAttributionType(4); - dr.setClassificationId(docClass.getClassificationId()); + // 淇濆瓨鏂囦欢璁板綍 + DocFile docFile = new DocFile(); + docFile.setDocId(docId); + docFile.setFileName(uploadResult.getFileName()); + docFile.setFileEncodeName(uploadResult.getEncodeFileName()); + docFile.setFilePath(uploadResult.getFilePath()); + docFile.setFileSize(uploadResult.getFileSize()); + docFile.setFileSuffix(uploadResult.getFileSuffix()); + docFile.setUpdateUser("system"); try { - boolean b = docRelativeService.save(dr); - if(!b) { + docRelative.setDocId(docId); + if (!docRelativeService.save(docRelative)) { ExceptionCast.cast(DocumentCode.DOC_UPLOAD_ERROR); } - }catch (Exception e) { - e.printStackTrace(); + if (!docFileService.addDocFile(docFile)) return false; + docInfo.setPublishVersion(docFile.getDocVersion()); + docInfo.setPublishFileId(docFile.getFileId()); + return super.save(docInfo); + } catch (Exception e) { + log.error("Archive processing failed", e); + throw new RuntimeException(e); } - DocFile docFile = new DocFile(); - docFile.setDocId(docInfo.getDocId()); - docFile.setFileName(fileUploadResult.getFileName()); - docFile.setFileEncodeName(fileUploadResult.getEncodeFileName()); - docFile.setFilePath(fileUploadResult.getFilePath()); - docFile.setFileSize(fileUploadResult.getFileSize()); - docFile.setFileSuffix(fileUploadResult.getFileSuffix()); - docFile.setUpdateUser("11"); - boolean b = docFileService.addDocFile(docFile); - if(!b) { - return false; - } - docInfo.setPublishVersion(docFile.getDocVersion()); - docInfo.setPublishFileId(docFile.getFileId()); - boolean saveBool = super.save(docInfo); - return saveBool; - } + private boolean savePhysicalDeviceFile(File sourceFile, NcTxtFilePathInfo fileInfo) throws IOException { + // 鐢熸垚鍏冩暟鎹枃浠� + Path metaFilePath = Paths.get(localFilePath, fileInfo.getFileTxtName() + ".nc"); + String metaContent = String.join("\n", + fileInfo.getFileTxtName(), + fileInfo.getFileNcName(), + fileInfo.getOrigFileName(), + fileInfo.getOrigFileSuffix(), + fileInfo.getFilePath(), + fileInfo.getEquipmentId(), + String.valueOf(fileInfo.getFileAddOrDelete()), + String.valueOf(sourceFile.length()) + ); + Files.write(metaFilePath, metaContent.getBytes(StandardCharsets.UTF_8)); + + // 澶嶅埗鏂囦欢鍒版柊浣嶇疆锛堜笉淇敼鍘熷鏂囦欢锛� + Path targetPath = Paths.get(localFilePath+"/", fileInfo.getFileNcName()+".NC"); + Files.copy(sourceFile.toPath(), targetPath); + return true; + } @Override @Transactional(rollbackFor = {Exception.class}) -- Gitblit v1.9.3