refactor(项目管理): 优化文件批量下载方式为流式下载

This commit is contained in:
song-tianyang 2023-12-18 16:18:55 +08:00 committed by Craftsman
parent 5172dcc91d
commit aa9a98d829
17 changed files with 260 additions and 155 deletions

View File

@ -47,6 +47,7 @@ public class DefaultRepositoryDir {
private static final String PROJECT_ENV_SSL_DIR = PROJECT_DIR + "/environment/%s"; private static final String PROJECT_ENV_SSL_DIR = PROJECT_DIR + "/environment/%s";
private static final String PROJECT_FUNCTIONAL_CASE_DIR = PROJECT_DIR + "/functional-case/%s"; private static final String PROJECT_FUNCTIONAL_CASE_DIR = PROJECT_DIR + "/functional-case/%s";
private static final String PROJECT_FILE_MANAGEMENT_DIR = PROJECT_DIR + "/file-management"; private static final String PROJECT_FILE_MANAGEMENT_DIR = PROJECT_DIR + "/file-management";
private static final String PROJECT_FILE_MANAGEMENT_PREVIEW_DIR = PROJECT_DIR + "/file-management/preview";
/** /**
* 接口调试相关文件的存储目录 * 接口调试相关文件的存储目录
* project/{projectId}/apiCase/{apiDebugId} * project/{projectId}/apiCase/{apiDebugId}
@ -87,6 +88,10 @@ public class DefaultRepositoryDir {
return String.format(PROJECT_FILE_MANAGEMENT_DIR, projectId); return String.format(PROJECT_FILE_MANAGEMENT_DIR, projectId);
} }
public static String getFileManagementPreviewDir(String projectId) {
return String.format(PROJECT_FILE_MANAGEMENT_PREVIEW_DIR, projectId);
}
public static String getBugDir(String projectId, String bugId) { public static String getBugDir(String projectId, String bugId) {
return String.format(PROJECT_BUG_DIR, projectId, bugId); return String.format(PROJECT_BUG_DIR, projectId, bugId);
} }

View File

@ -6,7 +6,6 @@ import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
@ -53,7 +52,10 @@ public class GitRepository implements FileRepository {
@Override @Override
public InputStream getFileAsStream(FileRequest request) throws Exception { public InputStream getFileAsStream(FileRequest request) throws Exception {
return new ByteArrayInputStream(getFile(request)); GitFileRequest gitFileInfo = request.getGitFileRequest();
GitRepositoryUtil repositoryUtils = new GitRepositoryUtil(
gitFileInfo.getUrl(), gitFileInfo.getUserName(), gitFileInfo.getToken());
return repositoryUtils.getFileStream(gitFileInfo.getUrl(), gitFileInfo.getCommitId());
} }
// 缓冲区大小 // 缓冲区大小

View File

@ -20,6 +20,7 @@ import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.PathFilter; import org.eclipse.jgit.treewalk.filter.PathFilter;
import java.io.InputStream;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -58,6 +59,14 @@ public class GitRepositoryUtil {
return returnBytes; return returnBytes;
} }
public InputStream getFileStream(String filePath, String commitId) throws Exception {
InMemoryRepository repo = this.getGitRepositoryInMemory(repositoryUrl, userName, token);
ObjectId fileCommitObjectId = repo.resolve(commitId);
ObjectId objectId = this.getTreeWork(repo, fileCommitObjectId, filePath).getObjectId(0);
ObjectLoader loader = repo.open(objectId);
return loader.openStream();
}
public Map<String, byte[]> getFiles(List<RepositoryQuery> RepositoryQueryList) throws Exception { public Map<String, byte[]> getFiles(List<RepositoryQuery> RepositoryQueryList) throws Exception {
Map<String, byte[]> returnMap = new HashMap<>(); Map<String, byte[]> returnMap = new HashMap<>();
if (CollectionUtils.isEmpty(RepositoryQueryList)) { if (CollectionUtils.isEmpty(RepositoryQueryList)) {

View File

@ -10,7 +10,7 @@ import java.io.*;
public class TempFileUtils { public class TempFileUtils {
private static final String TEMP_FILE_FOLDER = "/tmp/metersphere/file/"; private static final String TEMP_FILE_FOLDER = "/tmp/metersphere/file/";
private static final int CREATE_FILE_BYTES_MAX_LENGTH = 256;
private TempFileUtils() { private TempFileUtils() {
} }
@ -48,18 +48,6 @@ public class TempFileUtils {
} }
} }
//压缩图片
public static String catchCompressImgIfNotExists(String fileId, byte[] fileBytes) {
try {
String previewPath = getPreviewImgFilePath(fileId);
compressPic(fileBytes, previewPath);
return previewPath;
} catch (Exception ignore) {
}
return null;
}
public static void compressPic(byte[] fileBytes, String compressPicAbsolutePath) throws Exception { public static void compressPic(byte[] fileBytes, String compressPicAbsolutePath) throws Exception {
// 读取原始图像 // 读取原始图像
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(fileBytes)); BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(fileBytes));
@ -122,10 +110,11 @@ public class TempFileUtils {
} }
try (InputStream in = new ByteArrayInputStream(fileBytes); OutputStream out = new FileOutputStream(file)) { try (InputStream in = new ByteArrayInputStream(fileBytes); OutputStream out = new FileOutputStream(file)) {
final int MAX = 4096;
byte[] buf = new byte[MAX]; byte[] buf = new byte[CREATE_FILE_BYTES_MAX_LENGTH];
for (int bytesRead = in.read(buf, 0, MAX); bytesRead != -1; bytesRead = in.read(buf, 0, MAX)) { int num;
out.write(buf, 0, bytesRead); while ((num = in.read(buf)) > 0) {
out.write(buf, 0, num);
} }
} catch (IOException e) { } catch (IOException e) {
LogUtils.error(e); LogUtils.error(e);
@ -151,7 +140,7 @@ public class TempFileUtils {
if (file.exists()) { if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file); try (FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] b = new byte[1024]; byte[] b = new byte[CREATE_FILE_BYTES_MAX_LENGTH];
int n; int n;
while ((n = fis.read(b)) != -1) { while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n); bos.write(b, 0, n);

View File

@ -6,6 +6,7 @@ import io.metersphere.project.dto.filemanagement.response.FileAssociationRespons
import io.metersphere.project.service.FileAssociationService; import io.metersphere.project.service.FileAssociationService;
import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.system.log.constants.OperationLogModule; import io.metersphere.system.log.constants.OperationLogModule;
import io.metersphere.system.security.CheckOwner;
import io.metersphere.system.utils.SessionUtils; import io.metersphere.system.utils.SessionUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@ -27,6 +28,7 @@ public class FileAssociationController {
@GetMapping("/list/{id}") @GetMapping("/list/{id}")
@Operation(summary = "项目管理-文件管理-文件关联-文件资源关联列表") @Operation(summary = "项目管理-文件管理-文件关联-文件资源关联列表")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#id", resourceType = "file_metadata")
public List<FileAssociationResponse> getAssociationList(@PathVariable String id) { public List<FileAssociationResponse> getAssociationList(@PathVariable String id) {
return fileAssociationService.selectFileAllVersionAssociation(id); return fileAssociationService.selectFileAllVersionAssociation(id);
} }
@ -34,6 +36,7 @@ public class FileAssociationController {
@GetMapping("/upgrade/{projectId}/{id}") @GetMapping("/upgrade/{projectId}/{id}")
@Operation(summary = "项目管理-文件管理-文件关联-更新资源关联的文件到最新版本") @Operation(summary = "项目管理-文件管理-文件关联-更新资源关联的文件到最新版本")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#projectId", resourceType = "project")
public String upgrade(@PathVariable String projectId,@PathVariable String id) { public String upgrade(@PathVariable String projectId,@PathVariable String id) {
FileLogRecord fileLogRecord = FileLogRecord.builder() FileLogRecord fileLogRecord = FileLogRecord.builder()
.logModule(OperationLogModule.PROJECT_FILE_MANAGEMENT) .logModule(OperationLogModule.PROJECT_FILE_MANAGEMENT)
@ -47,6 +50,7 @@ public class FileAssociationController {
@PostMapping("/delete") @PostMapping("/delete")
@Operation(summary = "项目管理-文件管理-文件关联-取消文件和资源的关联") @Operation(summary = "项目管理-文件管理-文件关联-取消文件和资源的关联")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getProjectId()", resourceType = "project")
public int delete(@RequestBody @Validated FileAssociationDeleteRequest request) { public int delete(@RequestBody @Validated FileAssociationDeleteRequest request) {
FileLogRecord fileLogRecord = FileLogRecord.builder() FileLogRecord fileLogRecord = FileLogRecord.builder()
.logModule(OperationLogModule.PROJECT_FILE_MANAGEMENT) .logModule(OperationLogModule.PROJECT_FILE_MANAGEMENT)

View File

@ -13,6 +13,7 @@ import io.metersphere.system.utils.SessionUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
@ -35,6 +36,7 @@ public class FileManagementController {
@GetMapping(value = "/type/{projectId}") @GetMapping(value = "/type/{projectId}")
@Operation(summary = "项目管理-文件管理-获取已存在的文件类型") @Operation(summary = "项目管理-文件管理-获取已存在的文件类型")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#projectId", resourceType = "project")
public List<String> getFileType(@PathVariable String projectId) { public List<String> getFileType(@PathVariable String projectId) {
return fileMetadataService.getFileType(projectId, StorageType.MINIO.name()); return fileMetadataService.getFileType(projectId, StorageType.MINIO.name());
} }
@ -42,6 +44,7 @@ public class FileManagementController {
@PostMapping("/page") @PostMapping("/page")
@Operation(summary = "项目管理-文件管理-表格分页查询文件") @Operation(summary = "项目管理-文件管理-表格分页查询文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#request.getProjectId()", resourceType = "project")
public Pager<List<FileInformationResponse>> page(@Validated @RequestBody FileMetadataTableRequest request) { public Pager<List<FileInformationResponse>> page(@Validated @RequestBody FileMetadataTableRequest request) {
return fileMetadataService.page(request); return fileMetadataService.page(request);
} }
@ -49,6 +52,7 @@ public class FileManagementController {
@GetMapping("/get/{id}") @GetMapping("/get/{id}")
@Operation(summary = "项目管理-文件管理-查看文件详情") @Operation(summary = "项目管理-文件管理-查看文件详情")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#id", resourceType = "file_metadata")
public FileInformationResponse page(@PathVariable String id) { public FileInformationResponse page(@PathVariable String id) {
return fileMetadataService.getFileInformation(id); return fileMetadataService.getFileInformation(id);
} }
@ -57,6 +61,7 @@ public class FileManagementController {
@PostMapping("/module/count") @PostMapping("/module/count")
@Operation(summary = "项目管理-文件管理-表格分页查询文件") @Operation(summary = "项目管理-文件管理-表格分页查询文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#request.getProjectId()", resourceType = "project")
public Map<String, Long> moduleCount(@Validated @RequestBody FileMetadataTableRequest request) { public Map<String, Long> moduleCount(@Validated @RequestBody FileMetadataTableRequest request) {
return fileMetadataService.moduleCount(request, SessionUtils.getUserId()); return fileMetadataService.moduleCount(request, SessionUtils.getUserId());
} }
@ -64,6 +69,7 @@ public class FileManagementController {
@PostMapping("/upload") @PostMapping("/upload")
@Operation(summary = "项目管理-文件管理-上传文件") @Operation(summary = "项目管理-文件管理-上传文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD)
@CheckOwner(resourceId = "#request.getProjectId()", resourceType = "project")
public String upload(@Validated @RequestPart("request") FileUploadRequest request, @RequestPart(value = "file", required = false) MultipartFile uploadFile) throws Exception { public String upload(@Validated @RequestPart("request") FileUploadRequest request, @RequestPart(value = "file", required = false) MultipartFile uploadFile) throws Exception {
return fileMetadataService.upload(request, SessionUtils.getUserId(), uploadFile); return fileMetadataService.upload(request, SessionUtils.getUserId(), uploadFile);
} }
@ -71,6 +77,7 @@ public class FileManagementController {
@PostMapping("/re-upload") @PostMapping("/re-upload")
@Operation(summary = "项目管理-文件管理-重新上传文件") @Operation(summary = "项目管理-文件管理-重新上传文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getFileId()", resourceType = "file_metadata")
public String reUpload(@Validated @RequestPart("request") FileReUploadRequest request, @RequestPart(value = "file", required = false) MultipartFile uploadFile) throws Exception { public String reUpload(@Validated @RequestPart("request") FileReUploadRequest request, @RequestPart(value = "file", required = false) MultipartFile uploadFile) throws Exception {
return fileMetadataService.reUpload(request, SessionUtils.getUserId(), uploadFile); return fileMetadataService.reUpload(request, SessionUtils.getUserId(), uploadFile);
} }
@ -86,6 +93,7 @@ public class FileManagementController {
@PostMapping(value = "/delete") @PostMapping(value = "/delete")
@Operation(summary = "项目管理-文件管理-删除文件") @Operation(summary = "项目管理-文件管理-删除文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_DELETE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_DELETE)
@CheckOwner(resourceId = "#request.getSelectIds()", resourceType = "file_metadata")
public void delete(@Validated @RequestBody FileBatchProcessRequest request) throws Exception { public void delete(@Validated @RequestBody FileBatchProcessRequest request) throws Exception {
fileManagementService.delete(request, SessionUtils.getUserId()); fileManagementService.delete(request, SessionUtils.getUserId());
} }
@ -93,6 +101,7 @@ public class FileManagementController {
@PostMapping(value = "/update") @PostMapping(value = "/update")
@Operation(summary = "项目管理-文件管理-修改文件") @Operation(summary = "项目管理-文件管理-修改文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getId()", resourceType = "file_metadata")
public void update(@Validated @RequestBody FileUpdateRequest request) throws Exception { public void update(@Validated @RequestBody FileUpdateRequest request) throws Exception {
fileMetadataService.update(request, SessionUtils.getUserId()); fileMetadataService.update(request, SessionUtils.getUserId());
} }
@ -100,6 +109,7 @@ public class FileManagementController {
@GetMapping(value = "/jar-file-status/{fileId}/{enable}") @GetMapping(value = "/jar-file-status/{fileId}/{enable}")
@Operation(summary = "项目管理-文件管理-Jar文件启用禁用操作") @Operation(summary = "项目管理-文件管理-Jar文件启用禁用操作")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#fileId", resourceType = "file_metadata")
public void changeJarFileStatus(@PathVariable String fileId, @PathVariable boolean enable) { public void changeJarFileStatus(@PathVariable String fileId, @PathVariable boolean enable) {
fileMetadataService.changeJarFileStatus(fileId, enable, SessionUtils.getUserId()); fileMetadataService.changeJarFileStatus(fileId, enable, SessionUtils.getUserId());
} }
@ -107,13 +117,15 @@ public class FileManagementController {
@PostMapping(value = "/batch-download") @PostMapping(value = "/batch-download")
@Operation(summary = "项目管理-文件管理-批量下载文件") @Operation(summary = "项目管理-文件管理-批量下载文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_DOWNLOAD) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_DOWNLOAD)
public ResponseEntity<byte[]> downloadBodyFiles(@Validated @RequestBody FileBatchProcessRequest request) { @CheckOwner(resourceId = "#request.getSelectIds()", resourceType = "file_metadata")
return fileMetadataService.batchDownload(request); public void downloadBodyFiles(@Validated @RequestBody FileBatchProcessRequest request, HttpServletResponse httpServletResponse) {
fileMetadataService.batchDownload(request, httpServletResponse);
} }
@PostMapping(value = "/batch-move") @PostMapping(value = "/batch-move")
@Operation(summary = "项目管理-文件管理-批量移动文件") @Operation(summary = "项目管理-文件管理-批量移动文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getSelectIds()", resourceType = "file_metadata")
public void batchMoveFiles(@Validated @RequestBody FileBatchMoveRequest request) { public void batchMoveFiles(@Validated @RequestBody FileBatchMoveRequest request) {
fileMetadataService.batchMove(request, SessionUtils.getUserId()); fileMetadataService.batchMove(request, SessionUtils.getUserId());
} }
@ -122,6 +134,7 @@ public class FileManagementController {
@GetMapping(value = "/file-version/{fileId}") @GetMapping(value = "/file-version/{fileId}")
@Operation(summary = "项目管理-文件管理-文件历史版本") @Operation(summary = "项目管理-文件管理-文件历史版本")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#fileId", resourceType = "file_metadata")
public List<FileVersionResponse> getFileVersion(@PathVariable String fileId) { public List<FileVersionResponse> getFileVersion(@PathVariable String fileId) {
return fileMetadataService.getFileVersion(fileId); return fileMetadataService.getFileVersion(fileId);
} }

View File

@ -6,6 +6,7 @@ import io.metersphere.project.service.FileModuleService;
import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.system.dto.sdk.BaseTreeNode; import io.metersphere.system.dto.sdk.BaseTreeNode;
import io.metersphere.system.dto.sdk.request.NodeMoveRequest; import io.metersphere.system.dto.sdk.request.NodeMoveRequest;
import io.metersphere.system.security.CheckOwner;
import io.metersphere.system.utils.SessionUtils; import io.metersphere.system.utils.SessionUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@ -27,6 +28,7 @@ public class FileModuleController {
@GetMapping("/tree/{projectId}") @GetMapping("/tree/{projectId}")
@Operation(summary = "项目管理-文件管理-模块-查找模块") @Operation(summary = "项目管理-文件管理-模块-查找模块")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#projectId", resourceType = "project")
public List<BaseTreeNode> getTree(@PathVariable String projectId) { public List<BaseTreeNode> getTree(@PathVariable String projectId) {
return fileModuleService.getTree(projectId); return fileModuleService.getTree(projectId);
} }
@ -34,6 +36,7 @@ public class FileModuleController {
@PostMapping("/add") @PostMapping("/add")
@Operation(summary = "项目管理-文件管理-模块-添加模块") @Operation(summary = "项目管理-文件管理-模块-添加模块")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD)
@CheckOwner(resourceId = "#request.getProjectId()", resourceType = "project")
public String add(@RequestBody @Validated FileModuleCreateRequest request) { public String add(@RequestBody @Validated FileModuleCreateRequest request) {
return fileModuleService.add(request, SessionUtils.getUserId()); return fileModuleService.add(request, SessionUtils.getUserId());
} }
@ -41,6 +44,7 @@ public class FileModuleController {
@PostMapping("/update") @PostMapping("/update")
@Operation(summary = "项目管理-文件管理-模块-修改模块") @Operation(summary = "项目管理-文件管理-模块-修改模块")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getId()", resourceType = "file_module")
public boolean list(@RequestBody @Validated FileModuleUpdateRequest request) { public boolean list(@RequestBody @Validated FileModuleUpdateRequest request) {
fileModuleService.update(request, SessionUtils.getUserId()); fileModuleService.update(request, SessionUtils.getUserId());
return true; return true;
@ -49,6 +53,7 @@ public class FileModuleController {
@GetMapping("/delete/{deleteId}") @GetMapping("/delete/{deleteId}")
@Operation(summary = "项目管理-文件管理-模块-删除模块") @Operation(summary = "项目管理-文件管理-模块-删除模块")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_DELETE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_DELETE)
@CheckOwner(resourceId = "#deleteId", resourceType = "file_module")
public void deleteNode(@PathVariable String deleteId) { public void deleteNode(@PathVariable String deleteId) {
fileModuleService.deleteModule(deleteId, SessionUtils.getUserId()); fileModuleService.deleteModule(deleteId, SessionUtils.getUserId());
} }
@ -56,6 +61,7 @@ public class FileModuleController {
@PostMapping("/move") @PostMapping("/move")
@Operation(summary = "项目管理-文件管理-模块-移动模块") @Operation(summary = "项目管理-文件管理-模块-移动模块")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getDragNodeId()", resourceType = "file_module")
public void moveNode(@Validated @RequestBody NodeMoveRequest request) { public void moveNode(@Validated @RequestBody NodeMoveRequest request) {
fileModuleService.moveNode(request, SessionUtils.getUserId()); fileModuleService.moveNode(request, SessionUtils.getUserId());
} }

View File

@ -10,6 +10,7 @@ import io.metersphere.project.service.FileRepositoryService;
import io.metersphere.sdk.constants.PermissionConstants; import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.constants.StorageType; import io.metersphere.sdk.constants.StorageType;
import io.metersphere.system.dto.sdk.BaseTreeNode; import io.metersphere.system.dto.sdk.BaseTreeNode;
import io.metersphere.system.security.CheckOwner;
import io.metersphere.system.utils.SessionUtils; import io.metersphere.system.utils.SessionUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@ -33,6 +34,7 @@ public class FileRepositoryController {
@GetMapping("/list/{projectId}") @GetMapping("/list/{projectId}")
@Operation(summary = "项目管理-文件管理-存储库-存储库列表") @Operation(summary = "项目管理-文件管理-存储库-存储库列表")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#projectId", resourceType = "project")
public List<BaseTreeNode> getTree(@PathVariable String projectId) { public List<BaseTreeNode> getTree(@PathVariable String projectId) {
return fileRepositoryService.getTree(projectId); return fileRepositoryService.getTree(projectId);
} }
@ -40,27 +42,31 @@ public class FileRepositoryController {
@GetMapping(value = "/file-type/{projectId}") @GetMapping(value = "/file-type/{projectId}")
@Operation(summary = "项目管理-文件管理-存储库-获取已存在的存储库文件类型") @Operation(summary = "项目管理-文件管理-存储库-获取已存在的存储库文件类型")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#projectId", resourceType = "project")
public List<String> getFileType(@PathVariable String projectId) { public List<String> getFileType(@PathVariable String projectId) {
return fileMetadataService.getFileType(projectId, StorageType.GIT.name()); return fileMetadataService.getFileType(projectId, StorageType.GIT.name());
} }
@GetMapping(value = "/info/{id}")
@Operation(summary = "项目管理-文件管理-存储库-存储库信息")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
public FileRepositoryResponse getRepositoryInfo(@PathVariable String id) {
return fileRepositoryService.getRepositoryInfo(id);
}
@PostMapping("/add-repository") @PostMapping("/add-repository")
@Operation(summary = "项目管理-文件管理-存储库-添加存储库") @Operation(summary = "项目管理-文件管理-存储库-添加存储库")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD)
@CheckOwner(resourceId = "#request.getProjectId()", resourceType = "project")
public String add(@RequestBody @Validated FileRepositoryCreateRequest request) { public String add(@RequestBody @Validated FileRepositoryCreateRequest request) {
return fileRepositoryService.addRepository(request, SessionUtils.getUserId()); return fileRepositoryService.addRepository(request, SessionUtils.getUserId());
} }
@GetMapping(value = "/info/{id}")
@Operation(summary = "项目管理-文件管理-存储库-存储库信息")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ)
@CheckOwner(resourceId = "#id", resourceType = "file_module")
public FileRepositoryResponse getRepositoryInfo(@PathVariable String id) {
return fileRepositoryService.getRepositoryInfo(id);
}
@PostMapping("/update-repository") @PostMapping("/update-repository")
@Operation(summary = "项目管理-文件管理-存储库-修改存储库") @Operation(summary = "项目管理-文件管理-存储库-修改存储库")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_UPDATE)
@CheckOwner(resourceId = "#request.getId()", resourceType = "file_module")
public boolean list(@RequestBody @Validated FileRepositoryUpdateRequest request) { public boolean list(@RequestBody @Validated FileRepositoryUpdateRequest request) {
fileRepositoryService.updateRepository(request, SessionUtils.getUserId()); fileRepositoryService.updateRepository(request, SessionUtils.getUserId());
return true; return true;
@ -76,6 +82,7 @@ public class FileRepositoryController {
@PostMapping("/add-file") @PostMapping("/add-file")
@Operation(summary = "项目管理-文件管理-存储库-添加文件") @Operation(summary = "项目管理-文件管理-存储库-添加文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD)
@CheckOwner(resourceId = "#request.getModuleId()", resourceType = "file_module")
public String addFile(@Validated @RequestBody RepositoryFileAddRequest request) throws Exception { public String addFile(@Validated @RequestBody RepositoryFileAddRequest request) throws Exception {
return fileRepositoryService.addFile(request, SessionUtils.getUserId()); return fileRepositoryService.addFile(request, SessionUtils.getUserId());
} }
@ -83,6 +90,7 @@ public class FileRepositoryController {
@GetMapping("/pull-file/{id}") @GetMapping("/pull-file/{id}")
@Operation(summary = "项目管理-文件管理-存储库-更新文件") @Operation(summary = "项目管理-文件管理-存储库-更新文件")
@RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD) @RequiresPermissions(PermissionConstants.PROJECT_FILE_MANAGEMENT_READ_ADD)
@CheckOwner(resourceId = "#id", resourceType = "file_metadata")
public String pullFile(@PathVariable String id) throws Exception { public String pullFile(@PathVariable String id) throws Exception {
return fileMetadataService.pullFile(id, SessionUtils.getUserId()); return fileMetadataService.pullFile(id, SessionUtils.getUserId());
} }

View File

@ -4,11 +4,17 @@ import io.metersphere.project.domain.*;
import io.metersphere.project.dto.filemanagement.FileManagementQuery; import io.metersphere.project.dto.filemanagement.FileManagementQuery;
import io.metersphere.project.dto.filemanagement.request.FileBatchProcessRequest; import io.metersphere.project.dto.filemanagement.request.FileBatchProcessRequest;
import io.metersphere.project.mapper.*; import io.metersphere.project.mapper.*;
import io.metersphere.sdk.constants.DefaultRepositoryDir;
import io.metersphere.sdk.constants.ModuleConstants; import io.metersphere.sdk.constants.ModuleConstants;
import io.metersphere.sdk.constants.StorageType;
import io.metersphere.sdk.dto.FileMetadataRepositoryDTO;
import io.metersphere.sdk.dto.FileModuleRepositoryDTO;
import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.file.FileRequest;
import io.metersphere.sdk.util.BeanUtils;
import io.metersphere.sdk.util.LogUtils; import io.metersphere.sdk.util.LogUtils;
import io.metersphere.sdk.util.TempFileUtils; import io.metersphere.sdk.util.TempFileUtils;
import io.metersphere.sdk.file.FileRequest; import io.metersphere.sdk.util.Translator;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -26,6 +32,8 @@ public class FileManagementService {
@Resource @Resource
private FileMetadataRepositoryMapper fileMetadataRepositoryMapper; private FileMetadataRepositoryMapper fileMetadataRepositoryMapper;
@Resource @Resource
private FileModuleRepositoryMapper fileModuleRepositoryMapper;
@Resource
private FileAssociationMapper fileAssociationMapper; private FileAssociationMapper fileAssociationMapper;
@Resource @Resource
private FileModuleMapper fileModuleMapper; private FileModuleMapper fileModuleMapper;
@ -69,9 +77,13 @@ public class FileManagementService {
FileRequest fileRequest = new FileRequest(); FileRequest fileRequest = new FileRequest();
fileRequest.setFileName(fileMetadata.getId()); fileRequest.setFileName(fileMetadata.getId());
fileRequest.setStorage(fileMetadata.getStorage()); fileRequest.setStorage(fileMetadata.getStorage());
fileRequest.setFolder(DefaultRepositoryDir.getFileManagementDir(fileMetadata.getProjectId()));
try { try {
//删除存储容器中的文件 //删除存储容器中的文件
fileService.deleteFile(fileRequest); fileService.deleteFile(fileRequest);
//删除缓存文件
fileRequest.setFolder(DefaultRepositoryDir.getFileManagementPreviewDir(fileMetadata.getProjectId()));
fileService.deleteFile(fileRequest);
//删除临时文件 //删除临时文件
TempFileUtils.deleteTmpFile(fileMetadata.getId()); TempFileUtils.deleteTmpFile(fileMetadata.getId());
} catch (Exception e) { } catch (Exception e) {
@ -148,4 +160,55 @@ public class FileManagementService {
} }
} }
} }
public byte[] getFile(FileMetadata fileMetadata) throws Exception {
if (fileMetadata == null) {
throw new MSException(Translator.get("file.not.exist"));
}
FileRequest fileRequest = new FileRequest();
fileRequest.setFileName(fileMetadata.getId());
fileRequest.setFolder(DefaultRepositoryDir.getFileManagementDir(fileMetadata.getProjectId()));
fileRequest.setStorage(fileMetadata.getStorage());
//获取git文件下载
if (StringUtils.equals(fileMetadata.getStorage(), StorageType.GIT.name())) {
FileModuleRepository fileModuleRepository = fileModuleRepositoryMapper.selectByPrimaryKey(fileMetadata.getModuleId());
FileMetadataRepository fileMetadataRepository = fileMetadataRepositoryMapper.selectByPrimaryKey(fileMetadata.getId());
FileModuleRepositoryDTO repositoryDTO = new FileModuleRepositoryDTO();
BeanUtils.copyBean(repositoryDTO, fileModuleRepository);
FileMetadataRepositoryDTO metadataRepositoryDTO = new FileMetadataRepositoryDTO();
BeanUtils.copyBean(metadataRepositoryDTO, fileMetadataRepository);
fileRequest.setGitFileRequest(repositoryDTO, metadataRepositoryDTO);
}
return fileService.download(fileRequest);
}
public byte[] getPreviewImg(FileMetadata fileMetadata) {
FileRequest previewRequest = new FileRequest();
previewRequest.setFileName(fileMetadata.getId());
previewRequest.setStorage(StorageType.MINIO.name());
previewRequest.setFolder(DefaultRepositoryDir.getFileManagementPreviewDir(fileMetadata.getProjectId()));
byte[] previewImg = null;
try {
previewImg = fileService.download(previewRequest);
} catch (Exception e) {
LogUtils.error("获取预览图失败", e);
}
if (previewImg == null || previewImg.length == 0) {
try {
byte[] fileBytes = this.getFile(fileMetadata);
TempFileUtils.compressPic(fileBytes, TempFileUtils.getPreviewImgFilePath(fileMetadata.getId()));
previewImg = TempFileUtils.getFile(TempFileUtils.getPreviewImgFilePath(fileMetadata.getId()));
fileService.upload(previewImg, previewRequest);
return previewImg;
} catch (Exception e) {
LogUtils.error("获取预览图失败", e);
}
}
return new byte[0];
}
} }

View File

@ -17,8 +17,6 @@ import io.metersphere.project.utils.FileMetadataUtils;
import io.metersphere.sdk.constants.DefaultRepositoryDir; import io.metersphere.sdk.constants.DefaultRepositoryDir;
import io.metersphere.sdk.constants.ModuleConstants; import io.metersphere.sdk.constants.ModuleConstants;
import io.metersphere.sdk.constants.StorageType; import io.metersphere.sdk.constants.StorageType;
import io.metersphere.sdk.dto.FileMetadataRepositoryDTO;
import io.metersphere.sdk.dto.FileModuleRepositoryDTO;
import io.metersphere.sdk.dto.RemoteFileAttachInfo; import io.metersphere.sdk.dto.RemoteFileAttachInfo;
import io.metersphere.sdk.exception.MSException; import io.metersphere.sdk.exception.MSException;
import io.metersphere.sdk.file.FileRepository; import io.metersphere.sdk.file.FileRepository;
@ -30,6 +28,7 @@ import io.metersphere.system.uid.IDGenerator;
import io.metersphere.system.utils.PageUtils; import io.metersphere.system.utils.PageUtils;
import io.metersphere.system.utils.Pager; import io.metersphere.system.utils.Pager;
import jakarta.annotation.Resource; import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -285,7 +284,15 @@ public class FileMetadataService {
uploadFileRequest.setFileName(fileMetadata.getId()); uploadFileRequest.setFileName(fileMetadata.getId());
uploadFileRequest.setFolder(this.generateMinIOFilePath(fileMetadata.getProjectId())); uploadFileRequest.setFolder(this.generateMinIOFilePath(fileMetadata.getProjectId()));
uploadFileRequest.setStorage(StorageType.MINIO.name()); uploadFileRequest.setStorage(StorageType.MINIO.name());
return fileService.upload(file, uploadFileRequest); String filePath = fileService.upload(file, uploadFileRequest);
if (TempFileUtils.isImage(fileMetadata.getType())) {
TempFileUtils.compressPic(file.getBytes(), TempFileUtils.getPreviewImgFilePath(fileMetadata.getId()));
byte[] previewImg = TempFileUtils.getFile(TempFileUtils.getPreviewImgFilePath(fileMetadata.getId()));
uploadFileRequest.setFolder(DefaultRepositoryDir.getFileManagementPreviewDir(fileMetadata.getProjectId()));
fileService.upload(previewImg, uploadFileRequest);
}
return filePath;
} }
public File getTmpFile(FileMetadata fileMetadata) { public File getTmpFile(FileMetadata fileMetadata) {
@ -294,7 +301,7 @@ public class FileMetadataService {
file = new File(TempFileUtils.getTmpFilePath(fileMetadata.getId())); file = new File(TempFileUtils.getTmpFilePath(fileMetadata.getId()));
} else { } else {
try { try {
String filePath = TempFileUtils.createFile(TempFileUtils.getTmpFilePath(fileMetadata.getId()), this.getFile(fileMetadata)); String filePath = TempFileUtils.createFile(TempFileUtils.getTmpFilePath(fileMetadata.getId()), fileManagementService.getFile(fileMetadata));
file = new File(filePath); file = new File(filePath);
} catch (Exception ignore) { } catch (Exception ignore) {
} }
@ -308,7 +315,7 @@ public class FileMetadataService {
filePath = TempFileUtils.getTmpFilePath(fileMetadata.getId()); filePath = TempFileUtils.getTmpFilePath(fileMetadata.getId());
} else { } else {
try { try {
filePath = TempFileUtils.createFile(TempFileUtils.getTmpFilePath(fileMetadata.getId()), this.getFile(fileMetadata)); filePath = TempFileUtils.createFile(TempFileUtils.getTmpFilePath(fileMetadata.getId()), fileManagementService.getFile(fileMetadata));
} catch (Exception ignore) { } catch (Exception ignore) {
} }
} }
@ -331,30 +338,6 @@ public class FileMetadataService {
return fileName + "." + type; return fileName + "." + type;
} }
private byte[] getFile(FileMetadata fileMetadata) throws Exception {
if (fileMetadata == null) {
throw new MSException(Translator.get("file.not.exist"));
}
FileRequest fileRequest = new FileRequest();
fileRequest.setFileName(fileMetadata.getId());
fileRequest.setFolder(this.generateMinIOFilePath(fileMetadata.getProjectId()));
fileRequest.setStorage(fileMetadata.getStorage());
//获取git文件下载
if (StringUtils.equals(fileMetadata.getStorage(), StorageType.GIT.name())) {
FileModuleRepository fileModuleRepository = fileModuleRepositoryMapper.selectByPrimaryKey(fileMetadata.getModuleId());
FileMetadataRepository fileMetadataRepository = fileMetadataRepositoryMapper.selectByPrimaryKey(fileMetadata.getId());
FileModuleRepositoryDTO repositoryDTO = new FileModuleRepositoryDTO();
BeanUtils.copyBean(repositoryDTO, fileModuleRepository);
FileMetadataRepositoryDTO metadataRepositoryDTO = new FileMetadataRepositoryDTO();
BeanUtils.copyBean(metadataRepositoryDTO, fileMetadataRepository);
fileRequest.setGitFileRequest(repositoryDTO, metadataRepositoryDTO);
}
return fileService.download(fileRequest);
}
public void update(FileUpdateRequest request, String operator) { public void update(FileUpdateRequest request, String operator) {
//检查模块的合法性 //检查模块的合法性
FileMetadata fileMetadata = fileMetadataMapper.selectByPrimaryKey(request.getId()); FileMetadata fileMetadata = fileMetadataMapper.selectByPrimaryKey(request.getId());
@ -399,24 +382,16 @@ public class FileMetadataService {
return PageUtils.setPageInfo(page, this.list(request)); return PageUtils.setPageInfo(page, this.list(request));
} }
public ResponseEntity<byte[]> batchDownload(FileBatchProcessRequest request) { public void batchDownload(FileBatchProcessRequest request, HttpServletResponse httpServletResponse) {
List<FileMetadata> fileMetadataList = fileManagementService.getProcessList(request); List<FileMetadata> fileMetadataList = fileManagementService.getProcessList(request);
this.checkDownloadSize(fileMetadataList); this.checkDownloadSize(fileMetadataList);
try { this.batchDownloadWithResponse(fileMetadataList, httpServletResponse);
byte[] bytes = this.batchDownload(fileMetadataList);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "files.zip")
.body(bytes);
} catch (Exception e) {
return ResponseEntity.status(509).body(e.getMessage().getBytes());
}
} }
public byte[] batchDownload(List<FileMetadata> fileMetadataList) { public void batchDownloadWithResponse(List<FileMetadata> fileMetadataList, HttpServletResponse response) {
Map<String, File> fileMap = new HashMap<>(); Map<String, File> fileMap = new HashMap<>();
fileMetadataList.forEach(fileMetadata -> fileMap.put(this.getFileName(fileMetadata.getName(), fileMetadata.getType()), this.getTmpFile(fileMetadata))); fileMetadataList.forEach(fileMetadata -> fileMap.put(this.getFileName(fileMetadata.getName(), fileMetadata.getType()), this.getTmpFile(fileMetadata)));
return FileDownloadUtils.listBytesToZip(fileMap); FileDownloadUtils.zipFilesWithResponse(fileMap, response);
} }
//检查下载的文件的大小 //检查下载的文件的大小
@ -507,10 +482,13 @@ public class FileMetadataService {
//获取压缩过的图片 //获取压缩过的图片
bytes = TempFileUtils.getFile(TempFileUtils.getPreviewImgFilePath(fileMetadata.getId())); bytes = TempFileUtils.getFile(TempFileUtils.getPreviewImgFilePath(fileMetadata.getId()));
} else { } else {
/**
* 从minio中获取临时文件
* 如果minio不存在压缩后上传到minio中并缓存到文件目录中
*/
//压缩图片并保存在临时文件夹中 //压缩图片并保存在临时文件夹中
bytes = TempFileUtils.getFile( bytes = fileManagementService.getPreviewImg(fileMetadata);
TempFileUtils.catchCompressImgIfNotExists(fileMetadata.getId(), this.getFile(fileMetadata)) TempFileUtils.createFile(TempFileUtils.getPreviewImgFilePath(fileMetadata.getId()), bytes);
);
} }
} }

