This commit is contained in:
s2042968 2025-01-07 09:38:03 +08:00
commit d0187511bc
23 changed files with 129 additions and 1303 deletions

View File

@ -40,8 +40,7 @@ public class LoginInterceptor implements HandlerInterceptor {
private boolean checkSysAdminOperation(HttpServletRequest request) {
String requestURI = request.getRequestURI();
if (!requestURI.startsWith("/data/ed/prj")) {
// 校验当前用户是不是系统管理员再进行后续权限校验
return true;
return UserThreadLocal.getAdminType().equals(AdminTypeEnum.SYSTEM.getValue());
}
return true;
}

View File

@ -1,27 +0,0 @@
package com.electromagnetic.industry.software.manage.controller;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.manage.service.CategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RequestMapping("/data/ed/category")
@RestController
public class CategoryController {
@Resource
private CategoryService categoryService;
/**
* 目录树查询
*/
@ApiOperation(value = "目录树查询", notes = "")
@RequestMapping(value = "/tree", method = RequestMethod.GET)
public ElectromagneticResult<?> categoryTree() {
return categoryService.getAllCategories();
}
}

View File

@ -1,106 +0,0 @@
package com.electromagnetic.industry.software.manage.controller;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.manage.pojo.req.EDDataRequest;
import com.electromagnetic.industry.software.manage.pojo.req.FileChunkDTO;
import com.electromagnetic.industry.software.manage.service.EDDataService;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
@RequestMapping("/data1/ed/file")
@RestController
public class EDDataController {
@Resource
private EDDataService edDataService;
@ApiOperation(value = "新建文件夹", notes = "")
@RequestMapping(value = "/createFolder", method = RequestMethod.POST)
public ElectromagneticResult<?> createFolder(@RequestBody EDDataRequest request) {
return edDataService.createFolder(request);
}
@ApiOperation(value = "获取文件信息列表", notes = "")
@RequestMapping(value = "/getFileInfoList", method = RequestMethod.POST)
public ElectromagneticResult<?> getFileInfoList(@RequestBody EDDataRequest request) {
return edDataService.getDataInfoList(request);
}
@ApiOperation(value = "更新文件信息", notes = "")
@RequestMapping(value = "/updateFileInfo", method = RequestMethod.POST)
public ElectromagneticResult<?> updateFileInfo(@RequestBody EDDataRequest request) {
return edDataService.updateFileInfo(request);
}
@ApiOperation(value = "获取子文件数量", notes = "")
@RequestMapping(value = "/getChildFileCount", method = RequestMethod.POST)
public ElectromagneticResult<?> getChildFileCount(@RequestBody EDDataRequest request) {
return edDataService.getChildFileCount(request);
}
@ApiOperation(value = "上传", notes = "")
@RequestMapping(value = "/upload", consumes = "multipart/form-data", method = RequestMethod.POST)
public ElectromagneticResult<?> upload(@RequestParam("parentId") String parentId,
@RequestParam("file") MultipartFile file,
@RequestParam("gmtBatchUpload") Long gmtBatchUpload) {
EDDataRequest request = new EDDataRequest();
request.setParentId(parentId);
request.setFileData(file);
request.setGmtBatchUpload(new Date(gmtBatchUpload));
return edDataService.uploadFile(request);
}
@ApiOperation(value = "下载", notes = "")
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(@RequestParam String dataId, HttpServletResponse response) throws IOException {
return edDataService.download(dataId, response);
}
@ApiOperation(value = "数据导出", notes = "")
@RequestMapping(value = "/batchExport", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> batchExport(@RequestParam String dataIdArr, HttpServletResponse response) throws IOException {
return edDataService.batchExport(dataIdArr, response);
}
@ApiOperation(value = "获取已经上传的分片", notes = "")
@RequestMapping(value = "/getUploadedChunkNums", method = RequestMethod.GET)
public ElectromagneticResult<?> getUploadedChunkNums(@RequestParam String identifier) {
return edDataService.getUploadedChunkNums(identifier);
}
@ApiOperation(value = "合并分片", notes = "")
@RequestMapping(value = "/mergeChunks", method = RequestMethod.GET)
public ElectromagneticResult<?> mergeChunks(@RequestParam String identifier,
@RequestParam String fileName,
@RequestParam Integer totalChunks) {
return edDataService.mergeChunks(identifier, fileName, totalChunks);
}
@ApiOperation(value = "分片上传", notes = "")
@RequestMapping(value = "/batchImport", method = RequestMethod.POST)
public ElectromagneticResult<?> batchImport(FileChunkDTO fileChunkDTO) {
return edDataService.batchImport(fileChunkDTO);
}
@ApiOperation(value = "检查分片是否存在", notes = "")
@RequestMapping(value = "/batchImport", method = RequestMethod.GET)
public ElectromagneticResult<?> checkChunkExist(FileChunkDTO fileChunkDTO) {
return edDataService.checkChunkExist(fileChunkDTO);
}
}

View File

@ -4,7 +4,6 @@ import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.common.util.ElectromagneticResultUtil;
import com.electromagnetic.industry.software.manage.pojo.models.EdFileRelation;
import com.electromagnetic.industry.software.manage.pojo.req.CheckNameUniqueRequest;
import com.electromagnetic.industry.software.manage.service.EdFileInfoService;
import com.electromagnetic.industry.software.manage.service.EdFileRelationService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@ -20,37 +19,39 @@ public class EdFileRelationController {
/**
* 创建文件关系
*
* @param relation
* @return
*/
@RequestMapping (value = "/create", method = RequestMethod.POST)
public ElectromagneticResult<?> createRelation (@RequestBody EdFileRelation relation) {
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ElectromagneticResult<?> createRelation(@RequestBody EdFileRelation relation) {
return ElectromagneticResultUtil.success(edFileRelationService.createRelation(relation));
}
/**
* 取消文件关系
*
* @param relationId 关系主键id
* @return
*/
@RequestMapping (value = "/cancel/{relationId}", method = RequestMethod.GET)
public ElectromagneticResult<?> cancelRelation (@PathVariable("relationId") String relationId) {
@RequestMapping(value = "/cancel/{relationId}", method = RequestMethod.GET)
public ElectromagneticResult<?> cancelRelation(@PathVariable("relationId") String relationId) {
return ElectromagneticResultUtil.success(edFileRelationService.cancelRelation(relationId));
}
/**
* 展示文件关系
*/
@RequestMapping (value = "listRelations/{id}", method = RequestMethod.GET)
public ElectromagneticResult<?> listRelations (@PathVariable("id") String id) {
@RequestMapping(value = "listRelations/{id}", method = RequestMethod.GET)
public ElectromagneticResult<?> listRelations(@PathVariable("id") String id) {
return ElectromagneticResultUtil.success(edFileRelationService.listRelations(id));
}
/**
* 检验文件名是否唯一
*/
@RequestMapping (value = "/checkFileNameExist", method = RequestMethod.POST)
public ElectromagneticResult<?> checkFileNameExist (@RequestBody CheckNameUniqueRequest checkNameUniqueRequest) {
@RequestMapping(value = "/checkFileNameExist", method = RequestMethod.POST)
public ElectromagneticResult<?> checkFileNameExist(@RequestBody CheckNameUniqueRequest checkNameUniqueRequest) {
String fileName = checkNameUniqueRequest.getFileName();
String parentId = checkNameUniqueRequest.getParentId();
return ElectromagneticResultUtil.success(edFileRelationService.checkNameUnique(parentId, fileName));
@ -59,11 +60,11 @@ public class EdFileRelationController {
/**
* 本地上传并建立关系
*/
@RequestMapping (value="/upload", method = RequestMethod.POST)
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ElectromagneticResult<?> uploadRelation(@RequestParam("parentId") String parentId,
@RequestParam("file") MultipartFile file,
@RequestParam("description") String description,
@RequestParam("id") String id){
return ElectromagneticResultUtil.success(edFileRelationService.uploadFileAndRelation(parentId,id,file,description));
@RequestParam("id") String id) {
return ElectromagneticResultUtil.success(edFileRelationService.uploadFileAndRelation(parentId, id, file, description));
}
}

View File

@ -2,6 +2,7 @@ package com.electromagnetic.industry.software.manage.controller;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.manage.pojo.req.FolderResortDTO;
import com.electromagnetic.industry.software.manage.pojo.req.QueryPublishStatus;
import com.electromagnetic.industry.software.manage.service.EdPrjService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
@ -68,4 +69,9 @@ public class ProjectController {
public ElectromagneticResult<?> follow(@RequestParam String sourceId, @RequestParam String targetId) {
return edPrjService.follow(sourceId, targetId);
}
@RequestMapping("publishStatus")
public ElectromagneticResult<?> publishStatus(@RequestBody QueryPublishStatus queryPublishStatus) {
return edPrjService.publishStatus(queryPublishStatus);
}
}

View File

@ -7,7 +7,6 @@ import com.electromagnetic.industry.software.manage.pojo.req.RoleDTO;
import com.electromagnetic.industry.software.manage.pojo.req.RolePageDTO;
import com.electromagnetic.industry.software.manage.service.RoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@ -71,7 +70,7 @@ public class RoleController {
return ElectromagneticResultUtil.success(roleService.getAllRoleNames());
}
@ApiOperation(value="获得角色配置模版", notes = "")
@ApiOperation(value = "获得角色配置模版", notes = "")
@GetMapping(value = "/getRoleTemplate")
public ElectromagneticResult<?> getRoleTemplate() {
return ElectromagneticResultUtil.success(roleService.getRoleTemplate());

View File

@ -2,7 +2,6 @@ package com.electromagnetic.industry.software.manage.pojo.models;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

View File

@ -1,7 +1,6 @@
package com.electromagnetic.industry.software.manage.pojo.other;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Data;
import java.util.Date;

View File

@ -0,0 +1,10 @@
package com.electromagnetic.industry.software.manage.pojo.req;
import lombok.Data;
import java.util.List;
@Data
public class QueryPublishStatus {
private List<String> prjIds;
}

View File

@ -14,6 +14,6 @@ import java.util.List;
public class UploadRecordVO {
private long total;
List<UploadRecordDTO> records = new ArrayList<>();
private List<UploadRecordDTO> records = new ArrayList<>();
}

View File

@ -1,9 +0,0 @@
package com.electromagnetic.industry.software.manage.service;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
public interface CategoryService {
ElectromagneticResult<?> getAllCategories();
}

View File

@ -1,109 +0,0 @@
package com.electromagnetic.industry.software.manage.service;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.manage.pojo.req.EDDataRequest;
import com.electromagnetic.industry.software.manage.pojo.req.FileChunkDTO;
import com.electromagnetic.industry.software.manage.pojo.req.FileChunkResultDTO;
import com.electromagnetic.industry.software.manage.pojo.resp.EDDataPageResponse;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public interface EDDataService {
/**
* 创建文件夹
*
* @param request
* @return
*/
ElectromagneticResult<Boolean> createFolder(EDDataRequest request);
/**
* 获取文件信息列表
*
* @param request
* @return
*/
ElectromagneticResult<EDDataPageResponse> getDataInfoList(EDDataRequest request);
/**
* 更新文件信息
*
* @param request
* @return
*/
ElectromagneticResult<Boolean> updateFileInfo(EDDataRequest request);
/**
* 获取子文件数量
*
* @param request
* @return
*/
ElectromagneticResult<Map<String, Integer>> getChildFileCount(EDDataRequest request);
/**
* 上传
*
* @param request
* @return
*/
ElectromagneticResult<Boolean> uploadFile(EDDataRequest request);
/**
* 下载
*
* @param dataId
* @return
*/
ResponseEntity<InputStreamResource> download(String dataId, HttpServletResponse response) throws IOException;
/**
* 导出数据
*
* @param dataIdArr
* @return
*/
ResponseEntity<InputStreamResource> batchExport(String dataIdArr, HttpServletResponse response) throws IOException;
/**
* 导入数据
*
* @param fileChunkDTO
* @return
*/
ElectromagneticResult<?> batchImport(FileChunkDTO fileChunkDTO);
/**
* 获取已经上传的分片
*
* @param identifier
* @return
*/
ElectromagneticResult<List<Integer>> getUploadedChunkNums(String identifier);
/**
* 合并分片
*
* @param identifier
* @param fileName
* @param totalChunks
* @return
*/
ElectromagneticResult<?> mergeChunks(String identifier, String fileName, Integer totalChunks);
/**
* 检查分片是否存在
*
* @param fileChunkDTO
* @return
*/
ElectromagneticResult<FileChunkResultDTO> checkChunkExist(FileChunkDTO fileChunkDTO);
}

View File

@ -7,7 +7,6 @@ import com.electromagnetic.industry.software.manage.pojo.req.FileInfoQueryDTO;
import com.electromagnetic.industry.software.manage.pojo.req.UpdateFileInfoDTO;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
@ -141,12 +140,14 @@ public interface EdFileInfoService {
/**
* 发布管理
*
* @return
*/
ElectromagneticResult<?> uploadRecord(int pageNum, int pageSize);
/**
* 查询文件详情
*
* @param id
* @return
*/

View File

@ -9,6 +9,7 @@ public interface EdFileRelationService {
/**
* 创建文件关系
*
* @param edFileRelation
* @return
*/
@ -16,20 +17,23 @@ public interface EdFileRelationService {
/**
* 取消文件关系
*
* @param id
* @return
*/
Boolean cancelRelation (String id);
Boolean cancelRelation(String id);
/**
* 获取关系展示数据
*
* @param id
* @return
*/
FileRelationViewVO listRelations (String id);
FileRelationViewVO listRelations(String id);
/**
* 检查文件名是否唯一
*
* @param parentId
* @param fileName
* @return

View File

@ -2,6 +2,7 @@ package com.electromagnetic.industry.software.manage.service;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.manage.pojo.req.FolderResortDTO;
import com.electromagnetic.industry.software.manage.pojo.req.QueryPublishStatus;
import java.util.List;
@ -88,4 +89,12 @@ public interface EdPrjService {
* @return
*/
ElectromagneticResult<?> modifyFolder(String id, String newFolderName);
/**
* 获取项目的发布状态
*
* @param queryPublishStatus
* @return
*/
ElectromagneticResult<?> publishStatus(QueryPublishStatus queryPublishStatus);
}

View File

@ -1,85 +0,0 @@
package com.electromagnetic.industry.software.manage.service.serviceimpl;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.common.util.ElectromagneticResultUtil;
import com.electromagnetic.industry.software.manage.mapper.CategoryMapper;
import com.electromagnetic.industry.software.manage.pojo.models.Category;
import com.electromagnetic.industry.software.manage.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class CategoryServiceImpl implements CategoryService {
@Resource
private CategoryMapper categoryMapper;
@Override
public ElectromagneticResult<?> getAllCategories() {
List<Category> categories = categoryMapper.selectAllCategories();
List<Category> returnList = new ArrayList<>();
List<String> tempList = categories.stream().map(Category::getCategoryId).collect(Collectors.toList());
for (Category category : categories) {
if (!tempList.contains(category.getParentId())) {
recursionFn(categories, category);
returnList.add(category);
}
}
if (returnList.isEmpty()) {
returnList = categories;
}
return ElectromagneticResultUtil.success(returnList);
}
/**
* 递归列表
*
* @param list
* @param category
*/
private void recursionFn(List<Category> list, Category category) {
List<Category> childList = getChildList(list, category);
category.setChildren(childList);
for (Category child : childList) {
if (hasChild(list, child)) {
recursionFn(list, child);
}
}
}
/**
* 得到子节点列表
*
* @param list
* @param category
* @return
*/
private List<Category> getChildList(List<Category> list, Category category) {
List<Category> childList = new ArrayList<>();
Iterator<Category> it = list.iterator();
while (it.hasNext()) {
Category child = it.next();
if (!StringUtils.isEmpty(child.getParentId()) && child.getParentId().equals(category.getCategoryId())) {
childList.add(child);
}
}
return childList;
}
/**
* 判断是否有子节点
*
* @param list
* @param category
* @return
*/
private boolean hasChild(List<Category> list, Category category) {
return !getChildList(list, category).isEmpty();
}
}

View File

@ -1,899 +0,0 @@
package com.electromagnetic.industry.software.manage.service.serviceimpl;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.electromagnetic.industry.software.common.cons.ElectromagneticConstants;
import com.electromagnetic.industry.software.common.resp.ElectromagneticResult;
import com.electromagnetic.industry.software.common.util.EleCommonUtil;
import com.electromagnetic.industry.software.common.util.ElectromagneticResultUtil;
import com.electromagnetic.industry.software.common.util.IdWorker;
import com.electromagnetic.industry.software.common.util.UserThreadLocal;
import com.electromagnetic.industry.software.manage.mapper.CategoryMapper;
import com.electromagnetic.industry.software.manage.mapper.EDDataMapper;
import com.electromagnetic.industry.software.manage.mapper.EDDataMappers;
import com.electromagnetic.industry.software.manage.pojo.models.Category;
import com.electromagnetic.industry.software.manage.pojo.models.EDDataInfo;
import com.electromagnetic.industry.software.manage.pojo.other.EDDataPage;
import com.electromagnetic.industry.software.manage.pojo.other.EDDataParams;
import com.electromagnetic.industry.software.manage.pojo.req.EDDataRequest;
import com.electromagnetic.industry.software.manage.pojo.req.FileChunkDTO;
import com.electromagnetic.industry.software.manage.pojo.req.FileChunkResultDTO;
import com.electromagnetic.industry.software.manage.pojo.resp.EDDataPageResponse;
import com.electromagnetic.industry.software.manage.service.EDDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
public class EDDataServiceImpl implements EDDataService {
private static final String UPLOAD_FILE_CHUNK_SUFFIX = ".part";
// 文件夹名称分隔符
private static final String FOLDER_NAME_SEPARATOR = "_";
@Resource
private EDDataMapper edDataMapper;
@Resource
private CategoryMapper categoryMapper;
// @Value("${data.windows.path}")
private String uploadFilePath;
// @Value("${data.file.storage.dir}")
private String fileStorageDir;
// @Value("${data.import.cache.dir}")
private String importCacheDir;
// @Value("${file.encode.passwd}")
private String encodePasswd;
// @Value("${data.type.folder}")
private String dataTypeFolder;
// @Value("${data.windows.path}")
private String windowsDir;
// @Value("${data.file.cache.dir}")
private String fileCacheDir;
// @Value("${data.upload.cache.dir}")
private String uploadCacheDir;
// @Value("${data.export.cache.dir}")
private String exportCacheDir;
// @Value("${data.type.file}")
private String dataTypeFile;
@Override
public ElectromagneticResult<Boolean> createFolder(EDDataRequest request) {
EDDataInfo edDataInfo = EDDataMappers.INSTANCE.getEDDataInfo(request);
edDataInfo.setCreator(UserThreadLocal.getUserId());
edDataInfo.setCreatorName(UserThreadLocal.getUsername());
edDataInfo.setModifier(UserThreadLocal.getUserId());
edDataInfo.setModifierName(UserThreadLocal.getUsername());
edDataInfo.setCategoryId(request.getParentId());
edDataInfo.setDataName(request.getName());
edDataInfo.setNote(request.getNote());
edDataInfo.setGmtBatchUpload(new Date());
edDataInfo.setDataId(IdWorker.getSnowFlakeIdString());
edDataInfo.setDataNo(edDataInfo.getDataId());
edDataInfo.setDataType(dataTypeFolder);
edDataInfo.setVersion("1.0.0");
edDataInfo.setDataStatus("publish");
edDataInfo.setSaveStatus("success");
try {
return ElectromagneticResultUtil.success(createDataInfo(edDataInfo));
} catch (Exception e) {
log.error("创建文件夹失败。。。", e);
return ElectromagneticResultUtil.fail("500", e.getMessage());
}
}
public Boolean createDataInfo(EDDataInfo edDataInfo) throws Exception {
// 获取上级目录的名称
String fileName = edDataInfo.getDataName();
Assert.isTrue(EleCommonUtil.isFileNameValid(fileName), ElectromagneticConstants.NAME_VALID_MSG);
Category categoryParent = new Category();
categoryParent.setCategoryId(edDataInfo.getCategoryId());
List<Category> categoryParentList = categoryMapper.selectCategories(categoryParent);
if (categoryParentList.size() < 1) {
throw new Exception("上级文件夹不存在");
} else {
// 获取新文件夹路径信息
categoryParent = categoryParentList.get(0);
String dataStoragePath = getDataStoragePath();
String folderParent = categoryParent.getCategoryId() + FOLDER_NAME_SEPARATOR + categoryParent.getCategoryName();
String folderNew = dataStoragePath + File.separator + folderParent + File.separator + edDataInfo.getDataName();
// 判断文件夹名称是否存在
EDDataParams folderParames = new EDDataParams();
folderParames.setParentId(edDataInfo.getCategoryId());
List<EDDataInfo> childFileInfoList = edDataMapper.getDataInfoList(folderParames);
for (EDDataInfo fileInfo : childFileInfoList) {
if (fileInfo.getDataName().equals(edDataInfo.getDataName())) {
throw new Exception("文件夹已存在");
}
}
// 将文件夹数据写到数据库中
if (edDataMapper.createDataInfo(edDataInfo)) {
if (!FileUtil.exist(folderNew)) {
FileUtil.mkdir(folderNew);
}
}
}
return Boolean.TRUE;
}
/**
* 获取数据存储目录
*
* @return
*/
public String getDataStoragePath() {
String osName = System.getProperty("os.name").toLowerCase();
return osName.startsWith("win") ? windowsDir + fileStorageDir : fileStorageDir;
}
@Override
public ElectromagneticResult<EDDataPageResponse> getDataInfoList(EDDataRequest request) {
EDDataParams parames = EDDataMappers.INSTANCE.getEDDataParames(request);
//获取中支指标配置列表
PageHelper.startPage(parames.getPageIndex(), parames.getPageSize());
List<EDDataInfo> edDataInfoList = edDataMapper.getDataInfoList(parames);
PageInfo<EDDataInfo> pageInfo = new PageInfo<>(edDataInfoList);
EDDataPage edDataPage = new EDDataPage();
edDataPage.setEdDataInfo(pageInfo);
//模型转换
EDDataPageResponse edDataPageResponse = EDDataMappers.INSTANCE.getEDDataInfoToModel(edDataPage);
return ElectromagneticResultUtil.success(edDataPageResponse);
}
@Override
public ElectromagneticResult<Boolean> updateFileInfo(EDDataRequest request) {
try {
EDDataParams parames = EDDataMappers.INSTANCE.getEDDataParames(request);
parames.setUserId(UserThreadLocal.getUserId());
parames.setUserName(UserThreadLocal.getUsername());
return ElectromagneticResultUtil.success(updateFileInfo(parames));
} catch (Exception e) {
log.error("文件信息更新失败。。。", e);
return ElectromagneticResultUtil.fail("500", e.getMessage());
}
}
public Boolean updateFileInfo(EDDataParams parames) throws Exception {
String dataStoragePath = getDataStoragePath();
if (!FileUtil.exist(dataStoragePath)) {
throw new Exception("数据存储文件夹不存在");
}
EDDataParams paramesFind = new EDDataParams();
paramesFind.setDataId(parames.getDataId());
List<EDDataInfo> edDataInfoList = edDataMapper.getDataInfoList(paramesFind);
if (edDataInfoList.size() < 1) {
throw new Exception("文件信息不存在");
}
EDDataInfo edDataInfo = edDataInfoList.get(0);
String filePathOfFolder = getFilePathOfFolder(edDataInfo.getCategoryId());
String fileType = StrUtil.isEmpty(edDataInfo.getFileType()) ? "" : "." + edDataInfo.getFileType();
String fileStorageFullPath = dataStoragePath + filePathOfFolder + File.separator + edDataInfo.getDataName() + fileType;
if (!FileUtil.exist(fileStorageFullPath)) {
throw new Exception("文件不存在");
}
String fileNameNew = parames.getName() + fileType;
if (fileNameNew != null && fileNameNew != "" && !fileNameNew.equals(edDataInfo.getDataName())) {
FileUtil.rename(Paths.get(fileStorageFullPath), fileNameNew, true);
}
// 修改文件夹
edDataMapper.updateFileInfo(parames);
// 修改文件夹中的文件
if (edDataInfo.getDataType().equals(dataTypeFolder) && parames.getEffectFlag() != null) {
EDDataParams paramesChild = new EDDataParams();
paramesChild.setParentId(edDataInfo.getDataId());
paramesChild.setEffectFlag(parames.getEffectFlag());
edDataMapper.updateFileInfo(paramesChild);
}
return Boolean.TRUE;
}
public String getFilePathOfFolder(String categoryId) {
String filePathOfFolder = ""; //文件存放在文件夹的路径
String categoryIdHighest = categoryId; //最高级的目录编码
EDDataParams folderParames = new EDDataParams();
folderParames.setDataId(categoryId);
List<EDDataInfo> edDataInfoList = edDataMapper.getDataInfoList(folderParames);
EDDataInfo edDataInfoParent = null;
if (CollUtil.isNotEmpty(edDataInfoList)) {
categoryIdHighest = edDataInfoList.get(0).getCategoryId();
edDataInfoParent = edDataInfoList.get(0);
}
Category categoryParent = new Category();
categoryParent.setCategoryId(categoryIdHighest);
List<Category> categoryParentList = categoryMapper.selectCategories(categoryParent);
if (categoryParentList.size() > 0) {
categoryParent = categoryParentList.get(0);
filePathOfFolder = categoryParent.getCategoryId() + FOLDER_NAME_SEPARATOR + categoryParent.getCategoryName();
if (edDataInfoParent != null) {
String fileType = StrUtil.isEmpty(edDataInfoParent.getFileType()) ? "" : "." + edDataInfoParent.getFileType();
filePathOfFolder = filePathOfFolder + File.separator + edDataInfoParent.getDataName() + fileType;
}
}
return filePathOfFolder;
}
@Override
public ElectromagneticResult<Map<String, Integer>> getChildFileCount(EDDataRequest request) {
EDDataParams parames = EDDataMappers.INSTANCE.getEDDataParames(request);
Integer fileCount = getChildFileCount(parames);
Map<String, Integer> result = new HashMap<>();
result.put("fileCount", fileCount);
return ElectromagneticResultUtil.success(result);
}
public Integer getChildFileCount(EDDataParams parames) {
Integer childFileCount = 0;
List<EDDataInfo> edDataInfoList = edDataMapper.getDataInfoList(parames);
parames.setDataId(null);
for (EDDataInfo edDataInfo : edDataInfoList) {
if (edDataInfo.getDataType().equals(dataTypeFolder)) {
parames.setParentId(edDataInfo.getDataId());
childFileCount += getChildFileCount(parames);
} else if (edDataInfo.getDataType().equals(dataTypeFile) && edDataInfo.getEffectFlag().equals(1)) {
++childFileCount;
}
}
return childFileCount;
}
@Override
public ElectromagneticResult<Boolean> uploadFile(EDDataRequest request) {
try {
EDDataParams parames = EDDataMappers.INSTANCE.getEDDataParames(request);
parames.setUserId(UserThreadLocal.getUserId());
parames.setUserName(UserThreadLocal.getUsername());
return ElectromagneticResultUtil.success(upload(parames));
} catch (Exception e) {
log.error("上传文件失败。。。", e);
return ElectromagneticResultUtil.fail("500", e.getMessage());
}
}
private Boolean upload(EDDataParams parames) throws Exception {
// 获取目录编码ID
String categoryId = parames.getParentId();
// 获取要上传的文件
MultipartFile fileInput = parames.getFileData();
// 检查文件是否为空
if (fileInput == null || fileInput.isEmpty()) {
throw new Exception("上传的文件为空");
}
// 获取文件名
String fileFullName = fileInput.getOriginalFilename();
// 获取文件类型
String fileType = EleCommonUtil.getFileType(fileFullName);
// 获取文件名称
String fileName = EleCommonUtil.getFileName(fileFullName);
Assert.isTrue(EleCommonUtil.isFileNameValid(fileName), ElectromagneticConstants.NAME_VALID_MSG);
// 判断文件名称是否存在
EDDataParams folderParames = new EDDataParams();
folderParames.setParentId(categoryId);
List<EDDataInfo> childFileInfoList = edDataMapper.getDataInfoList(folderParames);
for (EDDataInfo fileInfo : childFileInfoList) {
if (fileInfo.getDataName().equals(fileFullName)) {
throw new Exception("上传的文件已存在");
}
}
String dataStoragePath = getDataStoragePath();
if (!FileUtil.exist(dataStoragePath)) {
FileUtil.mkdir(dataStoragePath);
}
//获取文件存放在文件夹的路径
String filePathOfFolder = getFilePathOfFolder(categoryId);
// 将文件数据信息写到数据库
EDDataInfo edDataInfo = new EDDataInfo();
// 创建新文件数据
edDataInfo.setCreator(parames.getUserId());
edDataInfo.setCreatorName(parames.getUserName());
edDataInfo.setModifier(parames.getUserId());
edDataInfo.setModifierName(parames.getUserName());
edDataInfo.setCategoryId(parames.getParentId());
edDataInfo.setDataName(fileName);
edDataInfo.setNote(parames.getNote());
edDataInfo.setFileType(fileType);
edDataInfo.setGmtBatchUpload(parames.getGmtBatchUpload());
edDataInfo.setDataId(IdWorker.getSnowFlakeIdString());
edDataInfo.setDataNo(edDataInfo.getDataId());
edDataInfo.setDataType(dataTypeFile);
edDataInfo.setVersion("1.0.0");
edDataInfo.setDataStatus("publish");
edDataInfo.setSaveStatus("saving");
boolean isSuccess = edDataMapper.createDataInfo(edDataInfo);
log.info("文件开始保存.");
// 保存文件数据 文件存储目录
// 文件保存目录路径
String fileSavePath = dataStoragePath + File.separator + filePathOfFolder;
String newFileName = edDataInfo.getDataId() + FOLDER_NAME_SEPARATOR + fileFullName;
if (!FileUtil.exist(fileSavePath)) {
FileUtil.mkdir(fileSavePath);
}
String dataCachePath = getDataCachePath();
String uploadFileCachePath = dataCachePath + uploadCacheDir + FOLDER_NAME_SEPARATOR + getTimeStampString();
if (!FileUtil.exist(uploadFileCachePath)) {
FileUtil.mkdir(uploadFileCachePath);
}
String fileCacheFullPath = uploadFileCachePath + File.separator + newFileName;
String fileSaveFullPath = fileSavePath + File.separator + fileFullName;
log.info("文件缓存路径为: " + fileCacheFullPath);
// 这里可以添加将文件保存到本地磁盘或其他存储介质的逻辑
File saveFile = new File(fileCacheFullPath);
// 将文件保存到硬盘
EDDataParams fileParames = new EDDataParams();
try {
fileInput.transferTo(saveFile);
fileParames.setDataId(edDataInfo.getDataId());
if (fileInput.getSize() == saveFile.length()) {
Path source = Paths.get(fileCacheFullPath);
Path target = Paths.get(fileSaveFullPath);
Files.move(source, target);
fileParames.setSaveStatus("success");
} else {
saveFile.delete();
fileParames.setSaveStatus("failure");
}
isSuccess = edDataMapper.updateFileInfo(fileParames);
FileUtil.del(uploadFileCachePath);//删除临时目录
log.info("文件保存成功: " + fileSaveFullPath);
return Boolean.TRUE;
} catch (IOException e) {
fileParames.setSaveStatus("failure");
edDataMapper.updateFileInfo(fileParames);
log.info("文件保存失败: " + fileSaveFullPath);
throw new Exception(e.getMessage());
}
}
/**
* 获取时间戳字符串
*
* @return
*/
public String getTimeStampString() {
long timestamp = System.currentTimeMillis();
return String.valueOf(timestamp);
}
/**
* 获取数据缓存目录
*
* @return
*/
public String getDataCachePath() {
String osName = System.getProperty("os.name").toLowerCase();
return osName.startsWith("win") ? windowsDir + fileCacheDir : fileCacheDir;
}
@Override
public ResponseEntity<InputStreamResource> download(String dataId, HttpServletResponse response) throws IOException {
// 获取文件存储的文件夹路径
String osName = System.getProperty("os.name").toLowerCase();
String storageFilePath = osName.startsWith("win") ? uploadFilePath + fileStorageDir : fileStorageDir;
EDDataParams parames = new EDDataParams();
parames.setDataId(dataId);
List<EDDataInfo> edDataInfos = edDataMapper.getDataInfoList(parames);
Assert.isTrue(CollUtil.isNotEmpty(edDataInfos), "没有找到该下载文件");
EDDataInfo edDataInfo = edDataInfos.get(0);
String filePathOfFolder = getFilePathOfFolder1(edDataInfo.getCategoryId());
String fileType = StrUtil.isEmpty(edDataInfo.getFileType()) ? "" : "." + edDataInfo.getFileType();
String filePath = storageFilePath + "/" + filePathOfFolder + "/" + edDataInfo.getDataName() + fileType;
Assert.isTrue(FileUtil.exist(filePath), "下载文件不存在。");
FileSystemResource fileSystemResource = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
String fileName = Base64.encode(fileSystemResource.getFilename());
response.setHeader("content-disposition", "attachment;filename=" + fileName);
// 构建响应实体(可以返回<byte[]或Resource返回类型取决body入参类型)
return ResponseEntity
.ok()
.headers(headers)
.contentLength(fileSystemResource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream;charset=UTF-8"))
.body(new InputStreamResource(fileSystemResource.getInputStream()));
}
private String getFilePathOfFolder1(String categoryId) {
String filePathOfFolder = ""; //文件存放在文件夹的路径
String categoryIdHighest = categoryId; //最高级的目录编码
EDDataParams folderParames = new EDDataParams();
folderParames.setDataId(categoryId);
List<EDDataInfo> edDataInfoList = edDataMapper.getDataInfoList(folderParames);
EDDataInfo edDataInfoParent = null;
if (CollUtil.isNotEmpty(edDataInfoList)) {
categoryIdHighest = edDataInfoList.get(0).getCategoryId();
edDataInfoParent = edDataInfoList.get(0);
}
Category categoryParent = new Category();
categoryParent.setCategoryId(categoryIdHighest);
List<Category> categoryParentList = categoryMapper.selectCategories(categoryParent);
if (categoryParentList.size() > 0) {
categoryParent = categoryParentList.get(0);
filePathOfFolder = categoryParent.getCategoryId() + FOLDER_NAME_SEPARATOR + categoryParent.getCategoryName();
if (edDataInfoParent != null) {
String fileType = StrUtil.isEmpty(edDataInfoParent.getFileType()) ? "" : "." + edDataInfoParent.getFileType();
filePathOfFolder = filePathOfFolder + File.separator + edDataInfoParent.getDataName() + fileType;
}
}
return filePathOfFolder;
}
@Override
public ResponseEntity<InputStreamResource> batchExport(String dataIdArr, HttpServletResponse response) throws IOException {
//1根据用户选择层级树编码查出所有文件和文件夹list
//2循环list将每个文件复制到新建目录并进行重命名命名规则目录树编码+,+文件夹编码有则填写无则为空+,+文件编码
//3打包新建为zip并根据生产下载地址域名+文件路径+文件
//4返回前端下载的地址
// **********在导出的过程中可能会出现有用户上传文件的情况
Map<String, String> result = new HashMap<>();
List<String> dataIdList = Arrays.asList(dataIdArr.split(","));
if (!dataIdList.isEmpty()) {
String filePath = exportData(dataIdList);
Assert.isTrue(FileUtil.exist(filePath), "下载文件不存在。");
File file = new File(filePath);
FileSystemResource fileSystemResource = new FileSystemResource(file);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
String fileName = Base64.encode(fileSystemResource.getFilename());
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
response.setHeader("content-disposition", "attachment;filename=" + fileName);
// 构建响应实体(可以返回<byte[]或Resource返回类型取决body入参类型)
return ResponseEntity
.ok()
.headers(headers)
.contentLength(fileSystemResource.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(fileSystemResource.getInputStream()));
}
return null;
}
public String exportData(List<String> dataIdList) {
String zipPathFileName = "";
String exportDataCachePath = "";
String enCodeZipPathFileName = "";
try {
// 获取文件夹编码ID数组
List<String> categoryIdInputList = dataIdList;
String dataCachePath = getDataCachePath();
// 导出数据时的临时存放目录
exportDataCachePath = dataCachePath + exportCacheDir + FOLDER_NAME_SEPARATOR + getTimeStampString();
if (!FileUtil.exist(exportDataCachePath)) {
FileUtil.mkdir(exportDataCachePath);
}
List<Category> categoryAllList = categoryMapper.selectAllCategories();
Map<String, Category> categoryAllMap = new HashMap(); //所有目录数组map
for (Category category : categoryAllList) {
categoryAllMap.put(category.getCategoryId(), category);
}
EDDataParams folderParames = new EDDataParams();
List<EDDataInfo> fileAllList = edDataMapper.getDataInfoList(folderParames); //获取所有文件信息数据
Map<String, EDDataInfo> fileAllMap = new HashMap(); //所有文件数组map
for (EDDataInfo fileFinfo : fileAllList) {
fileAllMap.put(fileFinfo.getDataId(), fileFinfo);
}
List<Category> categoryInputList = new ArrayList(); //客户端输入的目录数组
Map<String, Category> categoryInputMap = new HashMap(); //客户端输入的目录数组map
for (String categoryId : categoryIdInputList) {
Category category = categoryAllMap.get(categoryId);
if (category != null) {
categoryInputList.add(category);
categoryInputMap.put(categoryId, category);
}
}
// 将List<Category>转换为JSON字符串
String jsonStringCategory = JSONUtil.toJsonStr(categoryInputList);
String categoryListFileFullPath = exportDataCachePath + "/categoryList.json";
FileUtil.writeString(jsonStringCategory, categoryListFileFullPath, "utf-8");
log.info("目录树数据已成功导出为JSON文件。" + categoryListFileFullPath);
// 导出文件信息数据和文件数据
List<EDDataInfo> fileExportList = new ArrayList(); //需要导出的文件信息数据数组
Map<String, EDDataInfo> fileExportMap = new HashMap(); //需要导出的文件信息数据数组map
for (EDDataInfo fileFinfo : fileAllList) {
if (categoryInputMap.get(fileFinfo.getCategoryId()) != null) {
fileExportList.add(fileFinfo);
fileExportMap.put(fileFinfo.getDataId(), fileFinfo);
}
}
// 找出子文件夹下的文件
for (EDDataInfo fileFinfo : fileAllList) {
if (fileExportMap.get(fileFinfo.getCategoryId()) != null) {
fileExportList.add(fileFinfo);
}
}
// 将文件信息数据导出为json文件
String jsonStringFile = JSONUtil.toJsonStr(fileExportList);
String fileListFileFullPath = exportDataCachePath + "/fileInfoList.json";
FileUtil.writeString(jsonStringFile, fileListFileFullPath, "utf-8");
log.info("文件数据已成功导出为JSON文件。" + fileListFileFullPath);
// 将文件 复制到 数据导出的缓存目录中
String dataStoragePath = getDataStoragePath();
String needExportfolder = "";
for (Category category : categoryInputList) {
needExportfolder = dataStoragePath + category.getCategoryId() + FOLDER_NAME_SEPARATOR + category.getCategoryName();
if (FileUtil.exist(needExportfolder)) {
Path source = Paths.get(needExportfolder);
Path target = Paths.get(exportDataCachePath);
FileUtil.copy(source, target); // StandardCopyOption.REPLACE_EXISTING
}
}
log.info("文件数据已成功复制到目标目录。");
// 将目录树数据 文件夹及文件夹内数据 进行压缩打包
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
String dateString = sdf.format(date);
zipPathFileName = dataCachePath + "/exportData_" + dateString;
enCodeZipPathFileName = dataCachePath + "/exportData_" + dateString + ElectromagneticConstants.EXPORT_FILE_SUFFIX;
ZipUtil.zip(exportDataCachePath, zipPathFileName);
AES aes = SecureUtil.aes(encodePasswd.getBytes()); // aesKey是加密密钥
try (
InputStream inputStream = new FileInputStream(zipPathFileName);
OutputStream outputStream = new FileOutputStream(enCodeZipPathFileName);
) {
aes.encrypt(inputStream, outputStream, true);
} catch (Exception e) {
log.error("文件加密错误..", e);
}
log.info("目录树数据+文件数据已成功复制到目标目录。" + enCodeZipPathFileName);
} catch (Exception e) {
log.error("导出数据异常..", e);
} finally {
// 删除 导出数据的 缓存目录
FileUtil.del(exportDataCachePath);
}
return enCodeZipPathFileName;
}
@Override
public ElectromagneticResult<?> batchImport(FileChunkDTO fileChunkDTO) {
String identifier = fileChunkDTO.getIdentifier();
String fileName = fileChunkDTO.getFileName();
String dataCachePath = getDataCachePath();
String importDataCachePath = dataCachePath + importCacheDir;
// 首先检查文件是否存在如果存在则不允许重复上传
String destZipPath = importDataCachePath + identifier + File.separator + fileName;
boolean existFile = FileUtil.exist(new File(destZipPath));
if (existFile) {
return ElectromagneticResultUtil.fail("-1", "文件已经存在,请勿重复上传。");
}
// 检查该分片有没被上传过
String destChunkPath = importDataCachePath + identifier + File.separator + fileChunkDTO.getChunkNumber() + UPLOAD_FILE_CHUNK_SUFFIX;
boolean existChunk = FileUtil.exist(new File(destChunkPath));
if (existChunk) {
return ElectromagneticResultUtil.success(true);
}
File dir = new File(importDataCachePath + identifier + File.separator);
if (!dir.exists()) {
dir.mkdir();
}
try (
InputStream inputStream = fileChunkDTO.getFile().getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(destChunkPath);
) {
IoUtil.copy(inputStream, fileOutputStream);
} catch (IOException ioException) {
log.error("上传文件错误...", ioException);
}
return ElectromagneticResultUtil.success(fileChunkDTO.getIdentifier());
}
@Override
public ElectromagneticResult<List<Integer>> getUploadedChunkNums(String identifier) {
return ElectromagneticResultUtil.success(getUploadedChunks(identifier));
}
private List<Integer> getUploadedChunks(String identifier) {
String dataCachePath = getDataCachePath();
String importDataCachePath = dataCachePath + importCacheDir;
String destPath = importDataCachePath + identifier;
if (!FileUtil.exist(new File(destPath))) {
return new ArrayList<>();
}
return FileUtil.listFileNames(destPath)
.stream()
.filter(e -> !e.endsWith(ElectromagneticConstants.EXPORT_FILE_SUFFIX))
.map(e -> e.replace(UPLOAD_FILE_CHUNK_SUFFIX, ""))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
@Override
public ElectromagneticResult<?> mergeChunks(String identifier, String fileName, Integer totalChunks) {
String dataCachePath = getDataCachePath();
String importDataCachePath = dataCachePath + importCacheDir;
// 检查所有分片是否已经上传完成分片编号从1开始
for (int i = 1; i <= totalChunks; i++) {
String tmpPath = importDataCachePath + identifier + File.separator + i + UPLOAD_FILE_CHUNK_SUFFIX;
if (!FileUtil.exist(new File(tmpPath))) {
log.error("第{}个分片没有上传完成,请上传完成后再合并。", i);
ElectromagneticResultUtil.fail("-1", "文件尚未上传完成。");
}
}
// 合并分片
String destZipPath = importDataCachePath + identifier + File.separator + fileName;
File mergedFile = new File(destZipPath);
try {
RandomAccessFile targetFile = new RandomAccessFile(mergedFile, "rw");
byte[] buffer = new byte[1024];
for (int i = 1; i <= totalChunks; i++) {
String tmpPath = importDataCachePath + identifier + File.separator + i + UPLOAD_FILE_CHUNK_SUFFIX;
RandomAccessFile tmp = new RandomAccessFile(new File(tmpPath), "r");
int len;
while ((len = tmp.read(buffer)) != -1) {
targetFile.write(buffer, 0, len);
}
tmp.close();
}
targetFile.close();
} catch (IOException ioException) {
ElectromagneticResultUtil.fail("-1", "文件合并失败");
}
// 删除分片
for (int i = 1; i <= totalChunks; i++) {
String tmpPath = importDataCachePath + identifier + File.separator + i + UPLOAD_FILE_CHUNK_SUFFIX;
FileUtil.del(tmpPath);
}
// 检验文件的MD5值
// 解密文件
String decryptFilePath = destZipPath + "_decrypted";
AES aes = SecureUtil.aes(encodePasswd.getBytes()); // aesKey是加密密钥
try (
InputStream inputStream = new FileInputStream(destZipPath);
OutputStream outputStream = new FileOutputStream(decryptFilePath);
) {
aes.decrypt(inputStream, outputStream, true);
} catch (Exception e) {
log.error("文件加密错误..", e);
}
// 解压文件
String unzipFileOutputPath = importDataCachePath + identifier + File.separator;
ZipUtil.unzip(decryptFilePath, unzipFileOutputPath);
// 文件信息存入数据库
Map<String, List<String>> result = importData(importDataCachePath + identifier);
// 删除 解压数据的 缓存目录
FileUtil.del(unzipFileOutputPath);
return ElectromagneticResultUtil.success(result);
}
public Map<String, List<String>> importData(String folderPath) {
// 获取所有目录树节点数据
List<Category> categoryAllList = categoryMapper.selectAllCategories();
Map<String, Category> categoryAllMap = new HashMap(); //所有目录数组map
for (Category category : categoryAllList) {
categoryAllMap.put(category.getCategoryId(), category);
}
// 获取所有文件信息数据
EDDataParams parames = new EDDataParams();
List<EDDataInfo> fileInfoAllList = edDataMapper.getDataInfoList(parames);
Map<String, EDDataInfo> fileInfoAllMap = new HashMap(); //所有文件数组map
for (EDDataInfo fileInfo : fileInfoAllList) {
fileInfoAllMap.put(fileInfo.getDataId(), fileInfo);
}
// 读取并反序列化目录树的JSON文件数据为List<Category>然后写入到数据库中
String jsonStringCategory = FileUtil.readString(folderPath + "/categoryList.json", StandardCharsets.UTF_8);
JSONArray jsonArrayCategory = JSONUtil.parseArray(jsonStringCategory);
List<Category> categoryImportList = JSONUtil.toList(jsonArrayCategory, Category.class);
if (categoryImportList == null) {
log.error("读取并反序列化JSON文件数据为List<Category>失败!");
return null;
}
// 将目录树数据写入到数据库中
for (Category category : categoryImportList) {
if (categoryAllMap.get(category.getCategoryId()) == null) {
categoryMapper.createCategory(category);
}
}
// 读取并反序列化文件信息的JSON文件数据为List<EDDataInfo>然后写入到数据库中
String jsonStringFile = FileUtil.readString(folderPath + "/fileInfoList.json", StandardCharsets.UTF_8);
JSONArray jsonArrayFile = JSONUtil.parseArray(jsonStringFile);
List<EDDataInfo> fileInfoImportList = JSONUtil.toList(jsonArrayFile, EDDataInfo.class);
if (fileInfoImportList == null) {
log.error("读取并反序列化JSON文件数据为List<EDDataInfo>失败!");
return null;
}
// 将文件信息数据写入到数据库中
for (EDDataInfo fileInfo : fileInfoImportList) {
if (fileInfoAllMap.get(fileInfo.getDataId()) == null) {
edDataMapper.createDataInfo(fileInfo);
}
}
// 将解压后的文件夹和文件 移动到 上传文件的存储目录中
List<String> importFileSuccess = new ArrayList();
List<String> importFileFail = new ArrayList();
String dataStoragePath = getDataStoragePath();
if (!FileUtil.exist(dataStoragePath)) {
FileUtil.mkdir(dataStoragePath);
}
String importDataCachePath = folderPath; //导入数据时 数据文件解压后的目录
String importFileCachePath = ""; //需要导入的文件的缓存路径
String importFileCacheFullPath = ""; //需要导入的文件的全路径
String fileStorageFolder = ""; //文件存储的文件夹
String fileStoragePath = ""; //文件存储的文件夹路径
String fileStorageFullPath = ""; //文件存储的文件全路径
for (EDDataInfo fileInfo : fileInfoImportList) {
fileStorageFolder = getFilePathOfFolder(fileInfo.getCategoryId());
importFileCachePath = importDataCachePath + File.separator + fileStorageFolder;
importFileCacheFullPath = importFileCachePath + File.separator + fileInfo.getDataName();
fileStoragePath = dataStoragePath + File.separator + fileStorageFolder;
fileStorageFullPath = fileStoragePath + File.separator + fileInfo.getDataName();
if (fileInfoAllMap.get(fileInfo.getDataId()) == null
&& !fileStorageFolder.isEmpty()
&& FileUtil.exist(importFileCachePath)
&& FileUtil.exist(importFileCacheFullPath)
&& !FileUtil.exist(fileStorageFullPath)
) {
if (fileInfo.getDataType().equals(dataTypeFolder)) {
if (!FileUtil.exist(fileStorageFullPath)) {
FileUtil.mkdir(fileStorageFullPath);
}
} else if (fileInfo.getDataType().equals(dataTypeFile)) {
Path source = Paths.get(importFileCacheFullPath);
Path target = Paths.get(fileStorageFullPath);
FileUtil.move(source, target, true);
}
importFileSuccess.add(fileInfo.getDataId() + FOLDER_NAME_SEPARATOR + fileInfo.getDataName());
} else {
importFileFail.add(fileInfo.getDataId() + FOLDER_NAME_SEPARATOR + fileInfo.getDataName());
}
}
Map<String, List<String>> result = new HashMap<>();
result.put("success", importFileSuccess);
result.put("fail", importFileFail);
return result;
}
@Override
public ElectromagneticResult<FileChunkResultDTO> checkChunkExist(FileChunkDTO fileChunkDTO) {
String dataCachePath = getDataCachePath();
String importDataCachePath = dataCachePath + importCacheDir;
// 首先判断zip文件是否存在如果不存在则表示还没有上传完成
String identifier = fileChunkDTO.getIdentifier();
String fileName = fileChunkDTO.getFileName();
String destZipPath = importDataCachePath + identifier + File.separator + fileName;
boolean existFile = FileUtil.exist(new File(destZipPath));
if (existFile) {
return ElectromagneticResultUtil.success(new FileChunkResultDTO(true, new HashSet<>()));
}
List<Integer> uploadedChunks = getUploadedChunks(identifier);
return ElectromagneticResultUtil.success(new FileChunkResultDTO(false, new HashSet<>(uploadedChunks)));
}
}

View File

@ -8,6 +8,7 @@ import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.crypto.SecureUtil;
@ -61,9 +62,9 @@ import static com.electromagnetic.industry.software.common.cons.ElectromagneticC
@Service
public class EdFileInfoServiceImpl extends ServiceImpl<EdFileInfoMapper, EdFileInfo> implements EdFileInfoService {
private final EleLog log = new EleLog(EdFileInfoServiceImpl.class);
@Resource
private CommonService commonService;
private final EleLog log = new EleLog(EdFileInfoServiceImpl.class);
@Resource
private FileSystemService fileSystemService;
@Resource
@ -91,46 +92,45 @@ public class EdFileInfoServiceImpl extends ServiceImpl<EdFileInfoMapper, EdFileI
/**
* 查询文件列表
*
* @param fileInfoQueryDTO
* @param pars
* @return
*/
@Override
public ElectromagneticResult<?> queryEdFileInfo(FileInfoQueryDTO fileInfoQueryDTO) {
public ElectromagneticResult<?> queryEdFileInfo(FileInfoQueryDTO pars) {
LambdaQueryWrapper<EdFileInfo> queryWrapper = Wrappers.lambdaQuery(EdFileInfo.class)
.select()
.eq(EdFileInfo::getSaveStatus, EleDataSaveStatusEnum.SUCCESS.code)
.eq(EdFileInfo::getEffectFlag, EffectFlagEnum.EFFECT.code)
.eq(EdFileInfo::getParentId, fileInfoQueryDTO.getParentId())
.eq(Objects.equals(fileInfoQueryDTO.getDataStatus(), EleDataStatusEnum.NOT_PUBLISHED.code), EdFileInfo::getDataStatus, EleDataStatusEnum.NOT_PUBLISHED.code)
.eq(Objects.equals(fileInfoQueryDTO.getDataStatus(), EleDataStatusEnum.PUBLISHED.code), EdFileInfo::getDataStatus, EleDataStatusEnum.PUBLISHED.code)
.eq(Objects.equals(fileInfoQueryDTO.getDataStatus(), EleDataStatusEnum.OCCUPY.code), EdFileInfo::getDataStatus, EleDataStatusEnum.OCCUPY.code)
.eq(StrUtil.isNotEmpty(fileInfoQueryDTO.getFileType()), EdFileInfo::getFileType, fileInfoQueryDTO.getFileType())
.eq(EdFileInfo::getParentId, pars.getParentId())
.eq(ObjUtil.equals(pars.getDataStatus(), EleDataStatusEnum.NOT_PUBLISHED.code), EdFileInfo::getDataStatus, EleDataStatusEnum.NOT_PUBLISHED.code)
.eq(ObjUtil.equals(pars.getDataStatus(), EleDataStatusEnum.PUBLISHED.code), EdFileInfo::getDataStatus, EleDataStatusEnum.PUBLISHED.code)
.eq(ObjUtil.equals(pars.getDataStatus(), EleDataStatusEnum.OCCUPY.code), EdFileInfo::getDataStatus, EleDataStatusEnum.OCCUPY.code)
.eq(StrUtil.isNotEmpty(pars.getFileType()), EdFileInfo::getFileType, pars.getFileType())
.like(StrUtil.isNotEmpty(fileInfoQueryDTO.getKeyword()), EdFileInfo::getFileName, fileInfoQueryDTO.getKeyword())
.like(StrUtil.isNotEmpty(fileInfoQueryDTO.getKeyword()), EdFileInfo::getFileNote, fileInfoQueryDTO.getKeyword())
.like(StrUtil.isNotEmpty(pars.getKeyword()), EdFileInfo::getFileName, pars.getKeyword())
.like(StrUtil.isNotEmpty(pars.getKeyword()), EdFileInfo::getFileNote, pars.getKeyword())
.orderByAsc(Objects.equals(fileInfoQueryDTO.getCreatedTime(), 0), EdFileInfo::getCreatedTime)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getCreatedTime(), 1), EdFileInfo::getCreatedTime)
.orderByAsc(ObjUtil.equals(pars.getCreatedTime(), 0), EdFileInfo::getCreatedTime)
.orderByDesc(ObjUtil.equals(pars.getCreatedTime(), 1), EdFileInfo::getCreatedTime)
.orderByDesc(ObjUtil.isAllEmpty(pars.getCreatedTime(), pars.getFileVersion(), pars.getFileSize(), pars.getFileNameSort(), pars.getUpdatedTime(), pars.getFileTypeSort()), EdFileInfo::getCreatedTime)
.orderByAsc(Objects.equals(fileInfoQueryDTO.getFileVersion(), 0), EdFileInfo::getFileVersion)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getFileVersion(), 1), EdFileInfo::getFileVersion)
.orderByAsc(ObjUtil.equals(pars.getFileVersion(), 0), EdFileInfo::getFileVersion)
.orderByDesc(ObjUtil.equals(pars.getFileVersion(), 1), EdFileInfo::getFileVersion)
.orderByAsc(Objects.equals(fileInfoQueryDTO.getFileSize(), 0), EdFileInfo::getFileSize)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getFileSize(), 1), EdFileInfo::getFileSize)
.orderByAsc(ObjUtil.equals(pars.getFileSize(), 0), EdFileInfo::getFileSize)
.orderByDesc(ObjUtil.equals(pars.getFileSize(), 1), EdFileInfo::getFileSize)
.orderByAsc(Objects.equals(fileInfoQueryDTO.getFileNameSort(), 0), EdFileInfo::getFileName)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getFileNameSort(), 1), EdFileInfo::getFileName)
.orderByAsc(ObjUtil.equals(pars.getFileNameSort(), 0), EdFileInfo::getFileName)
.orderByDesc(ObjUtil.equals(pars.getFileNameSort(), 1), EdFileInfo::getFileName)
.orderByAsc(Objects.equals(fileInfoQueryDTO.getUpdatedTime(), 0), EdFileInfo::getUpdatedTime)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getUpdatedTime(), 1), EdFileInfo::getUpdatedTime)
.orderByAsc(ObjUtil.equals(pars.getUpdatedTime(), 0), EdFileInfo::getUpdatedTime)
.orderByDesc(ObjUtil.equals(pars.getUpdatedTime(), 1), EdFileInfo::getUpdatedTime)
.orderByAsc(Objects.equals(fileInfoQueryDTO.getFileTypeSort(), 0), EdFileInfo::getFileType)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getFileTypeSort(), 1), EdFileInfo::getFileType)
.orderByAsc(ObjUtil.equals(pars.getFileTypeSort(), 0), EdFileInfo::getSort)
.orderByDesc(ObjUtil.equals(pars.getFileTypeSort(), 1), EdFileInfo::getSort);
.orderByAsc(Objects.equals(fileInfoQueryDTO.getCreatedTime(), 0), EdFileInfo::getCreatedTime)
.orderByDesc(Objects.equals(fileInfoQueryDTO.getCreatedTime(), 1), EdFileInfo::getCreatedTime);
Page<EdFileInfo> edFileInfoPage = this.baseMapper.selectPage(new Page<>(fileInfoQueryDTO.getPageNum(), fileInfoQueryDTO.getPageSize()), queryWrapper);
Page<EdFileInfo> edFileInfoPage = this.baseMapper.selectPage(new Page<>(pars.getPageNum(), pars.getPageSize()), queryWrapper);
long total = edFileInfoPage.getTotal();
List<FileInfoVO> records = BeanUtil.copyToList(edFileInfoPage.getRecords(), FileInfoVO.class);
resetFileSize(records);
@ -153,6 +153,7 @@ public class EdFileInfoServiceImpl extends ServiceImpl<EdFileInfoMapper, EdFileI
/**
* 新建文件夹
*
* @return
*/
@Override
@ -502,7 +503,7 @@ public class EdFileInfoServiceImpl extends ServiceImpl<EdFileInfoMapper, EdFileI
String preVersionId = dbVersionRelation.get(id);
EdFileInfo tmp = importIdMap.get(preVersionId);
saveObj.setPreVersion(tmp.getFileVersion());
int effect = Objects.equals(saveObj.getId(), effectId) ? EffectFlagEnum.EFFECT.code : EffectFlagEnum.NOT_EFFECTIVE.code;
int effect = ObjUtil.equals(saveObj.getId(), effectId) ? EffectFlagEnum.EFFECT.code : EffectFlagEnum.NOT_EFFECTIVE.code;
saveObj.setEffectFlag(effect);
}
allObjs.addAll(saveObjs);
@ -557,7 +558,7 @@ public class EdFileInfoServiceImpl extends ServiceImpl<EdFileInfoMapper, EdFileI
for (EdFileInfo edFileInfo : edFileInfos) {
Integer preVersion = edFileInfo.getPreVersion();
EdFileInfo fileInfo = versionMap.get(preVersion);
String preVersionId = Objects.isNull(fileInfo) ? null : fileInfo.getId();
String preVersionId = ObjUtil.isNull(fileInfo) ? null : fileInfo.getId();
versionRelation.put(edFileInfo.getId(), preVersionId);
}
return versionRelation;

View File

@ -22,7 +22,6 @@ import com.electromagnetic.industry.software.manage.pojo.resp.FileSimpleInfoVO;
import com.electromagnetic.industry.software.manage.service.EdFileRelationService;
import com.electromagnetic.industry.software.manage.service.FileSystemService;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
@ -35,23 +34,24 @@ import static com.electromagnetic.industry.software.common.cons.ElectromagneticC
@Service
public class EdFileRelationServiceImpl extends ServiceImpl<EdFileRelationMapper, EdFileRelation> implements EdFileRelationService {
private final EleLog log = new EleLog(EdFileInfoServiceImpl.class);
@Resource
EdFileInfoMapper edFileInfoMapper;
@Resource
EdFileInfoServiceImpl edFileInfoService;
@Resource
private CommonService commonService;
private final EleLog log = new EleLog(EdFileInfoServiceImpl.class);
@Resource
private FileSystemService fileSystemService;
/**
* 创建文件关系
*
* @param edFileRelation
* @return
*/
@Override
public Boolean createRelation (EdFileRelation edFileRelation) {
public Boolean createRelation(EdFileRelation edFileRelation) {
// 无法建立已建立的关系
String queryId1 = edFileRelation.getId1();
String queryId2 = edFileRelation.getId2();
@ -61,7 +61,7 @@ public class EdFileRelationServiceImpl extends ServiceImpl<EdFileRelationMapper,
.eq(EdFileRelation::getId1, queryId2).eq(EdFileRelation::getId2, queryId1);
List<EdFileRelation> list = this.list(queryWrapper);
if (!list.isEmpty()) {
throw new BizException (-1, "请勿重复建立关系");
throw new BizException(-1, "请勿重复建立关系");
}
edFileRelation.setId(IdWorker.getSnowFlakeIdString());
@ -71,11 +71,12 @@ public class EdFileRelationServiceImpl extends ServiceImpl<EdFileRelationMapper,
/**
* 取消文件关系
*
* @param id
* @return
*/
@Override
public Boolean cancelRelation (String id) {
public Boolean cancelRelation(String id) {
return this.removeById(id);
}
@ -130,6 +131,7 @@ public class EdFileRelationServiceImpl extends ServiceImpl<EdFileRelationMapper,
/**
* 检查文件名是否唯一
*
* @param parentId
* @param fileName
* @return
@ -160,9 +162,9 @@ public class EdFileRelationServiceImpl extends ServiceImpl<EdFileRelationMapper,
List<Edge> edges = new ArrayList<>();
for (EdFileRelation edFileRelation : list) {
if (edFileRelation.getId1().equals(id)) {
edges.add(new Edge(edFileRelation.getId1(), edFileRelation.getId2(),edFileRelation.getId(),edFileRelation.getRelationship()));
edges.add(new Edge(edFileRelation.getId1(), edFileRelation.getId2(), edFileRelation.getId(), edFileRelation.getRelationship()));
} else {
edges.add(new Edge(edFileRelation.getId2(), edFileRelation.getId1(),edFileRelation.getId(),edFileRelation.getRelationship()));
edges.add(new Edge(edFileRelation.getId2(), edFileRelation.getId1(), edFileRelation.getId(), edFileRelation.getRelationship()));
}
}
return edges;

View File

@ -21,6 +21,7 @@ import com.electromagnetic.industry.software.common.util.UserThreadLocal;
import com.electromagnetic.industry.software.manage.mapper.EdFileInfoMapper;
import com.electromagnetic.industry.software.manage.pojo.models.EdFileInfo;
import com.electromagnetic.industry.software.manage.pojo.req.FolderResortDTO;
import com.electromagnetic.industry.software.manage.pojo.req.QueryPublishStatus;
import com.electromagnetic.industry.software.manage.pojo.resp.ProjectVO;
import com.electromagnetic.industry.software.manage.service.EdPrjService;
import com.electromagnetic.industry.software.manage.service.FileSystemService;
@ -422,4 +423,33 @@ public class EdPrjServiceImpl extends ServiceImpl<EdFileInfoMapper, EdFileInfo>
}
}
/**
* 获取项目的发布状态
*
* @param queryPublishStatus
* @return
*/
@Override
public ElectromagneticResult<?> publishStatus(QueryPublishStatus queryPublishStatus) {
Map<String, Integer> res = new HashMap<>();
List<String> prjIds = queryPublishStatus.getPrjIds();
List<EdFileInfo> edFileInfos = this.baseMapper.selectList(Wrappers.lambdaQuery(EdFileInfo.class).select(EdFileInfo::getFilePath)
.eq(EdFileInfo::getEffectFlag, EffectFlagEnum.EFFECT.code)
.eq(EdFileInfo::getPrjDir, true)
.eq(EdFileInfo::getDataStatus, EleDataStatusEnum.NOT_PUBLISHED.code));
Set<String> unpublishFiles = new HashSet<>();
for (EdFileInfo edFileInfo : edFileInfos) {
String filePath = edFileInfo.getFilePath();
String prjId = filePath.split(MYSQL_FILE_PATH_SPLIT)[0];
unpublishFiles.add(prjId);
}
for (String prjId : prjIds) {
res.put(prjId, EleDataStatusEnum.PUBLISHED.code);
if (unpublishFiles.contains(prjId)) {
res.put(prjId, EleDataStatusEnum.NOT_PUBLISHED.code);
}
}
return ElectromagneticResultUtil.success(res);
}
}

View File

@ -24,8 +24,10 @@ import com.electromagnetic.industry.software.manage.pojo.models.UserRole;
import com.electromagnetic.industry.software.manage.pojo.req.RoleDTO;
import com.electromagnetic.industry.software.manage.pojo.req.RolePageDTO;
import com.electromagnetic.industry.software.manage.pojo.req.RolePermissionDTO;
import com.electromagnetic.industry.software.manage.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.electromagnetic.industry.software.manage.service.PermissionService;
import com.electromagnetic.industry.software.manage.service.RolePermissionService;
import com.electromagnetic.industry.software.manage.service.RoleService;
import com.electromagnetic.industry.software.manage.service.UserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@ -62,7 +64,7 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements Ro
@Override
public Boolean createRole(RoleDTO roleDTO) {
if (!checkRoleNameUnique(roleDTO) ) {
if (!checkRoleNameUnique(roleDTO)) {
String info = "当前角色名称已存在:" + roleDTO.getRoleName();
log.error(info);
throw new BizException(-1, info);
@ -98,7 +100,7 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements Ro
@Override
public Boolean updateRole(RoleDTO roleDTO) {
if (!checkRoleNameUnique(roleDTO) ) {
if (!checkRoleNameUnique(roleDTO)) {
String info = "当前角色名称已存在:" + roleDTO.getRoleName();
log.error(info);
throw new BizException(-1, info);
@ -254,7 +256,7 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements Ro
queryWrapper.select(Role::getRoleName);
List<String> roleNames = this.listObjs(queryWrapper).stream().map(Object::toString).collect(Collectors.toList());
List<HashMap<String,String>> result = new ArrayList<>();
List<HashMap<String, String>> result = new ArrayList<>();
for (String roleName : roleNames) {
HashMap<String, String> map = new HashMap<>();
map.put("value", roleName);
@ -369,6 +371,7 @@ public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements Ro
/**
* 获取层级树结构
*
* @return
*/
private List<EdFileInfo> getFiles() {

View File

@ -30,8 +30,6 @@ import com.electromagnetic.industry.software.manage.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>