lyh
7 小时以前 7126eab629d31beb5164b576a44b865a6a00f07c
420工控网修改回传
已修改2个文件
381 ■■■■ 文件已修改
src/main/java/com/lxzn/framework/utils/file/FileUtil.java 75 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/lxzn/nc/service/impl/DocInfoServiceImpl.java 306 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
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;
        }
        Path targetPath = targetDir.resolve(newFileName);
        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();
            // 创建目标目录(包括所有不存在的父目录)
            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;
        }
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})
    @Transactional(rollbackFor = Exception.class)
    public boolean addDocInfoRec(String pathFile,File fileRec) {
        // /dnc/NC/3140058/REC/
        if (StringUtils.isEmpty(pathFile)) {
        // 参数校验
        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) {
            ExceptionCast.cast(DocumentCode.DOC_CLASS_ERROR);
        }
        //根据设备编号查询数据
        Integer recNum = pathFile.lastIndexOf("/REC/");
        if (recNum == -1) {
            return false;
        }
        String  recF =  pathFile.substring(0,recNum);//将返回def}ab
        Integer equipmentId = recF.lastIndexOf("/");
        String deviceNo = recF.substring(equipmentId+1,recF.length());
        // 增强路径解析逻辑
        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();
            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;
        return processArchiveFile(fileRec, deviceInfo, docClass);
            }
            //处理文件名称  文件路径
            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());
    // 增强路径解析方法
    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];
            }
        }
        return null;
    }
    // 非压缩文件处理(事务内)
    private boolean processNonArchiveFile(File fileRec, DeviceInfo deviceInfo,
                                          DocClassification docClass, String originalSuffix) {
            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();
            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);
        }
            }
            dncPassLogService.save(passInfoNc);
    // 压缩文件处理(事务内)
    private boolean processArchiveFile(File fileRec, DeviceInfo deviceInfo, DocClassification docClass) {
        MultipartFile multipartFile = FileUtil.fileToMultipartFile(fileRec);
        FileUploadResult uploadResult = FileUtil.uploadFile(multipartFile);
        if (uploadResult == null) return false;
            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());
        // 检查文档是否已存在
        String fileName = FileUtil.getFilenameNonSuffix(multipartFile.getOriginalFilename());
        if (findByAttrAndDocName(fileName, 4, deviceInfo.getDeviceId()) != null) {
            log.warn("Document already exists: {}", fileName);
                        return false;
                    }
                    // 3. 构建目标文件路径
                    File targetFile = new File(virtualDeviceDir, originalFilename);
                    try {
                        // 4. 使用NIO复制文件,并替换已存在的文件
                        //更换文件名,更换为ncTxt.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 {
                    //文件解析重新规划
                    //添加文件名字,第一行
                    boolean copyFileNc = FileUtil.copyFileUpNameRec(fileRec,
                            localFilePath + ncTxt.getFileNcName(),
                            fileSuffix,"NC");
                    if (!copyFileNc) {
                        FileUtil.deleteNcFile(loFilePath);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String fileName = FileUtil.getFilenameNonSuffix(file.getOriginalFilename());
        FileUploadResult fileUploadResult = FileUtil.uploadFile(file);
        if(fileUploadResult == null) {
            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();
        }
        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;
        }
            if (!docFileService.addDocFile(docFile)) return false;
        docInfo.setPublishVersion(docFile.getDocVersion());
        docInfo.setPublishFileId(docFile.getFileId());
        boolean saveBool = super.save(docInfo);
        return saveBool;
            return super.save(docInfo);
        } catch (Exception e) {
            log.error("Archive processing failed", e);
            throw new RuntimeException(e);
        }
    }
    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})