package org.springblade.mdm.task;
|
|
import com.alibaba.excel.util.StringUtils;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.codec.digest.DigestUtils;
|
import org.springblade.mdm.basesetting.machine.MachineService;
|
import org.springblade.mdm.basesetting.machine.entity.Machine;
|
import org.springblade.mdm.commons.service.ParamService;
|
import org.springblade.mdm.gkw.programnode.entity.MachineFile;
|
import org.springblade.mdm.gkw.programnode.service.MachineFileService;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.stereotype.Component;
|
|
import java.io.File;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
import java.nio.file.StandardCopyOption;
|
import java.nio.file.attribute.BasicFileAttributes;
|
import java.nio.file.attribute.FileTime;
|
import java.time.LocalDateTime;
|
import java.util.Date;
|
import java.util.List;
|
|
/**
|
* 机床回传文件夹rec,目录文件超过机床设定的时间移动到temp文件夹
|
*/
|
@Slf4j
|
@Component
|
@EnableScheduling
|
public class ReceiveDirClearTask {
|
@Autowired
|
private MachineFileService machineFileService;
|
@Autowired
|
private MachineService machineService;
|
@Autowired
|
private ParamService paramService;
|
/**
|
* 文件默认保存小时数
|
*/
|
private static final int DEFAULT_HOUR = 8;
|
// 每5秒执行一次
|
//@Scheduled(fixedRate = 1000000)
|
//@Scheduled(cron = "0 1 0 * * ?") // 每天上午0点1分执行
|
//@Scheduled(cron = "0 */3 * * * ?")
|
//@Scheduled(cron = "0 15 19 * * ?") //test
|
//@Scheduled(cron = "${task.cron.machine_file_scan}")
|
@Scheduled(cron = "${task.cron.machine_rec_clean:0 3 * * * ?}")
|
public void execute() {
|
String networkType = paramService.getParamValue(ParamService.NETWORK_TYPE,ParamService.NETWORK_TYPE_SHEMI);
|
|
if(!ParamService.NETWORK_TYPE_SHEMI.equals(networkType)){
|
//非涉密网,才扫描目录文件
|
moveOverTimeFiles();
|
}
|
|
}
|
|
/**
|
* 扫描数据库记录,超时则移动文件
|
*/
|
public void moveOverTimeFiles() {
|
List<Machine> machines = machineService.getEnableMachines();
|
LocalDateTime now = LocalDateTime.now();
|
for (Machine machine : machines) {
|
int remainHours = machine.getReceiveDirExpiryHours() != null ?machine.getReceiveDirExpiryHours():DEFAULT_HOUR;
|
LocalDateTime earlyTime = now.minusHours(remainHours);
|
List<MachineFile> overTimeFiles = this.machineFileService.lambdaQuery().lt(MachineFile::getFileCreateTime,earlyTime)
|
.eq(MachineFile::getDirType,MachineFile.DIR_TYPE_REC)
|
.eq(MachineFile::getMachineCode,machine.getCode()).list();
|
|
for(MachineFile overTimeFile : overTimeFiles){
|
try {
|
moveFileToTemp(overTimeFile, machine);
|
}catch(Exception e){
|
log.error("移动rec文件失败:"+overTimeFile.getName(),e);
|
}
|
}
|
|
}
|
|
}
|
|
/**
|
* 文件移动到temp
|
* @param overTimeFile
|
*/
|
private void moveFileToTemp(MachineFile overTimeFile,Machine machine) throws IOException {
|
String srcFilepath = MachineFileService.getBasePath(machine,overTimeFile.getDirType())+ File.separator+overTimeFile.getName();
|
Path source = Paths.get(srcFilepath);
|
if(!source.toFile().exists()){
|
return;
|
}
|
String targetFilepath = MachineFileService.getBasePath(machine,MachineFile.DIR_TYPE_TEMP)+ File.separator+overTimeFile.getName();
|
Path target = Paths.get(targetFilepath);
|
|
Path targetDir = target.getParent();
|
if (targetDir != null && !Files.exists(targetDir)) {
|
Files.createDirectories(targetDir);
|
}
|
|
// 使用 REPLACE_EXISTING 选项来覆盖已存在的文件
|
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
|
}
|
|
|
/**
|
* 扫描目录
|
* @param machine 机床信息
|
* @param dirType 目录类型
|
* @throws IOException
|
*/
|
public void scanDir(Machine machine,String dirType) throws IOException {
|
String basePath = MachineFileService.getBasePath(machine,dirType);
|
if(basePath == null) {
|
log.warn("目录类型不匹配:{}",dirType);
|
return;
|
}
|
Path dirPath = Paths.get(basePath);
|
if(!dirPath.toFile().exists()){
|
log.warn("扫描目录:{} 不存在",dirPath);
|
return;
|
}
|
// 只包含普通文件
|
List<Path> files = Files.list(dirPath)
|
.filter(Files::isRegularFile).toList();
|
|
byte[] buffer = new byte[2048];
|
|
MachineFile existFileInDb;
|
//boolean exists;//文件是否存在于数据库中
|
for (Path filePath : files) {
|
|
existFileInDb = null;
|
//exists = false;
|
|
MachineFile mf = new MachineFile();
|
|
mf.setTenantId("000000");
|
mf.setName(filePath.toFile().getName());
|
mf.setDirType(dirType);
|
mf.setMachineCode(machine.getCode());
|
|
try {
|
BasicFileAttributes attrs = Files.readAttributes(
|
filePath,
|
BasicFileAttributes.class
|
);
|
|
FileTime creationTime = attrs.creationTime();
|
Date creationDate = new Date(creationTime.toMillis());
|
mf.setFileCreateTime(creationDate);
|
|
FileTime modifyTime = attrs.lastModifiedTime();
|
mf.setFileModifyTime(new Date(modifyTime.toMillis()));
|
mf.setFileSize(Files.size(filePath));
|
try (InputStream inputStream = Files.newInputStream(filePath)) {
|
// 使用输入流读取文件内容
|
int bytesRead = inputStream.read(buffer);
|
mf.setMd5(DigestUtils.md5Hex(buffer));
|
} catch (IOException e) {
|
log.error("读取文件md5失败",e);
|
continue;//有错误,掠过
|
}
|
|
//exists = machineFileService.fileExists(mf.getName(),dirType,machine.getCode());
|
|
existFileInDb = machineFileService.getExistsFile(mf.getName(),dirType,machine.getCode());
|
System.out.println("文件创建时间: " + creationDate);
|
} catch (IOException e) {
|
log.error("读取文件信息失败",e);
|
}
|
if(existFileInDb == null) {
|
machineFileService.save(mf);
|
}else{
|
log.info("文件已存在掠过:{}",filePath.getFileName());
|
//已存在咋整。
|
existFileInDb.setFileSize(mf.getFileSize());
|
|
existFileInDb.setFileCreateTime(mf.getFileCreateTime());
|
existFileInDb.setFileModifyTime(mf.getFileModifyTime());
|
if(!StringUtils.equals(existFileInDb.getMd5(),mf.getMd5())){
|
//文件内容发生变化了,设置状态为初始状态
|
existFileInDb.setStatus(MachineFile.STATUS_NORMAL);
|
}
|
existFileInDb.setMd5(mf.getMd5());
|
|
|
machineFileService.updateById(existFileInDb);
|
|
}
|
|
}
|
|
|
}
|
|
/**
|
* 清理已经删除了文件的记录
|
* @param machine
|
* @param dirType
|
* @throws IOException
|
*/
|
void clearDeletedReccords(Machine machine,String dirType) throws IOException {
|
List<MachineFile> machineFiles = this.machineFileService.lambdaQuery().eq(MachineFile::getDirType,dirType)
|
.eq(MachineFile::getMachineCode,machine.getCode()).list();
|
|
String basePath = MachineFileService.getBasePath(machine,dirType);
|
if(basePath == null) {
|
log.warn("目录类型不匹配:{}",dirType);
|
return;
|
}
|
Path dirPath = Paths.get(basePath);
|
if(!dirPath.toFile().exists()){
|
log.warn("扫描目录:{} 不存在",dirPath);
|
return;
|
}
|
|
List<Path> files = Files.list(dirPath)
|
.filter(Files::isRegularFile).toList();
|
|
for(MachineFile mf : machineFiles){
|
long findCount = files.stream().filter(filePath -> filePath.toFile().getName().equals(mf.getName())).count();
|
if(findCount == 0){
|
//文件夹内没找到,需要删除记录
|
mf.markFileDeleted();
|
this.machineFileService.updateById(mf);
|
}
|
}
|
}
|
}
|