View File

@ -11,6 +11,10 @@ public class FileService {
return FileCenter.getRepository(request.getStorage()).saveFile(file, request); return FileCenter.getRepository(request.getStorage()).saveFile(file, request);
} }
public String upload(byte[] file, FileRequest request) throws Exception {
return FileCenter.getRepository(request.getStorage()).saveFile(file, request);
}
public byte[] download(FileRequest request) throws Exception { public byte[] download(FileRequest request) throws Exception {
return FileCenter.getRepository(request.getStorage()).getFile(request); return FileCenter.getRepository(request.getStorage()).getFile(request);
} }

View File

@ -1,28 +1,30 @@
package io.metersphere.project.utils; package io.metersphere.project.utils;
import io.metersphere.sdk.util.LogUtils; import io.metersphere.sdk.util.LogUtils;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
public class FileDownloadUtils { public class FileDownloadUtils {
public static byte[] listBytesToZip(Map<String, File> fileMap) { public static void zipFilesWithResponse(Map<String, File> fileMap, HttpServletResponse response) {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
for (Map.Entry<String, File> fileEntry : fileMap.entrySet()) { for (Map.Entry<String, File> fileEntry : fileMap.entrySet()) {
String fileName = fileEntry.getKey(); String fileName = fileEntry.getKey();
File file = fileEntry.getValue(); File file = fileEntry.getValue();
if (file.exists()) { if (file.exists()) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
ZipEntry zipEntry = new ZipEntry(fileName); ZipEntry zipEntry = new ZipEntry(fileName);
zipOutputStream.putNextEntry(zipEntry); zipOutputStream.putNextEntry(zipEntry);
byte[] buffer = new byte[1024]; byte[] buffer = new byte[512];
int num; int num;
while ((num = bis.read(buffer)) > 0) { while ((num = bis.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, num); zipOutputStream.write(buffer, 0, num);
@ -32,11 +34,12 @@ public class FileDownloadUtils {
} }
} }
} }
zipOutputStream.close();
return byteArrayOutputStream.toByteArray(); response.setContentType("application/zip");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setHeader("Content-disposition", "attachment;filename=files.zip");
} catch (Exception e) { } catch (Exception e) {
LogUtils.error(e); LogUtils.error(e);
return new byte[0];
} }
} }

View File

@ -17,10 +17,7 @@ import io.metersphere.project.service.FileService;
import io.metersphere.project.utils.FileManagementBaseUtils; import io.metersphere.project.utils.FileManagementBaseUtils;
import io.metersphere.project.utils.FileManagementRequestUtils; import io.metersphere.project.utils.FileManagementRequestUtils;
import io.metersphere.project.utils.FileMetadataUtils; import io.metersphere.project.utils.FileMetadataUtils;
import io.metersphere.sdk.constants.ModuleConstants; import io.metersphere.sdk.constants.*;
import io.metersphere.sdk.constants.PermissionConstants;
import io.metersphere.sdk.constants.SessionConstants;
import io.metersphere.sdk.constants.StorageType;
import io.metersphere.sdk.file.FileRequest; import io.metersphere.sdk.file.FileRequest;
import io.metersphere.sdk.util.FileAssociationSourceUtil; import io.metersphere.sdk.util.FileAssociationSourceUtil;
import io.metersphere.sdk.util.JSON; import io.metersphere.sdk.util.JSON;
@ -97,7 +94,7 @@ public class FileManagementControllerTests extends BaseTest {
@Resource @Resource
private CommonProjectService commonProjectService; private CommonProjectService commonProjectService;
List<CheckLogModel> checkLogModelList = new ArrayList<>(); private static List<CheckLogModel> LOG_CHECK_LIST = new ArrayList<>();
@BeforeEach @BeforeEach
public void initTestData() { public void initTestData() {
@ -172,7 +169,7 @@ public class FileManagementControllerTests extends BaseTest {
Assertions.assertNotNull(baseTreeNode.getParentId()); Assertions.assertNotNull(baseTreeNode.getParentId());
} }
Assertions.assertNotNull(a1Node); Assertions.assertNotNull(a1Node);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD) new CheckLogModel(a1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD)
); );
//测试a1无法获取存储库详情 //测试a1无法获取存储库详情
@ -212,10 +209,10 @@ public class FileManagementControllerTests extends BaseTest {
Assertions.assertNotNull(a2Node); Assertions.assertNotNull(a2Node);
Assertions.assertNotNull(a1b1Node); Assertions.assertNotNull(a1b1Node);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a2Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD) new CheckLogModel(a2Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD)
); );
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1b1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD) new CheckLogModel(a1b1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD)
); );
@ -241,7 +238,7 @@ public class FileManagementControllerTests extends BaseTest {
} }
} }
Assertions.assertNotNull(a1ChildNode); Assertions.assertNotNull(a1ChildNode);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1ChildNode.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD) new CheckLogModel(a1ChildNode.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD)
); );
@ -270,7 +267,7 @@ public class FileManagementControllerTests extends BaseTest {
} }
} }
Assertions.assertNotNull(a1a1c1Node); Assertions.assertNotNull(a1a1c1Node);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1a1c1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD) new CheckLogModel(a1a1c1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD)
); );
//子节点a1-b1下继续创建节点a1-b1-c1 //子节点a1-b1下继续创建节点a1-b1-c1
@ -297,7 +294,7 @@ public class FileManagementControllerTests extends BaseTest {
Assertions.assertNotNull(a1b1c1Node); Assertions.assertNotNull(a1b1c1Node);
preliminaryTreeNodes = treeNodes; preliminaryTreeNodes = treeNodes;
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1b1c1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD) new CheckLogModel(a1b1c1Node.getId(), OperationLogType.ADD, FileManagementRequestUtils.URL_MODULE_ADD)
); );
} }
@ -382,7 +379,7 @@ public class FileManagementControllerTests extends BaseTest {
this.requestPostWithOkAndReturn(FileManagementRequestUtils.URL_MODULE_UPDATE, updateRequest); this.requestPostWithOkAndReturn(FileManagementRequestUtils.URL_MODULE_UPDATE, updateRequest);
preliminaryTreeNodes = this.getFileModuleTreeNode(); preliminaryTreeNodes = this.getFileModuleTreeNode();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1Node.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_MODULE_UPDATE) new CheckLogModel(a1Node.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_MODULE_UPDATE)
); );
} }
@ -428,7 +425,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
MvcResult mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); MvcResult mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
String returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); String returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -450,7 +447,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -466,7 +463,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -480,7 +477,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -493,7 +490,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -514,7 +511,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -537,7 +534,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -558,7 +555,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -570,7 +567,7 @@ public class FileManagementControllerTests extends BaseTest {
paramMap.add("request", JSON.toJSONString(fileUploadRequest)); paramMap.add("request", JSON.toJSONString(fileUploadRequest));
mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap); mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_UPLOAD, paramMap);
returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); returnId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD) new CheckLogModel(returnId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_UPLOAD)
); );
FILE_ID_PATH.put(returnId, filePath); FILE_ID_PATH.put(returnId, filePath);
@ -699,7 +696,7 @@ public class FileManagementControllerTests extends BaseTest {
//重新上传并修改文件版本 //重新上传并修改文件版本
MvcResult mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_RE_UPLOAD, paramMap); MvcResult mvcResult = this.requestMultipartWithOkAndReturn(FileManagementRequestUtils.URL_FILE_RE_UPLOAD, paramMap);
String reUploadId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString(); String reUploadId = JSON.parseObject(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8), ResultHolder.class).getData().toString();
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(reUploadId, OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_RE_UPLOAD) new CheckLogModel(reUploadId, OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_RE_UPLOAD)
); );
FILE_ID_PATH.put(reUploadId, filePath); FILE_ID_PATH.put(reUploadId, filePath);
@ -888,7 +885,10 @@ public class FileManagementControllerTests extends BaseTest {
batchProcessDTO.setSelectAll(false); batchProcessDTO.setSelectAll(false);
batchProcessDTO.setProjectId(project.getId()); batchProcessDTO.setProjectId(project.getId());
batchProcessDTO.setSelectIds(new ArrayList<>(FILE_ID_PATH.keySet())); batchProcessDTO.setSelectIds(new ArrayList<>(FILE_ID_PATH.keySet()));
MvcResult mvcResult = this.requestPostDownloadFile(FileManagementRequestUtils.URL_FILE_BATCH_DOWNLOAD, null, batchProcessDTO);
MediaType zipMediaType = MediaType.parseMediaType("application/zip;charset=UTF-8");
MvcResult mvcResult = this.requestPostDownloadFile(FileManagementRequestUtils.URL_FILE_BATCH_DOWNLOAD, zipMediaType, batchProcessDTO);
byte[] fileBytes = mvcResult.getResponse().getContentAsByteArray(); byte[] fileBytes = mvcResult.getResponse().getContentAsByteArray();
Assertions.assertTrue(fileBytes.length > 0); Assertions.assertTrue(fileBytes.length > 0);
@ -896,12 +896,12 @@ public class FileManagementControllerTests extends BaseTest {
batchProcessDTO = new FileBatchProcessRequest(); batchProcessDTO = new FileBatchProcessRequest();
batchProcessDTO.setSelectAll(true); batchProcessDTO.setSelectAll(true);
batchProcessDTO.setProjectId(project.getId()); batchProcessDTO.setProjectId(project.getId());
mvcResult = this.requestPostDownloadFile(FileManagementRequestUtils.URL_FILE_BATCH_DOWNLOAD, null, batchProcessDTO); mvcResult = this.requestPostDownloadFile(FileManagementRequestUtils.URL_FILE_BATCH_DOWNLOAD, zipMediaType, batchProcessDTO);
fileBytes = mvcResult.getResponse().getContentAsByteArray(); fileBytes = mvcResult.getResponse().getContentAsByteArray();
Assertions.assertTrue(fileBytes.length > 0); Assertions.assertTrue(fileBytes.length > 0);
//重新下载全部文件 //重新下载全部文件
mvcResult = this.requestPostDownloadFile(FileManagementRequestUtils.URL_FILE_BATCH_DOWNLOAD, null, batchProcessDTO); mvcResult = this.requestPostDownloadFile(FileManagementRequestUtils.URL_FILE_BATCH_DOWNLOAD, zipMediaType, batchProcessDTO);
fileBytes = mvcResult.getResponse().getContentAsByteArray(); fileBytes = mvcResult.getResponse().getContentAsByteArray();
Assertions.assertTrue(fileBytes.length > 0); Assertions.assertTrue(fileBytes.length > 0);
@ -1001,6 +1001,7 @@ public class FileManagementControllerTests extends BaseTest {
} }
} }
//测试重复获取 //测试重复获取
FileInformationResponse testFileDTO = null;
for (FileInformationResponse fileDTO : fileList) { for (FileInformationResponse fileDTO : fileList) {
MvcResult originalResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_ORIGINAL, "admin", fileDTO.getId()), null); MvcResult originalResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_ORIGINAL, "admin", fileDTO.getId()), null);
Assertions.assertTrue(originalResult.getResponse().getContentAsByteArray().length > 0); Assertions.assertTrue(originalResult.getResponse().getContentAsByteArray().length > 0);
@ -1009,6 +1010,7 @@ public class FileManagementControllerTests extends BaseTest {
if (StringUtils.equalsIgnoreCase(fileDTO.getFileType(), "svg")) { if (StringUtils.equalsIgnoreCase(fileDTO.getFileType(), "svg")) {
compressedResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", fileDTO.getId()), MediaType.valueOf("image/svg+xml")); compressedResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", fileDTO.getId()), MediaType.valueOf("image/svg+xml"));
} else { } else {
testFileDTO = fileDTO;
compressedResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", fileDTO.getId()), null); compressedResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", fileDTO.getId()), null);
} }
byte[] fileBytes = compressedResult.getResponse().getContentAsByteArray(); byte[] fileBytes = compressedResult.getResponse().getContentAsByteArray();
@ -1024,8 +1026,27 @@ public class FileManagementControllerTests extends BaseTest {
} }
} }
//权限测试 //临时文件以及Minio中不存在预览图
FileRequest fileRequest = new FileRequest();
fileRequest.setFileName(testFileDTO.getId());
fileRequest.setFolder(DefaultRepositoryDir.getFileManagementPreviewDir(testFileDTO.getProjectId()));
fileRequest.setStorage(testFileDTO.getStorage());
fileService.deleteFile(fileRequest);
TempFileUtils.deleteTmpFile(testFileDTO.getId());
MvcResult compressedResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", testFileDTO.getId()), null);
byte[] fileBytes = compressedResult.getResponse().getContentAsByteArray();
Assertions.assertTrue(fileBytes.length > 0);
//minio里也没有
fileService.deleteFile(fileRequest);
fileRequest.setFolder(DefaultRepositoryDir.getFileManagementDir(testFileDTO.getProjectId()));
fileService.deleteFile(fileRequest);
TempFileUtils.deleteTmpFile(testFileDTO.getId());
compressedResult = this.requestGetDownloadFile(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", testFileDTO.getId()), null);
fileBytes = compressedResult.getResponse().getContentAsByteArray();
Assertions.assertEquals(fileBytes.length, 0);
//文件不存在原图缩略图两个接口校验 //文件不存在原图缩略图两个接口校验
mockMvc.perform(getRequestBuilder(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", IDGenerator.nextNum()))) mockMvc.perform(getRequestBuilder(String.format(FileManagementRequestUtils.URL_FILE_PREVIEW_COMPRESSED, "admin", IDGenerator.nextNum())))
@ -1069,7 +1090,7 @@ public class FileManagementControllerTests extends BaseTest {
updateRequest.setModuleId(a1a1Node.getId()); updateRequest.setModuleId(a1a1Node.getId());
this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_UPDATE, updateRequest); this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_UPDATE, updateRequest);
this.checkFileInformation(updateFileId, oldFileMetadata, updateRequest); this.checkFileInformation(updateFileId, oldFileMetadata, updateRequest);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(updateRequest.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_UPDATE) new CheckLogModel(updateRequest.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_UPDATE)
); );
@ -1189,7 +1210,7 @@ public class FileManagementControllerTests extends BaseTest {
//测试启用 //测试启用
this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_CHANGE_JAR_ENABLE, jarFileId, true)); this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_CHANGE_JAR_ENABLE, jarFileId, true));
this.checkFileEnable(jarFileId, true); this.checkFileEnable(jarFileId, true);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(jarFileId, OperationLogType.UPDATE, "/project/file/jar-file-status") new CheckLogModel(jarFileId, OperationLogType.UPDATE, "/project/file/jar-file-status")
); );
//测试禁用 //测试禁用
@ -1326,7 +1347,7 @@ public class FileManagementControllerTests extends BaseTest {
this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_DELETE, fileBatchProcessRequest); this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_DELETE, fileBatchProcessRequest);
this.checkFileIsDeleted(fileMetadataId, refId); this.checkFileIsDeleted(fileMetadataId, refId);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(fileMetadataId, OperationLogType.DELETE, FileManagementRequestUtils.URL_FILE_DELETE) new CheckLogModel(fileMetadataId, OperationLogType.DELETE, FileManagementRequestUtils.URL_FILE_DELETE)
); );
} }
@ -2072,10 +2093,10 @@ public class FileManagementControllerTests extends BaseTest {
this.checkModulePos(a2Node.getId(), a3Node.getId(), null, false); this.checkModulePos(a2Node.getId(), a3Node.getId(), null, false);
} }
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1Node.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_MODULE_MOVE) new CheckLogModel(a1Node.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_MODULE_MOVE)
); );
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a3Node.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_MODULE_MOVE) new CheckLogModel(a3Node.getId(), OperationLogType.UPDATE, FileManagementRequestUtils.URL_MODULE_MOVE)
); );
} }
@ -2096,7 +2117,7 @@ public class FileManagementControllerTests extends BaseTest {
}}); }});
this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_BATCH_UPDATE, moveRequest); this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_BATCH_UPDATE, moveRequest);
this.checkFileModule(picFileId, a1a1c1Node.getId()); this.checkFileModule(picFileId, a1a1c1Node.getId());
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(picFileId, OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_BATCH_UPDATE) new CheckLogModel(picFileId, OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_BATCH_UPDATE)
); );
//所有文件批量移动 //所有文件批量移动
@ -2203,7 +2224,7 @@ public class FileManagementControllerTests extends BaseTest {
BaseTreeNode a1b1Node = FileManagementBaseUtils.getNodeByName(this.getFileModuleTreeNode(), "a1-b1"); BaseTreeNode a1b1Node = FileManagementBaseUtils.getNodeByName(this.getFileModuleTreeNode(), "a1-b1");
this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_MODULE_DELETE, a1b1Node.getId())); this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_MODULE_DELETE, a1b1Node.getId()));
this.checkModuleIsEmpty(a1b1Node.getId()); this.checkModuleIsEmpty(a1b1Node.getId());
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1b1Node.getId(), OperationLogType.DELETE, FileManagementRequestUtils.URL_MODULE_DELETE) new CheckLogModel(a1b1Node.getId(), OperationLogType.DELETE, FileManagementRequestUtils.URL_MODULE_DELETE)
); );
@ -2211,7 +2232,7 @@ public class FileManagementControllerTests extends BaseTest {
BaseTreeNode a1a1Node = FileManagementBaseUtils.getNodeByName(this.getFileModuleTreeNode(), "a1-a1"); BaseTreeNode a1a1Node = FileManagementBaseUtils.getNodeByName(this.getFileModuleTreeNode(), "a1-a1");
this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_MODULE_DELETE, a1a1Node.getId())); this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_MODULE_DELETE, a1a1Node.getId()));
this.checkModuleIsEmpty(a1a1Node.getId()); this.checkModuleIsEmpty(a1a1Node.getId());
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(a1a1Node.getId(), OperationLogType.DELETE, FileManagementRequestUtils.URL_MODULE_DELETE) new CheckLogModel(a1a1Node.getId(), OperationLogType.DELETE, FileManagementRequestUtils.URL_MODULE_DELETE)
); );
@ -2416,7 +2437,7 @@ public class FileManagementControllerTests extends BaseTest {
@Order(100) @Order(100)
public void testLog() throws Exception { public void testLog() throws Exception {
Thread.sleep(5000); Thread.sleep(5000);
for (CheckLogModel checkLogModel : checkLogModelList) { for (CheckLogModel checkLogModel : LOG_CHECK_LIST) {
if (org.apache.commons.lang3.StringUtils.isEmpty(checkLogModel.getUrl())) { if (org.apache.commons.lang3.StringUtils.isEmpty(checkLogModel.getUrl())) {
this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType()); this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType());
} else { } else {

View File

@ -68,7 +68,7 @@ public class FileRepositoryControllerTest extends BaseTest {
@Resource @Resource
private CommonProjectService commonProjectService; private CommonProjectService commonProjectService;
List<RepositoryCheckLogModel> checkLogModelList = new ArrayList<>(); private static List<RepositoryCheckLogModel> LOG_CHECK_LIST = new ArrayList<>();
@BeforeEach @BeforeEach
public void initTestData() { public void initTestData() {
@ -166,7 +166,7 @@ public class FileRepositoryControllerTest extends BaseTest {
ResultHolder rh = JSON.parseObject(returnStr, ResultHolder.class); ResultHolder rh = JSON.parseObject(returnStr, ResultHolder.class);
repositoryId = rh.getData().toString(); repositoryId = rh.getData().toString();
this.checkFileRepository(repositoryId, createRequest.getProjectId(), createRequest.getName(), createRequest.getPlatform(), createRequest.getUrl(), createRequest.getToken(), createRequest.getUserName()); this.checkFileRepository(repositoryId, createRequest.getProjectId(), createRequest.getName(), createRequest.getPlatform(), createRequest.getUrl(), createRequest.getToken(), createRequest.getUserName());
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(repositoryId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_CREATE) new RepositoryCheckLogModel(repositoryId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_CREATE)
); );
@ -196,7 +196,7 @@ public class FileRepositoryControllerTest extends BaseTest {
returnStr = result.getResponse().getContentAsString(); returnStr = result.getResponse().getContentAsString();
rh = JSON.parseObject(returnStr, ResultHolder.class); rh = JSON.parseObject(returnStr, ResultHolder.class);
this.checkFileRepository(rh.getData().toString(), createRequest.getProjectId(), createRequest.getName(), createRequest.getPlatform(), createRequest.getUrl(), createRequest.getToken(), createRequest.getUserName()); this.checkFileRepository(rh.getData().toString(), createRequest.getProjectId(), createRequest.getName(), createRequest.getPlatform(), createRequest.getUrl(), createRequest.getToken(), createRequest.getUserName());
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(rh.getData().toString(), OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_CREATE) new RepositoryCheckLogModel(rh.getData().toString(), OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_CREATE)
); );
@ -271,7 +271,7 @@ public class FileRepositoryControllerTest extends BaseTest {
createRequest.setName("GITEA存储库改个名字"); createRequest.setName("GITEA存储库改个名字");
this.requestPostWithOkAndReturn(FileManagementRequestUtils.URL_FILE_REPOSITORY_UPDATE, createRequest); this.requestPostWithOkAndReturn(FileManagementRequestUtils.URL_FILE_REPOSITORY_UPDATE, createRequest);
this.checkFileRepository(repositoryId, project.getId(), "GITEA存储库改个名字", ModuleConstants.NODE_TYPE_GITEA, GITEA_URL, GITEA_TOKEN, null); this.checkFileRepository(repositoryId, project.getId(), "GITEA存储库改个名字", ModuleConstants.NODE_TYPE_GITEA, GITEA_URL, GITEA_TOKEN, null);
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(repositoryId, OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_REPOSITORY_UPDATE) new RepositoryCheckLogModel(repositoryId, OperationLogType.UPDATE, FileManagementRequestUtils.URL_FILE_REPOSITORY_UPDATE)
); );
//修改用户名 //修改用户名
@ -327,7 +327,7 @@ public class FileRepositoryControllerTest extends BaseTest {
this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_MODULE_DELETE, repositoryId)); this.requestGetWithOk(String.format(FileManagementRequestUtils.URL_MODULE_DELETE, repositoryId));
this.checkRepositoryDeleted(repositoryId); this.checkRepositoryDeleted(repositoryId);
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(repositoryId, OperationLogType.DELETE, FileManagementRequestUtils.URL_MODULE_DELETE) new RepositoryCheckLogModel(repositoryId, OperationLogType.DELETE, FileManagementRequestUtils.URL_MODULE_DELETE)
); );
@ -343,7 +343,7 @@ public class FileRepositoryControllerTest extends BaseTest {
ResultHolder rh = JSON.parseObject(returnStr, ResultHolder.class); ResultHolder rh = JSON.parseObject(returnStr, ResultHolder.class);
repositoryId = rh.getData().toString(); repositoryId = rh.getData().toString();
this.checkFileRepository(repositoryId, createRequest.getProjectId(), createRequest.getName(), createRequest.getPlatform(), createRequest.getUrl(), createRequest.getToken(), createRequest.getUserName()); this.checkFileRepository(repositoryId, createRequest.getProjectId(), createRequest.getName(), createRequest.getPlatform(), createRequest.getUrl(), createRequest.getToken(), createRequest.getUserName());
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(repositoryId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_CREATE) new RepositoryCheckLogModel(repositoryId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_CREATE)
); );
@ -393,7 +393,7 @@ public class FileRepositoryControllerTest extends BaseTest {
MvcResult result = this.requestPostWithOkAndReturn(FileManagementRequestUtils.URL_FILE_REPOSITORY_FILE_ADD, request); MvcResult result = this.requestPostWithOkAndReturn(FileManagementRequestUtils.URL_FILE_REPOSITORY_FILE_ADD, request);
String fileId = JSON.parseObject(result.getResponse().getContentAsString(), ResultHolder.class).getData().toString(); String fileId = JSON.parseObject(result.getResponse().getContentAsString(), ResultHolder.class).getData().toString();
this.checkRepositoryFile(fileId, request); this.checkRepositoryFile(fileId, request);
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(fileId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_FILE_ADD) new RepositoryCheckLogModel(fileId, OperationLogType.ADD, FileManagementRequestUtils.URL_FILE_REPOSITORY_FILE_ADD)
); );
getFileMessage(fileId); getFileMessage(fileId);
@ -644,7 +644,7 @@ public class FileRepositoryControllerTest extends BaseTest {
fileBatchProcessRequest.setSelectIds(fileList); fileBatchProcessRequest.setSelectIds(fileList);
this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_DELETE, fileBatchProcessRequest); this.requestPostWithOk(FileManagementRequestUtils.URL_FILE_DELETE, fileBatchProcessRequest);
for (String fileId : fileList) { for (String fileId : fileList) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new RepositoryCheckLogModel(fileId, OperationLogType.DELETE, FileManagementRequestUtils.URL_FILE_DELETE) new RepositoryCheckLogModel(fileId, OperationLogType.DELETE, FileManagementRequestUtils.URL_FILE_DELETE)
); );
this.checkRepositoryFileDeleted(fileId); this.checkRepositoryFileDeleted(fileId);
@ -655,7 +655,7 @@ public class FileRepositoryControllerTest extends BaseTest {
@Order(100) @Order(100)
public void testLog() throws Exception { public void testLog() throws Exception {
Thread.sleep(5000); Thread.sleep(5000);
for (RepositoryCheckLogModel checkLogModel : checkLogModelList) { for (RepositoryCheckLogModel checkLogModel : LOG_CHECK_LIST) {
if (org.apache.commons.lang3.StringUtils.isEmpty(checkLogModel.getUrl())) { if (org.apache.commons.lang3.StringUtils.isEmpty(checkLogModel.getUrl())) {
this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType()); this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType());
} else { } else {

View File

@ -45,7 +45,7 @@ public class UserLogService {
private UserRoleMapper userRoleMapper; private UserRoleMapper userRoleMapper;
//批量添加用户记录日志 //批量添加用户记录日志
public List<LogDTO> getBatchAddLogs(@Valid List<User> userList) { public List<LogDTO> getBatchAddLogs(@Valid List<User> userList, String requestPath) {
List<LogDTO> logs = new ArrayList<>(); List<LogDTO> logs = new ArrayList<>();
userList.forEach(user -> { userList.forEach(user -> {
LogDTO log = LogDTOBuilder.builder() LogDTO log = LogDTOBuilder.builder()
@ -54,7 +54,7 @@ public class UserLogService {
.type(OperationLogType.ADD.name()) .type(OperationLogType.ADD.name())
.module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE) .module(OperationLogModule.SETTING_SYSTEM_USER_SINGLE)
.method(HttpMethodConstants.POST.name()) .method(HttpMethodConstants.POST.name())
.path("/system/user/addUser") .path(requestPath)
.sourceId(user.getId()) .sourceId(user.getId())
.content(user.getName() + "(" + user.getEmail() + ")") .content(user.getName() + "(" + user.getEmail() + ")")
.originalValue(JSON.toJSONBytes(user)) .originalValue(JSON.toJSONBytes(user))

View File

@ -113,10 +113,10 @@ public class UserService {
this.validateUserInfo(userCreateDTO.getUserInfoList().stream().map(UserCreateInfo::getEmail).collect(Collectors.toList())); this.validateUserInfo(userCreateDTO.getUserInfoList().stream().map(UserCreateInfo::getEmail).collect(Collectors.toList()));
//检查用户权限的合法性 //检查用户权限的合法性
globalUserRoleService.checkRoleIsGlobalAndHaveMember(userCreateDTO.getUserRoleIdList(), true); globalUserRoleService.checkRoleIsGlobalAndHaveMember(userCreateDTO.getUserRoleIdList(), true);
return this.saveUserAndRole(userCreateDTO, source, operator); return this.saveUserAndRole(userCreateDTO, source, operator, "/system/user/addUser");
} }
private UserBatchCreateDTO saveUserAndRole(UserBatchCreateDTO userCreateDTO, String source, String operator) { private UserBatchCreateDTO saveUserAndRole(UserBatchCreateDTO userCreateDTO, String source, String operator, String requestPath) {
long createTime = System.currentTimeMillis(); long createTime = System.currentTimeMillis();
List<User> saveUserList = new ArrayList<>(); List<User> saveUserList = new ArrayList<>();
//添加用户 //添加用户
@ -136,7 +136,7 @@ public class UserService {
} }
userRoleRelationService.batchSave(userCreateDTO.getUserRoleIdList(), saveUserList); userRoleRelationService.batchSave(userCreateDTO.getUserRoleIdList(), saveUserList);
//写入操作日志 //写入操作日志
operationLogService.batchAdd(userLogService.getBatchAddLogs(saveUserList)); operationLogService.batchAdd(userLogService.getBatchAddLogs(saveUserList, requestPath));
return userCreateDTO; return userCreateDTO;
} }
@ -299,7 +299,7 @@ public class UserService {
userCreateInfoList.add(userCreateInfo); userCreateInfoList.add(userCreateInfo);
}); });
userBatchCreateDTO.setUserInfoList(userCreateInfoList); userBatchCreateDTO.setUserInfoList(userCreateInfoList);
this.saveUserAndRole(userBatchCreateDTO, source, sessionId); this.saveUserAndRole(userBatchCreateDTO, source, sessionId, "/system/user/import");
} }

View File

@ -102,7 +102,7 @@ public class UserControllerTests extends BaseTest {
UserRequestUtils userRequestUtils = null; UserRequestUtils userRequestUtils = null;
List<CheckLogModel> checkLogModelList = new ArrayList<>(); private static final List<CheckLogModel> LOG_CHECK_LIST = new ArrayList<>();
@Override @Override
@BeforeEach @BeforeEach
@ -340,7 +340,7 @@ public class UserControllerTests extends BaseTest {
user.setName("TEST-UPDATE"); user.setName("TEST-UPDATE");
userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE)
); );
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
@ -349,7 +349,7 @@ public class UserControllerTests extends BaseTest {
user.setEmail("songtianyang-test-email@12138.com"); user.setEmail("songtianyang-test-email@12138.com");
userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE)
); );
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
@ -358,7 +358,7 @@ public class UserControllerTests extends BaseTest {
user.setPhone("18511112222"); user.setPhone("18511112222");
userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE)
); );
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
@ -369,14 +369,14 @@ public class UserControllerTests extends BaseTest {
); );
response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE)
); );
UserParamUtils.compareUserDTO(response, checkDTO); UserParamUtils.compareUserDTO(response, checkDTO);
//更改用户组(把上面的情况添加别的权限) //更改用户组(把上面的情况添加别的权限)
userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE)
); );
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
@ -386,7 +386,7 @@ public class UserControllerTests extends BaseTest {
BeanUtils.copyBean(user, USER_LIST.get(0)); BeanUtils.copyBean(user, USER_LIST.get(0));
userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST); userMaintainRequest = UserParamUtils.getUserUpdateDTO(user, USER_ROLE_LIST);
response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class); response = userRequestUtils.parseObjectFromMvcResult(userRequestUtils.responsePost(UserRequestUtils.URL_USER_UPDATE, userMaintainRequest), UserEditRequest.class);
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE) new CheckLogModel(response.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE)
); );
checkDTO = this.getUserByEmail(user.getEmail()); checkDTO = this.getUserByEmail(user.getEmail());
@ -448,7 +448,7 @@ public class UserControllerTests extends BaseTest {
userChangeEnableRequest.setEnable(false); userChangeEnableRequest.setEnable(false);
this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk()); this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk());
for (String item : userChangeEnableRequest.getSelectIds()) { for (String item : userChangeEnableRequest.getSelectIds()) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item, OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE_ENABLE) new CheckLogModel(item, OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE_ENABLE)
); );
} }
@ -460,7 +460,7 @@ public class UserControllerTests extends BaseTest {
userChangeEnableRequest.setEnable(true); userChangeEnableRequest.setEnable(true);
this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk()); this.requestPost(UserRequestUtils.URL_USER_UPDATE_ENABLE, userChangeEnableRequest, status().isOk());
for (String item : userChangeEnableRequest.getSelectIds()) { for (String item : userChangeEnableRequest.getSelectIds()) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item, OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE_ENABLE) new CheckLogModel(item, OperationLogType.UPDATE, UserRequestUtils.URL_USER_UPDATE_ENABLE)
); );
} }
@ -506,7 +506,7 @@ public class UserControllerTests extends BaseTest {
UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值
List<UserDTO> userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 List<UserDTO> userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList) { for (UserDTO item : userDTOList) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT)
); );
} }
@ -536,7 +536,7 @@ public class UserControllerTests extends BaseTest {
UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList) { for (UserDTO item : userDTOList) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT)
); );
} }
@ -550,7 +550,7 @@ public class UserControllerTests extends BaseTest {
UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex); UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);
userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList) { for (UserDTO item : userDTOList) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT)
); );
} }
@ -573,7 +573,7 @@ public class UserControllerTests extends BaseTest {
UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值 UserParamUtils.checkImportResponse(response, importSuccessData, errorDataIndex);//检查返回值
userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库 userDTOList = this.checkImportUserInDb(userImportReportDTOByFile);//检查数据已入库
for (UserDTO item : userDTOList) { for (UserDTO item : userDTOList) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT) new CheckLogModel(item.getId(), OperationLogType.ADD, UserRequestUtils.URL_USER_IMPORT)
); );
} }
@ -714,7 +714,7 @@ public class UserControllerTests extends BaseTest {
UserExample userExample = new UserExample(); UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo("admin").andPasswordEqualTo(CodingUtils.md5("metersphere")); userExample.createCriteria().andIdEqualTo("admin").andPasswordEqualTo(CodingUtils.md5("metersphere"));
Assertions.assertEquals(1, userMapper.countByExample(userExample)); Assertions.assertEquals(1, userMapper.countByExample(userExample));
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel("admin", OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD) new CheckLogModel("admin", OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD)
); );
} }
@ -737,7 +737,7 @@ public class UserControllerTests extends BaseTest {
UserExample userExample = new UserExample(); UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtils.md5(checkUser.getEmail())); userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtils.md5(checkUser.getEmail()));
Assertions.assertEquals(1, userMapper.countByExample(userExample)); Assertions.assertEquals(1, userMapper.countByExample(userExample));
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(checkUser.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD) new CheckLogModel(checkUser.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD)
); );
} }
@ -763,7 +763,7 @@ public class UserControllerTests extends BaseTest {
UserExample userExample = new UserExample(); UserExample userExample = new UserExample();
userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtils.md5(checkUser.getEmail())); userExample.createCriteria().andIdEqualTo(checkUser.getId()).andPasswordEqualTo(CodingUtils.md5(checkUser.getEmail()));
Assertions.assertEquals(1, userMapper.countByExample(userExample)); Assertions.assertEquals(1, userMapper.countByExample(userExample));
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(checkUser.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD) new CheckLogModel(checkUser.getId(), OperationLogType.UPDATE, UserRequestUtils.URL_USER_RESET_PASSWORD)
); );
} }
@ -790,7 +790,7 @@ public class UserControllerTests extends BaseTest {
); );
//检查日志 //检查日志
for (String userID : request.getSelectIds()) { for (String userID : request.getSelectIds()) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_USER_ROLE_RELATION) new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_USER_ROLE_RELATION)
); );
} }
@ -926,7 +926,7 @@ public class UserControllerTests extends BaseTest {
} }
//检查日志 //检查日志
for (String userID : request.getSelectIds()) { for (String userID : request.getSelectIds()) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_ADD_PROJECT_MEMBER) new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_ADD_PROJECT_MEMBER)
); );
} }
@ -970,7 +970,7 @@ public class UserControllerTests extends BaseTest {
} }
//检查日志 //检查日志
for (String userID : request.getSelectIds()) { for (String userID : request.getSelectIds()) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_ADD_ORGANIZATION_MEMBER) new CheckLogModel(userID, OperationLogType.UPDATE, UserRequestUtils.URL_ADD_ORGANIZATION_MEMBER)
); );
} }
@ -1077,7 +1077,7 @@ public class UserControllerTests extends BaseTest {
User user = userMapper.selectByPrimaryKey(deleteUser.getId()); User user = userMapper.selectByPrimaryKey(deleteUser.getId());
Assertions.assertTrue(user.getDeleted()); Assertions.assertTrue(user.getDeleted());
//检查日志 //检查日志
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(deleteUser.getId(), OperationLogType.DELETE, UserRequestUtils.URL_USER_DELETE) new CheckLogModel(deleteUser.getId(), OperationLogType.DELETE, UserRequestUtils.URL_USER_DELETE)
); );
removeList.add(deleteUser); removeList.add(deleteUser);
@ -1113,7 +1113,7 @@ public class UserControllerTests extends BaseTest {
@Order(101) @Order(101)
public void testLog() throws Exception { public void testLog() throws Exception {
Thread.sleep(5000); Thread.sleep(5000);
for (CheckLogModel checkLogModel : checkLogModelList) { for (CheckLogModel checkLogModel : LOG_CHECK_LIST) {
if (StringUtils.isEmpty(checkLogModel.getUrl())) { if (StringUtils.isEmpty(checkLogModel.getUrl())) {
this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType()); this.checkLog(checkLogModel.getResourceId(), checkLogModel.getOperationType());
} else { } else {
@ -1148,7 +1148,7 @@ public class UserControllerTests extends BaseTest {
private void addUser2List(MvcResult mvcResult) throws Exception { private void addUser2List(MvcResult mvcResult) throws Exception {
UserBatchCreateDTO userMaintainRequest = userRequestUtils.parseObjectFromMvcResult(mvcResult, UserBatchCreateDTO.class); UserBatchCreateDTO userMaintainRequest = userRequestUtils.parseObjectFromMvcResult(mvcResult, UserBatchCreateDTO.class);
for (UserCreateInfo item : userMaintainRequest.getUserInfoList()) { for (UserCreateInfo item : userMaintainRequest.getUserInfoList()) {
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(item.getId(), OperationLogType.ADD, null) new CheckLogModel(item.getId(), OperationLogType.ADD, null)
); );
} }
@ -1188,7 +1188,7 @@ public class UserControllerTests extends BaseTest {
UserInviteResponse response = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), UserInviteResponse.class); UserInviteResponse response = JSON.parseObject(JSON.toJSONString(resultHolder.getData()), UserInviteResponse.class);
Assertions.assertEquals(2, response.getInviteIds().size()); Assertions.assertEquals(2, response.getInviteIds().size());
//检查日志 此处日志的资源是邀请的用户即admin //检查日志 此处日志的资源是邀请的用户即admin
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel("admin", OperationLogType.ADD, UserRequestUtils.URL_INVITE) new CheckLogModel("admin", OperationLogType.ADD, UserRequestUtils.URL_INVITE)
); );
INVITE_RECORD_ID_LIST.addAll(response.getInviteIds()); INVITE_RECORD_ID_LIST.addAll(response.getInviteIds());
@ -1263,7 +1263,7 @@ public class UserControllerTests extends BaseTest {
ResultHolder resultHolder = JSON.parseObject(resultHolderStr, ResultHolder.class); ResultHolder resultHolder = JSON.parseObject(resultHolderStr, ResultHolder.class);
//检查日志 此处日志的资源是邀请的用户即admin //检查日志 此处日志的资源是邀请的用户即admin
checkLogModelList.add( LOG_CHECK_LIST.add(
new CheckLogModel(resultHolder.getData().toString(), OperationLogType.ADD, UserRequestUtils.URL_INVITE_REGISTER) new CheckLogModel(resultHolder.getData().toString(), OperationLogType.ADD, UserRequestUtils.URL_INVITE_REGISTER)
); );
} }