instruction
stringlengths
77
90.1k
package cn.chinatowercom.dataflow.backend.controller;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.security.util.SecurityUtils;import io.swagger.annotations.Api;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @author catfishing * @date 2023/2/7 基础功能管理 */@Slf4j@RestController@RequiredArgsConstructor@RequestMapping("/base")@Tag(name = "基础功能管理")@Api(value = "base", tags = "基础功能管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class BaseController { // 获取当前用户信息 @PostMapping("/getCurrentUserInfo") public R<String> getCurrentUserInfo() { String username = SecurityUtils.getUser().getUsername(); return R.ok(username); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import cn.chinatowercom.dataflow.backend.entity.dto.SysDatasourceConf;import cn.chinatowercom.dataflow.backend.service.SysDatasourceConfService;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;/** * 数据源表 * * @author catfishing * @date 2023-02-01 14:12:13 */@RestController@RequiredArgsConstructor@RequestMapping("/dataSetsManage" )@Tag(name = "数据源表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class DataSetsManageController { private final SysDatasourceConfService sysDatasourceConfService; /** * 分页查询 * @param page 分页对象 * @param sysDatasourceConf 数据源表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysdatasourceconf_get')" ) public R<IPage<SysDatasourceConf>> getSysDatasourceConfPage(Page<SysDatasourceConf> page, SysDatasourceConf sysDatasourceConf) { return R.ok(sysDatasourceConfService.page(page, Wrappers.query(sysDatasourceConf))); } /** * 通过id查询数据源表 * @param id id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{id}" ) //@PreAuthorize("@pms.hasPermission('backend_sysdatasourceconf_get')" ) public R<SysDatasourceConf> getById(@PathVariable("id" ) Long id) { return R.ok(sysDatasourceConfService.getById(id)); } /** * 新增数据源表 * @param sysDatasourceConf 数据源表 * @return R */ @Operation(summary = "新增数据源表", description = "新增数据源表") @SysLog("新增数据源表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysdatasourceconf_add')" ) public R<Boolean> save(@RequestBody SysDatasourceConf sysDatasourceConf) { return R.ok(sysDatasourceConfService.save(sysDatasourceConf)); } /** * 修改数据源表 * @param sysDatasourceConf 数据源表 * @return R */ @Operation(summary = "修改数据源表", description = "修改数据源表") @SysLog("修改数据源表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysdatasourceconf_edit')" ) public R<Boolean> updateById(@RequestBody SysDatasourceConf sysDatasourceConf) { return R.ok(sysDatasourceConfService.updateById(sysDatasourceConf)); } /** * 通过id删除数据源表 * @param id id * @return R */ @Operation(summary = "通过id删除数据源表", description = "通过id删除数据源表") @SysLog("通过id删除数据源表" ) @DeleteMapping("/{id}" ) //@PreAuthorize("@pms.hasPermission('backend_sysdatasourceconf_del')" ) public R<Boolean> removeById(@PathVariable Long id) { return R.ok(sysDatasourceConfService.removeById(id)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.SysDict;import cn.chinatowercom.dataflow.backend.entity.SysDictItem;import cn.chinatowercom.dataflow.backend.service.SysDictItemService;import cn.chinatowercom.dataflow.backend.service.SysDictService;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import io.swagger.annotations.Api;import lombok.RequiredArgsConstructor;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.Cacheable;import org.springframework.security.access.prepost.PreAuthorize;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;import java.util.List;/** * <p> * 数据库字段字典值映射 * </p> * * @author catfishing * @since 2023-03-20 */@RestController@RequiredArgsConstructor@RequestMapping("/dict")@Api(value = "dict", tags = "数据库字段字典值映射")public class DictController { private final SysDictItemService sysDictItemService; private final SysDictService sysDictService; /** * 通过ID查询字典信息 * @param id ID * @return 字典信息 */ @GetMapping("/{id:\\d+}") public R<SysDict> getById(@PathVariable Long id) { return R.ok(sysDictService.getById(id)); } /** * 分页查询字典信息 * @param page 分页对象 * @return 分页对象 */ @GetMapping("/page") public R<IPage<SysDict>> getDictPage(Page page, SysDict sysDict) { return R.ok(sysDictService.page(page, Wrappers.query(sysDict))); } /** * 通过字典类型查找字典 * @param type 类型 * @return 同类型字典 */ @GetMapping("/type/{type}") @Cacheable(value = CacheConstants.DICT_DETAILS, key = "#type") public R<List<SysDictItem>> getDictByType(@PathVariable String type) { return R.ok(sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getType, type))); } /** * 添加字典 * @param sysDict 字典信息 * @return success、false */ @SysLog("添加字典") @PostMapping @PreAuthorize("@pms.hasPermission('sys_dict_add')") public R<Boolean> save(@Valid @RequestBody SysDict sysDict) { return R.ok(sysDictService.save(sysDict)); } /** * 删除字典,并且清除字典缓存 * @param id ID * @return R */ @SysLog("删除字典") @DeleteMapping("/{id:\\d+}") @PreAuthorize("@pms.hasPermission('sys_dict_del')") public R<Object> removeById(@PathVariable Long id) { sysDictService.removeDict(id); return R.ok(); } /** * 修改字典 * @param sysDict 字典信息 * @return success/false */ @PutMapping @SysLog("修改字典") @PreAuthorize("@pms.hasPermission('sys_dict_edit')") public R<String> updateById(@Valid @RequestBody SysDict sysDict) { sysDictService.updateDict(sysDict); return R.ok(); } /** * 分页查询 * @param page 分页对象 * @param sysDictItem 字典项 * @return */ @GetMapping("/item/page") public R<IPage<SysDictItem>> getSysDictItemPage(Page page, SysDictItem sysDictItem) { return R.ok(sysDictItemService.page(page, Wrappers.query(sysDictItem))); } /** * 通过id查询字典项 * @param id id * @return R */ @GetMapping("/item/{id:\\d+}") public R<SysDictItem> getDictItemById(@PathVariable("id") Long id) { return R.ok(sysDictItemService.getById(id)); } /** * 新增字典项 * @param sysDictItem 字典项 * @return R */ @SysLog("新增字典项") @PostMapping("/item") @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) public R<Boolean> save(@RequestBody SysDictItem sysDictItem) { return R.ok(sysDictItemService.save(sysDictItem)); } /** * 修改字典项 * @param sysDictItem 字典项 * @return R */ @SysLog("修改字典项") @PutMapping("/item") public R<String> updateById(@RequestBody SysDictItem sysDictItem) { sysDictItemService.updateDictItem(sysDictItem); return R.ok(); } /** * 通过id删除字典项 * @param id id * @return R */ @SysLog("删除字典项") @DeleteMapping("/item/{id:\\d+}") public R<String> removeDictItemById(@PathVariable Long id) { sysDictItemService.removeDictItem(id); return R.ok(); } @SysLog("清除字典缓存") @DeleteMapping("/cache") @PreAuthorize("@pms.hasPermission('sys_dict_del')") public R<String> clearDictCache() { sysDictService.clearDictCache(); return R.ok(); }}
package cn.chinatowercom.dataflow.backend.controller;import cn.chinatowercom.dataflow.backend.entity.SysImportFile;import com.alibaba.fastjson.JSON;import cn.chinatowercom.dataflow.backend.constant.ImportFileType;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportInfoDTO;import cn.chinatowercom.dataflow.backend.service.SysImportFileService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * @author hj * @Description 文件管理类 * @createTime 2023/02/01 14:55 */@NoAuth(value = false)@Slf4j@RestController@RequiredArgsConstructor@RequestMapping("/fileManage")@Tag(name = "文件管理")public class FileManageController { @Autowired private SysImportFileService sysImportFileService; /** * 导入文件上传 * * @param importInfo * @param multipartFile * @return */ @Operation(summary = "导入文件上传", description = "导入文件上传") @PostMapping("/uploadImportFile") @SysLog("导入文件上传") public R uploadImportFile(@RequestParam("importInfo") String importInfo, @RequestParam("file") MultipartFile multipartFile) { try { SysImportInfoDTO sysImportInfoDTO = JSON.parseObject(importInfo, SysImportInfoDTO.class); if (StringUtils.isBlank(sysImportInfoDTO.getTemplateId())) { return R.failed("模板id不能为空"); } if (StringUtils.isBlank(sysImportInfoDTO.getProjectId())) { return R.failed("项目id不能为空"); } if (multipartFile.isEmpty()) { return R.failed("文件不能为空"); } if (!checkFileType(multipartFile)) { return R.failed("文件类型错误,文件必须是excel文件或压缩文件"); } return sysImportFileService.uploadImportFile(sysImportInfoDTO, multipartFile); } catch (Exception e) { log.error("上传文件失败:{}", e); return R.failed("上传文件失败"); } } /** * 初步根据文件后缀验证上传文件的类型是否是excel或支持的压缩文件类型 * * @param file * @return */ private boolean checkFileType(MultipartFile file) { String originalFilename = file.getOriginalFilename(); if (!StringUtils.isBlank(originalFilename)) { String suffix = originalFilename.substring(originalFilename.lastIndexOf('.')); //先判断后缀名 if (ImportFileType.FILE_XLS.equalsIgnoreCase(suffix) || ImportFileType.FILE_XLSX.equalsIgnoreCase(suffix) || ImportFileType.FILE_CSV.equalsIgnoreCase(suffix) || ImportFileType.FILE_ZIP.equalsIgnoreCase(suffix) || ImportFileType.FILE_RAR.equalsIgnoreCase(suffix) || ImportFileType.FILE__7Z.equalsIgnoreCase(suffix) || ImportFileType.FILE_7Z.equalsIgnoreCase(suffix) || ImportFileType.FILE_TAR__GZ.equalsIgnoreCase(suffix) || ImportFileType.FILE_TAR_GZ.equalsIgnoreCase(suffix) || ImportFileType.FILE_TAR.equalsIgnoreCase(suffix) || ImportFileType.FILE_GZ.equalsIgnoreCase(suffix) || ImportFileType.FILE_BZ2.equalsIgnoreCase(suffix) || ImportFileType.FILE_TAR_BZ2.equalsIgnoreCase(suffix) ) { return true; } } return false; } /** * 上传文件 * * @param multipartFile * @return */ @Operation(summary = "文件上传", description = "文件上传") @PostMapping("/uploadFile") @SysLog("上传文件") public R uploadFile(@RequestParam("fileGrpup") Integer fileGrpup, @RequestParam("file") MultipartFile multipartFile) { try { if (multipartFile.isEmpty()) { return R.failed("文件不能为空"); } if (!checkFileType(multipartFile)) { return R.failed("文件类型错误,文件必须是excel文件或压缩文件"); } Long fileId = sysImportFileService.uploadFile(fileGrpup,multipartFile); return R.ok(fileId); } catch (Exception e) { log.error("上传文件保存失败:{}", e); return R.failed("上传文件保存失败"); } } /** * 下载文件 * * @param fileId * @param request * @param response * @return */ @Operation(summary = "文件下载", description = "文件下载") @GetMapping("/downFile") @SysLog("文件下载") public void downFile(@RequestParam("fileId") String fileId, @RequestParam(value = "contentType", required = false) String contentType, HttpServletRequest request, HttpServletResponse response) { try { sysImportFileService.downFile(fileId, contentType, request, response); } catch (Exception e) { log.error("文件下载失败:{}", e); } } /** * 新增文件信息表 * @param sysImportFile 文件信息表 * @return R */ @Operation(summary = "新增文件信息表", description = "新增文件信息表") @SysLog("新增文件信息表" ) @PostMapping public Long save(@RequestBody SysImportFile sysImportFile) { if(sysImportFileService.save(sysImportFile)) return sysImportFile.getId(); return null; } /** * 通过id查询文件信息 * @param id id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{id}" ) public SysImportFile getById(@PathVariable("id" ) Long id) { return sysImportFileService.getById(id); }}
package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.dto.SysProjectInfo;import cn.chinatowercom.dataflow.backend.service.SysProjectInfoService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import io.swagger.annotations.Api;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;/** * 项目信息表 * * @author catfishing * @date 2023-02-01 14:25:17 */@RestController@RequiredArgsConstructor@RequestMapping("/projectManage" )@Tag(name = "项目信息表管理")@Api(value = "projectManage", tags = "项目信息表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class ProjectManageController { private final SysProjectInfoService sysProjectInfoService; /** * 分页查询 * @param page 分页对象 * @param sysProjectInfo 项目信息表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysprojectinfo_get')" ) public R getSysProjectInfoPage(Page page, SysProjectInfo sysProjectInfo) { return R.ok(sysProjectInfoService.page(page, Wrappers.query(sysProjectInfo))); } /** * 通过id查询项目信息表 * @param projectId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{projectId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysprojectinfo_get')" ) public R getById(@PathVariable("projectId" ) Long projectId) { return R.ok(sysProjectInfoService.getById(projectId)); } /** * 新增项目信息表 * @param sysProjectInfo 项目信息表 * @return R */ @Operation(summary = "新增项目信息表", description = "新增项目信息表") @SysLog("新增项目信息表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysprojectinfo_add')" ) public R save(@RequestBody SysProjectInfo sysProjectInfo) { return R.ok(sysProjectInfoService.save(sysProjectInfo)); } /** * 修改项目信息表 * @param sysProjectInfo 项目信息表 * @return R */ @Operation(summary = "修改项目信息表", description = "修改项目信息表") @SysLog("修改项目信息表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysprojectinfo_edit')" ) public R updateById(@RequestBody SysProjectInfo sysProjectInfo) { return R.ok(sysProjectInfoService.updateById(sysProjectInfo)); } /** * 通过id删除项目信息表 * @param projectId id * @return R */ @Operation(summary = "通过id删除项目信息表", description = "通过id删除项目信息表") @SysLog("通过id删除项目信息表" ) @DeleteMapping("/{projectId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysprojectinfo_del')" ) public R removeById(@PathVariable String projectId) { return R.ok(sysProjectInfoService.removeById(projectId)); }}
package cn.chinatowercom.dataflow.backend.controller;import com.alibaba.fastjson.JSONObject;import cn.chinatowercom.dataflow.backend.service.ScdfResourcesService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import io.swagger.annotations.Api;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;/** * @author liangbing * @date 2023/4/5 资源管理 */@Slf4j@RestController@RequiredArgsConstructor@RequestMapping("/resources")@Tag(name = "资源管理")@Api(value = "resources", tags = "资源管理")public class ScdfResourcesController { @Autowired private ScdfResourcesService scdfResourcesService; /** * 根据导入ID查询任务列表 * * @return R */ @Operation(summary = "根据导入ID查询任务列表", description = "根据导入ID查询任务列表") @SysLog("根据导入ID查询任务列表") @PostMapping("/tasks/executions") public R getTasksExecutionsByImportId( @RequestParam("projectId") String projectId, @RequestParam(value = "importId", required = false) Long importId, @RequestParam(value = "page", required = false, defaultValue = "0") int page, @RequestParam(value = "size", required = false, defaultValue = "10") int size) { try { if(importId == null || importId == 0l){ return R.ok(scdfResourcesService.getTasksExecutions(projectId, page, size)); } else { return R.ok(scdfResourcesService.getTasksExecutionsByImportId(projectId, importId, page, size)); } } catch (Exception e) { return R.failed(e.getMessage()); } } /** * 根据任务Id获取到externalExecutionId参数,查询job日志接口需要使用 * * @return R */ @Operation(summary = "根据任务Id获取到externalExecutionId参数,查询job日志接口需要使用", description = "根据任务Id获取到externalExecutionId参数,查询job日志接口需要使用") @SysLog("根据任务Id获取到externalExecutionId参数,查询job日志接口需要使用") @PostMapping("/tasks/executions/{executionId}") public R getTasksExecutionById( @PathVariable("executionId") Long executionId, @RequestParam(value = "projectId", required = false, defaultValue = "1") String projectId ) { try { JSONObject jsonObject = scdfResourcesService.getTasksExecutionById(projectId, executionId); return R.ok(jsonObject); } catch (Exception e) { return R.failed(e.getMessage()); } } /** * 查询job日志信息 * * @return R */ @Operation(summary = "查询job日志信息", description = "查询job日志信息") @SysLog("查询job日志信息") @PostMapping("/tasks/logs/{externalTaskExecutionId}") public R getTasksLogsById( @PathVariable("externalTaskExecutionId") String externalTaskExecutionId, @RequestParam(value = "projectId", required = false, defaultValue = "1") String projectId ) { try { String response = scdfResourcesService.getTasksLogsById(projectId, externalTaskExecutionId); return R.ok(response); } catch (Exception e) { return R.failed(e.getMessage()); } } /** * 根据任务ID查询job列表信息 * * @return R */ @Operation(summary = "根据任务ID查询job列表信息", description = "根据任务ID查询job列表信息") @SysLog("根据任务ID查询job列表信息") @PostMapping("/jobs/thinexecutions") public R getJobsThinExecutionsByTaskId( @RequestParam(value = "projectId", required = false, defaultValue = "1") String projectId, @RequestParam(value = "taskExecutionId", required = false) Long taskExecutionId, @RequestParam(value = "page", required = false, defaultValue = "0") int page, @RequestParam(value = "size", required = false, defaultValue = "10") int size ) { try { return R.ok(scdfResourcesService.getJobsThinExecutionsByTaskId(projectId, taskExecutionId, page, size)); } catch (Exception e) { return R.failed(e.getMessage()); } } /** * 根据JOB-ID查询step列表信息 * * @return R */ @Operation(summary = "根据JOB-ID查询step列表信息", description = "根据JOB-ID查询step列表信息") @SysLog("根据JOB-ID查询step列表信息") @PostMapping("/jobs/executions/{jobId}/steps") public R getJobsExecutionStepsByJobExecutionId( @RequestParam(value = "projectId", required = false, defaultValue = "1") String projectId, @PathVariable(value = "jobId") Long jobId, @RequestParam(value = "page", required = false, defaultValue = "0") int page, @RequestParam(value = "size", required = false, defaultValue = "10") int size ) { try { if(null == jobId) { return R.failed("jobExecutionId is null"); } else { return R.ok(scdfResourcesService.getJobsExecutionStepsByJobExecutionId(projectId, jobId, page, size)); } } catch (Exception e) { return R.failed(e.getMessage()); } } /** * 根据job执行id查询job详细信息 * @param executionId job执行id * @param projectId 项目id * @return R */ @Operation(summary = "根据job执行id查询job详细信息", description = "根据job执行id查询job详细信息") @SysLog("根据job执行id查询job详细信息") @PostMapping("/jobs/executions/{executionId}") public R getJobDetailById( @PathVariable("executionId") Long executionId, @RequestParam(value = "projectId") String projectId ) { try { JSONObject jsonObject = scdfResourcesService.getJobDetailById(projectId, executionId); return R.ok(jsonObject); } catch (Exception e) { return R.failed(e.getMessage()); } } /** * 根据job执行id和步骤id查询步骤详细信息 * @param executionId job执行id * @param stepId 步骤id * @param projectId 项目id * @return R */ @Operation(summary = "根据job执行id和步骤id查询步骤详细信息", description = "根据job执行id和步骤id查询步骤详细信息") @SysLog("根据job执行id和步骤id查询步骤详细信息") @PostMapping("/jobs/executions/{executionId}/steps/{stepId}") public R getStepDetail( @PathVariable("executionId") Long executionId, @PathVariable("stepId") Long stepId, @RequestParam(value = "projectId") String projectId ) { try { JSONObject jsonObject = scdfResourcesService.getStepDetail(projectId, executionId,stepId); return R.ok(jsonObject); } catch (Exception e) { return R.failed(e.getMessage()); } }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.SysImportInfo;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportInfoDTO;import cn.chinatowercom.dataflow.backend.service.SysImportInfoService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.*;import javax.validation.Valid;/** * 导入导出结果表 * * @author hj * @date 2023-03-15 15:32:33 */@Slf4j@RestController@RequiredArgsConstructor@RequestMapping("/sysimportinfo")@Tag(name = "导入导出结果表管理")@NoAuth(value = false)//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysImportInfoController { private final SysImportInfoService sysImportInfoService; /** * 提交导入请求 * * @param sysImportInfoDTO 导入导出结果表 * @return R */ @Operation(summary = "提交导入请求", description = "提交导入请求") @SysLog("提交导入请求") @PostMapping("/submitImport") public R submitImport(@RequestBody SysImportInfoDTO sysImportInfoDTO) { if (sysImportInfoDTO.getFileId() == null) { return R.failed("导入文件不能为空"); } if (!StringUtils.hasText(sysImportInfoDTO.getTemplateId())) { return R.failed("模板id不能为空"); } return sysImportInfoService.submitImport(sysImportInfoDTO); } /** * 数据导入 * * @param sysImportInfoDTO 导入导出结果表 * @return R */ @Operation(summary = "数据导入", description = "数据导入") @SysLog("提交导入请求") @PostMapping("/importData") public R importData(@Valid @RequestBody SysImportInfoDTO sysImportInfoDTO) { return sysImportInfoService.importData(sysImportInfoDTO); } /** * 分页查询 * * @param page 分页对象 * @param sysImportInfo 导入导出结果表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page") public R getSysImportInfoPage(Page page, SysImportInfo sysImportInfo) { try { return R.ok(sysImportInfoService.getSysImportInfoPage(page, sysImportInfo)); } catch (Exception e) { log.error("查询导入结构接口错误:{}", e); return R.failed("查询失败"); } } /** * 通过id查询导入导出结果表 * * @param id id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/getImportInfo/{id}") public R getById(@PathVariable("id") Long id) { return R.ok(sysImportInfoService.getSysImportInfoById(id)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLog;import cn.chinatowercom.dataflow.backend.service.SysImportInfoLogService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.annotation.NoAuth;import org.springframework.security.access.prepost.PreAuthorize;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.security.SecurityRequirement;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.http.HttpHeaders;import org.springframework.web.bind.annotation.*;/** * 导入日志表 * * @author hj * @date 2023-03-15 15:32:33 */@RestController@RequiredArgsConstructor@RequestMapping("/sysimportinfolog" )@Tag(name = "导入日志表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysImportInfoLogController { private final SysImportInfoLogService sysImportInfoLogService; /** * 分页查询 * @param page 分页对象 * @param sysImportInfoLog 导入日志表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('demo_sysimportinfolog_get')" ) public R getSysImportInfoLogPage(Page page, SysImportInfoLog sysImportInfoLog) { sysImportInfoLog.setDelFlag("0"); return R.ok(sysImportInfoLogService.getSysImportInfoLogPage(page, sysImportInfoLog)); } /** * 通过id查询导入日志表 * @param logId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{logId}" ) //@PreAuthorize("@pms.hasPermission('demo_sysimportinfolog_get')" ) public R getById(@PathVariable("logId" ) Long logId) { return R.ok(sysImportInfoLogService.getById(logId)); } /** * 新增导入日志表 * @param sysImportInfoLog 导入日志表 * @return R */ @Operation(summary = "新增导入日志表", description = "新增导入日志表") @SysLog("新增导入日志表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('demo_sysimportinfolog_add')" ) public R save(@RequestBody SysImportInfoLog sysImportInfoLog) { return R.ok(sysImportInfoLogService.save(sysImportInfoLog)); } /** * 修改导入日志表 * @param sysImportInfoLog 导入日志表 * @return R */ @Operation(summary = "修改导入日志表", description = "修改导入日志表") @SysLog("修改导入日志表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('demo_sysimportinfolog_edit')" ) public R updateById(@RequestBody SysImportInfoLog sysImportInfoLog) { return R.ok(sysImportInfoLogService.updateById(sysImportInfoLog)); } /** * 根据import_id更新log * @param sysImportInfoLog 导入日志表 * @return R */ @NoAuth(value = false) @Operation(summary = "修改导入日志表", description = "修改导入日志表") @SysLog("修改导入日志表" ) @PostMapping("/updateByImportId") //@PreAuthorize("@pms.hasPermission('demo_sysimportinfolog_edit')" ) public R updateByImportId(@RequestBody SysImportInfoLog sysImportInfoLog) { return R.ok(sysImportInfoLogService.updateByImportId(sysImportInfoLog)); } /** * 通过id删除导入日志表 * @param logId id * @return R */ @Operation(summary = "通过id删除导入日志表", description = "通过id删除导入日志表") @SysLog("通过id删除导入日志表" ) @DeleteMapping("/{logId}" ) //@PreAuthorize("@pms.hasPermission('demo_sysimportinfolog_del')" ) public R removeById(@PathVariable Long logId) { return R.ok(sysImportInfoLogService.removeById(logId)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLogTask;import cn.chinatowercom.dataflow.backend.service.SysImportInfoLogTaskService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;import javax.validation.constraints.Min;/** * * * @author liangbing * @date 2023-04-06 16:58:23 */@RestController@RequiredArgsConstructor@RequestMapping("/sysimportinfologtask" )@Tag(name = "管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysImportInfoLogTaskController { private final SysImportInfoLogTaskService sysImportInfoLogTaskService; /** * 分页查询 * @param page 分页对象 * @param sysImportInfoLogTask * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportinfologtask_get')" ) public R getSysImportInfoLogTaskPage(Page page, SysImportInfoLogTask sysImportInfoLogTask) { return R.ok(sysImportInfoLogTaskService.page(page, Wrappers.query(sysImportInfoLogTask))); } /** * 通过id查询 * @param logTaskId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{logTaskId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportinfologtask_get')" ) public R getById(@PathVariable("logTaskId" ) Long logTaskId) { return R.ok(sysImportInfoLogTaskService.getById(logTaskId)); } /** * 新增 * @param sysImportInfoLogTask * @return R */ @Operation(summary = "新增", description = "新增") @SysLog("新增" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportinfologtask_add')" ) public R save(@RequestBody SysImportInfoLogTask sysImportInfoLogTask) { return R.ok(sysImportInfoLogTaskService.save(sysImportInfoLogTask)); } /** * 新增或修改 * @param sysImportInfoLogTask * @return R */ @NoAuth(value = false) @Operation(summary = "新增", description = "新增") @SysLog("新增" ) @PostMapping("/insertOrUpdate") public R saveOrUpdate(@RequestBody SysImportInfoLogTask sysImportInfoLogTask) { return R.ok(sysImportInfoLogTaskService.insertOrUpdate(sysImportInfoLogTask)); } /** * 修改 * @param sysImportInfoLogTask * @return R */ @Operation(summary = "修改", description = "修改") @SysLog("修改" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportinfologtask_edit')" ) public R updateById(@RequestBody SysImportInfoLogTask sysImportInfoLogTask) { return R.ok(sysImportInfoLogTaskService.updateById(sysImportInfoLogTask)); } /** * 通过id删除 * @param logTaskId id * @return R */ @Operation(summary = "通过id删除", description = "通过id删除") @SysLog("通过id删除" ) @DeleteMapping("/{logTaskId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportinfologtask_del')" ) public R removeById(@PathVariable Long logTaskId) { return R.ok(sysImportInfoLogTaskService.removeById(logTaskId)); } /** * 根据import_id查询log_task表 * @param importId id * @return R */ @NoAuth(value = false) @Operation(summary = "根据import_id查询导入导出文件拆分表", description = "根据import_id查询导入导出文件拆分表") @SysLog("根据import_id查询导入导出文件拆分表" ) @PostMapping("/getByImportId" ) public R getByImportId(@Min(1)Long importId) { if(importId==null) return R.failed("参数不能为空"); return R.ok(sysImportInfoLogTaskService.getByImportId(importId)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoSplit;import cn.chinatowercom.dataflow.backend.service.SysImportInfoSplitService;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;/** * 导入导出文件拆分表 * * @author catfishing * @date 2023-04-07 12:55:40 */@RestController@RequiredArgsConstructor@RequestMapping("/sysimportinfosplit" )@Tag(name = "导入导出文件拆分表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysImportInfoSplitController { private final SysImportInfoSplitService sysImportInfoSplitService; /** * 分页查询 * @param page 分页对象 * @param sysImportInfoSplit 导入导出文件拆分表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportinfosplit_get')" ) public R getSysImportInfoSplitPage(Page page, SysImportInfoSplit sysImportInfoSplit) { return R.ok(sysImportInfoSplitService.page(page, Wrappers.query(sysImportInfoSplit))); } /** * 通过id查询导入导出文件拆分表 * @param splitId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{splitId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportinfosplit_get')" ) public R getById(@PathVariable("splitId" ) Long splitId) { return R.ok(sysImportInfoSplitService.getById(splitId)); } /** * 新增导入导出文件拆分表 * @param sysImportInfoSplit 导入导出文件拆分表 * @return R */ @Operation(summary = "新增导入导出文件拆分表", description = "新增导入导出文件拆分表") @SysLog("新增导入导出文件拆分表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportinfosplit_add')" ) public R save(@RequestBody SysImportInfoSplit sysImportInfoSplit) { return R.ok(sysImportInfoSplitService.save(sysImportInfoSplit)); } /** * 修改导入导出文件拆分表 * @param sysImportInfoSplit 导入导出文件拆分表 * @return R */ @NoAuth(value = false) @Operation(summary = "修改导入导出文件拆分表", description = "修改导入导出文件拆分表") @SysLog("修改导入导出文件拆分表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportinfosplit_edit')" ) public R updateById(@RequestBody SysImportInfoSplit sysImportInfoSplit) { return R.ok(sysImportInfoSplitService.updateById(sysImportInfoSplit)); } /** * 通过id删除导入导出文件拆分表 * @param splitId id * @return R */ @Operation(summary = "通过id删除导入导出文件拆分表", description = "通过id删除导入导出文件拆分表") @SysLog("通过id删除导入导出文件拆分表" ) @DeleteMapping("/{splitId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportinfosplit_del')" ) public R removeById(@PathVariable Long splitId) { return R.ok(sysImportInfoSplitService.removeById(splitId)); } /** * 根据import_id查询导入导出文件拆分表 * @param importId id * @return R */ @NoAuth(value = false) @Operation(summary = "根据import_id查询导入导出文件拆分表", description = "根据import_id查询导入导出文件拆分表") @SysLog("根据import_id查询导入导出文件拆分表" ) @PostMapping("/getByImportId" ) public R getByImportId(Long importId) { if(importId==null) return R.failed("参数不能为空"); return R.ok(sysImportInfoSplitService.getByImportId(importId)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import cn.hutool.core.text.CharSequenceUtil;import cn.hutool.core.util.StrUtil;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportRuleType;import cn.chinatowercom.dataflow.backend.service.SysImportRuleTypeService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;/** * 指标规则类型表 * * @author catfishing * @date 2023-03-13 15:20:16 */@RestController@RequiredArgsConstructor@RequestMapping("/sysimportruletype" )@Tag(name = "指标规则类型表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysImportRuleTypeController { private final SysImportRuleTypeService sysImportRuleTypeService; /** * 分页查询 * @param page 分页对象 * @param sysImportRuleType 指标规则类型表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportruletype_get')" ) public R getSysImportRuleTypePage(Page page, SysImportRuleType sysImportRuleType) { sysImportRuleType.setDelFlag("0"); QueryWrapper<SysImportRuleType> queryWrapper = Wrappers.query(sysImportRuleType); // add by liangbing on 2023-04-18 // 处理ruleType为多个值的情况 if(CharSequenceUtil.isNotEmpty(sysImportRuleType.getRuleType()) && sysImportRuleType.getRuleType().indexOf(',') != -1) { String ruleType = sysImportRuleType.getRuleType(); sysImportRuleType.setRuleType(null); queryWrapper = Wrappers.query(sysImportRuleType); for(String ruleValue : ruleType.split(",")) { queryWrapper.or(wq -> wq.eq("rule_type", ruleValue)); } } // 按创建时间升序排序 queryWrapper.orderByAsc("create_time"); return R.ok(sysImportRuleTypeService.page(page, queryWrapper)); } /** * 通过id查询指标规则类型表 * @param ruleTypeId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{ruleTypeId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportruletype_get')" ) public R getById(@PathVariable("ruleTypeId" ) Long ruleTypeId) { return R.ok(sysImportRuleTypeService.getById(ruleTypeId)); } /** * 新增指标规则类型表 * @param sysImportRuleType 指标规则类型表 * @return R */ @Operation(summary = "新增指标规则类型表", description = "新增指标规则类型表") @SysLog("新增指标规则类型表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportruletype_add')" ) public R save(@RequestBody SysImportRuleType sysImportRuleType) { return R.ok(sysImportRuleTypeService.save(sysImportRuleType)); } /** * 修改指标规则类型表 * @param sysImportRuleType 指标规则类型表 * @return R */ @Operation(summary = "修改指标规则类型表", description = "修改指标规则类型表") @SysLog("修改指标规则类型表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportruletype_edit')" ) public R updateById(@RequestBody SysImportRuleType sysImportRuleType) { return R.ok(sysImportRuleTypeService.updateById(sysImportRuleType)); } /** * 通过id删除指标规则类型表 * @param ruleTypeId id * @return R */ @Operation(summary = "通过id删除指标规则类型表", description = "通过id删除指标规则类型表") @SysLog("通过id删除指标规则类型表" ) @DeleteMapping("/{ruleTypeId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportruletype_del')" ) public R removeById(@PathVariable Long ruleTypeId) { return R.ok(sysImportRuleTypeService.removeById(ruleTypeId)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportServer;import cn.chinatowercom.dataflow.backend.service.SysImportServerService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import org.springframework.security.access.prepost.PreAuthorize;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.security.SecurityRequirement;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.http.HttpHeaders;import org.springframework.web.bind.annotation.*;/** * * * @author catfishing * @date 2023-03-27 16:33:38 */@RestController@RequiredArgsConstructor@RequestMapping("/sysimportserver" )@Tag(name = "管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysImportServerController { private final SysImportServerService sysImportServerService; /** * 分页查询 * @param page 分页对象 * @param sysImportServer * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportserver_get')" ) public R getSysImportServerPage(Page page, SysImportServer sysImportServer) { return R.ok(sysImportServerService.page(page, Wrappers.query(sysImportServer))); } /** * 通过id查询 * @param abilityId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{abilityId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportserver_get')" ) public R getById(@PathVariable("abilityId" ) Long abilityId) { return R.ok(sysImportServerService.getById(abilityId)); } /** * 新增 * @param sysImportServer * @return R */ @Operation(summary = "新增", description = "新增") @SysLog("新增" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportserver_add')" ) public R save(@RequestBody SysImportServer sysImportServer) { return R.ok(sysImportServerService.save(sysImportServer)); } /** * 修改 * @param sysImportServer * @return R */ @Operation(summary = "修改", description = "修改") @SysLog("修改" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysimportserver_edit')" ) public R updateById(@RequestBody SysImportServer sysImportServer) { return R.ok(sysImportServerService.updateById(sysImportServer)); } /** * 通过id删除 * @param abilityId id * @return R */ @Operation(summary = "通过id删除", description = "通过id删除") @SysLog("通过id删除" ) @DeleteMapping("/{abilityId}" ) //@PreAuthorize("@pms.hasPermission('backend_sysimportserver_del')" ) public R removeById(@PathVariable Long abilityId) { return R.ok(sysImportServerService.removeById(abilityId)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.dto.SysProjectTemplate;import cn.chinatowercom.dataflow.backend.service.SysProjectTemplateService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;/** * 项目和模板关联表 * * @author catfishing * @date 2023-02-08 10:42:41 */@RestController@RequiredArgsConstructor@RequestMapping("/sysprojecttemplate" )@Tag(name = "项目和模板关联表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysProjectTemplateController { private final SysProjectTemplateService sysProjectTemplateService; /** * 分页查询 * @param page 分页对象 * @param sysProjectTemplate 项目和模板关联表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_sysprojecttemplate_get')" ) public R getSysProjectTemplatePage(Page page, SysProjectTemplate sysProjectTemplate) { return R.ok(sysProjectTemplateService.page(page, Wrappers.query(sysProjectTemplate))); } /** * 通过id查询项目和模板关联表 * @param id id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{id}" ) //@PreAuthorize("@pms.hasPermission('backend_sysprojecttemplate_get')" ) public R getById(@PathVariable("id" ) Long id) { return R.ok(sysProjectTemplateService.getById(id)); } /** * 新增项目和模板关联表 * @param sysProjectTemplate 项目和模板关联表 * @return R */ @Operation(summary = "新增项目和模板关联表", description = "新增项目和模板关联表") @SysLog("新增项目和模板关联表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_sysprojecttemplate_add')" ) public R save(@RequestBody SysProjectTemplate sysProjectTemplate) { return R.ok(sysProjectTemplateService.save(sysProjectTemplate)); } /** * 修改项目和模板关联表 * @param sysProjectTemplate 项目和模板关联表 * @return R */ @Operation(summary = "修改项目和模板关联表", description = "修改项目和模板关联表") @SysLog("修改项目和模板关联表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysprojecttemplate_edit')" ) public R updateById(@RequestBody SysProjectTemplate sysProjectTemplate) { return R.ok(sysProjectTemplateService.updateById(sysProjectTemplate)); } /** * 通过id删除项目和模板关联表 * @param id id * @return R */ @Operation(summary = "通过id删除项目和模板关联表", description = "通过id删除项目和模板关联表") @SysLog("通过id删除项目和模板关联表" ) @DeleteMapping("/{id}" ) //@PreAuthorize("@pms.hasPermission('backend_sysprojecttemplate_del')" ) public R removeById(@PathVariable Long id) { return R.ok(sysProjectTemplateService.removeById(id)); }}
package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.dto.SysProjectUserRelation;import cn.chinatowercom.dataflow.backend.service.SysProjectUserRelationService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import io.swagger.annotations.Api;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.web.bind.annotation.*;/** * 项目人员关联表 * * @author catfishing * @date 2023-02-03 09:43:24 */@RestController@RequiredArgsConstructor@RequestMapping("/projectUserRelation" )@Tag(name = "项目人员关联表管理")@Api(value = "sysProjectUserRelation", tags = "项目人员关联表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysProjectUserRelationController { private final SysProjectUserRelationService sysProjectUserRelationService; /** * 分页查询 * @param page 分页对象 * @param sysProjectUserRelation 项目人员关联表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('demo_sysprojectuserrelation_get')" ) public R getSysProjectUserRelationPage(Page page, SysProjectUserRelation sysProjectUserRelation) { return R.ok(sysProjectUserRelationService.page(page, Wrappers.query(sysProjectUserRelation))); } /** * 通过id查询项目人员关联表 * @param id id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{id}" ) //@PreAuthorize("@pms.hasPermission('demo_sysprojectuserrelation_get')" ) public R getById(@PathVariable("id" ) Long id) { return R.ok(sysProjectUserRelationService.getById(id)); } /** * 新增项目人员关联表 * @param sysProjectUserRelation 项目人员关联表 * @return R */ @Operation(summary = "新增项目人员关联表", description = "新增项目人员关联表") @SysLog("新增项目人员关联表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('demo_sysprojectuserrelation_add')" ) public R save(@RequestBody SysProjectUserRelation sysProjectUserRelation) { return R.ok(sysProjectUserRelationService.save(sysProjectUserRelation)); } /** * 修改项目人员关联表 * @param sysProjectUserRelation 项目人员关联表 * @return R */ @Operation(summary = "修改项目人员关联表", description = "修改项目人员关联表") @SysLog("修改项目人员关联表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('demo_sysprojectuserrelation_edit')" ) public R updateById(@RequestBody SysProjectUserRelation sysProjectUserRelation) { return R.ok(sysProjectUserRelationService.updateById(sysProjectUserRelation)); } /** * 通过id删除项目人员关联表 * @param id id * @return R */ @Operation(summary = "通过id删除项目人员关联表", description = "通过id删除项目人员关联表") @SysLog("通过id删除项目人员关联表" ) @DeleteMapping("/{id}" ) //@PreAuthorize("@pms.hasPermission('demo_sysprojectuserrelation_del')" ) public R removeById(@PathVariable Long id) { return R.ok(sysProjectUserRelationService.removeById(id)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.controller;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import cn.chinatowercom.dataflow.backend.entity.dto.SysTemplateExportCriteria;import cn.chinatowercom.dataflow.backend.service.SysTemplateExportCriteriaService;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.log.annotation.SysLog;import org.springframework.security.access.prepost.PreAuthorize;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.security.SecurityRequirement;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import org.springframework.http.HttpHeaders;import org.springframework.web.bind.annotation.*;/** * 导出数据条件表 * * @author catfishing * @date 2023-03-13 15:20:16 */@RestController@RequiredArgsConstructor@RequestMapping("/systemplateexportcriteria" )@Tag(name = "导出数据条件表管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class SysTemplateExportCriteriaController { private final SysTemplateExportCriteriaService sysTemplateExportCriteriaService; /** * 分页查询 * @param page 分页对象 * @param sysTemplateExportCriteria 导出数据条件表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page" ) //@PreAuthorize("@pms.hasPermission('backend_systemplateexportcriteria_get')" ) public R getSysTemplateExportCriteriaPage(Page page, SysTemplateExportCriteria sysTemplateExportCriteria) { return R.ok(sysTemplateExportCriteriaService.page(page, Wrappers.query(sysTemplateExportCriteria))); } /** * 通过id查询导出数据条件表 * @param criteriaId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{criteriaId}" ) //@PreAuthorize("@pms.hasPermission('backend_systemplateexportcriteria_get')" ) public R getById(@PathVariable("criteriaId" ) Long criteriaId) { return R.ok(sysTemplateExportCriteriaService.getById(criteriaId)); } /** * 新增导出数据条件表 * @param sysTemplateExportCriteria 导出数据条件表 * @return R */ @Operation(summary = "新增导出数据条件表", description = "新增导出数据条件表") @SysLog("新增导出数据条件表" ) @PostMapping //@PreAuthorize("@pms.hasPermission('backend_systemplateexportcriteria_add')" ) public R save(@RequestBody SysTemplateExportCriteria sysTemplateExportCriteria) { return R.ok(sysTemplateExportCriteriaService.save(sysTemplateExportCriteria)); } /** * 修改导出数据条件表 * @param sysTemplateExportCriteria 导出数据条件表 * @return R */ @Operation(summary = "修改导出数据条件表", description = "修改导出数据条件表") @SysLog("修改导出数据条件表" ) @PutMapping //@PreAuthorize("@pms.hasPermission('backend_systemplateexportcriteria_edit')" ) public R updateById(@RequestBody SysTemplateExportCriteria sysTemplateExportCriteria) { return R.ok(sysTemplateExportCriteriaService.updateById(sysTemplateExportCriteria)); } /** * 通过id删除导出数据条件表 * @param criteriaId id * @return R */ @Operation(summary = "通过id删除导出数据条件表", description = "通过id删除导出数据条件表") @SysLog("通过id删除导出数据条件表" ) @DeleteMapping("/{criteriaId}" ) //@PreAuthorize("@pms.hasPermission('backend_systemplateexportcriteria_del')" ) public R removeById(@PathVariable Long criteriaId) { return R.ok(sysTemplateExportCriteriaService.removeById(criteriaId)); }}
package cn.chinatowercom.dataflow.backend.controller;import cn.chinatowercom.dataflow.backend.entity.dto.FileDto;import cn.chinatowercom.dataflow.backend.entity.dto.ImportDetailDto;import cn.chinatowercom.dataflow.backend.entity.dto.ImportTemplateDTO;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportTemplate;import cn.chinatowercom.dataflow.backend.entity.vo.ImportVo;import cn.chinatowercom.dataflow.backend.service.SysImportTemplateService;import com.alibaba.fastjson.JSON;import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.dataflow.core.base.json.JsonReportEntity;import com.strongdata.dataflow.core.base.util.Base64Util;import com.strongdata.dataflow.core.base.util.JRUtilNew;import com.strongdata.dataflow.core.base.util.JsonToXMLUtil;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.base.xml.ReportEntity;import com.strongdata.dataflow.core.log.annotation.SysLog;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.v3.oas.annotations.Operation;import io.swagger.v3.oas.annotations.tags.Tag;import lombok.RequiredArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.springframework.http.HttpStatus;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.validation.Valid;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.net.URLEncoder;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;/** * @author catfishing * @date 2023/2/1 模板管理 */@Slf4j@RestController@RequiredArgsConstructor@RequestMapping("/templateManage")@Tag(name = "模板管理")@Api(value = "templateManage", tags = "模板管理")//@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)public class TemplateManageController { private final static String DEFINE_SET_COOKIE = "Set-Cookie"; private final static String DEFINE_SET_COOKIE_VALUE = "fileDownload=false; path=/"; private final static String DEFINE_CACHE_CONTROL = "Cache-Control"; private final static String DEFINE_CACHE_CONTROL_VALUE = "no-cache, no-store, must-revalidate"; private final SysImportTemplateService sysImportTemplateService; /** * 保存报表 * * @param uuid * @param report * @return */ @Operation(summary = "新增导入模板定义表", description = "新增导入模板定义表") @SysLog("新增导入模板定义表") @PostMapping public R saveReport(@RequestParam(value = "uuid", required = false) String uuid, @RequestParam("report") String report) { try { report = Base64Util.decode(report, "Unicode"); } catch (Exception e) { log.error("模板保存失败:{}", e); return R.failed("模板错误"); } if(!StringUtils.hasText(report)) return R.failed("模板错误"); List<JsonReportEntity> json = JSON.parseArray(report,JsonReportEntity.class); List<ReportEntity> reportEntitys = new ArrayList<>(); json.stream().forEach(o->reportEntitys.add(JsonToXMLUtil.JsonToXml(o))); return sysImportTemplateService.saveReport(uuid, reportEntitys); } /** * 分页查询 * * @param page 分页对象 * @param importTemplateDTO 导入模板定义表 * @return */ @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page") //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_get')" ) public R getSysImportTemplatePage(Page page, ImportTemplateDTO importTemplateDTO) { importTemplateDTO.setDelFlag("0"); return R.ok(sysImportTemplateService.findTemplateByProjectId(page, importTemplateDTO)); } @Operation(summary = "查询所有模板", description = "查询所有模板") @GetMapping("/all") //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_get')" ) public R getSysImportTemplateAll(@Valid ImportTemplateDTO importTemplateDTO) { importTemplateDTO.setDelFlag("0"); return R.ok(sysImportTemplateService.getSysImportTemplateAll(importTemplateDTO)); } /** * 通过id查询导入模板定义表 * * @param templateId id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @PostMapping("/selectReport") //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_get')" ) public R<Map<String, List<JsonReportEntity>>> getById(@RequestParam("templateId") String templateId, @RequestParam(value = "sheetId", required = false) String sheetId) { SysImportTemplate template = sysImportTemplateService.getById(templateId); if (template == null) return R.ok(); List<ReportEntity> reportEntityList = JSON.parseArray(template.getOriginalTemplate(), ReportEntity.class); List<JsonReportEntity> jsonReportEntitys = new ArrayList<>(); Map reportEntitysMap = new HashMap(); if(!StringUtils.hasText(sheetId)){ if(CollectionUtils.isEmpty(reportEntityList)) R.failed("模板不存在"); reportEntityList.forEach(o-> { JsonReportEntity jsonReportEntity = JsonToXMLUtil.XmlToJson(o); jsonReportEntity.setFileName(template.getTemplateName()); jsonReportEntitys.add(jsonReportEntity); }); }else{ ReportEntity reportEntity = reportEntityList.stream().filter(o->sheetId.equals(o.getSheetId())).findFirst().orElse(null); if(reportEntity == null) R.failed("模板不存在"); JsonReportEntity jsonReportEntity = JsonToXMLUtil.XmlToJson(reportEntity); jsonReportEntity.setFileName(template.getTemplateName()); jsonReportEntitys.add(jsonReportEntity); } reportEntitysMap.put("templateInfos", jsonReportEntitys); return R.ok(reportEntitysMap); } /** * 修改导入模板定义表 * * @param sysImportTemplate 导入模板定义表 * @return R */ @Operation(summary = "修改导入模板定义表", description = "修改导入模板定义表") @SysLog("修改导入模板定义表") @PutMapping //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_edit')" ) public R updateById(@RequestBody SysImportTemplate sysImportTemplate) { // modify by liangbing // 发布时由于列表页面没有刷新获取最新数据,导致模板JSON更新值不是最新的,这里获取最新的值操作。 SysImportTemplate sysImportTemplate1 = sysImportTemplateService.getById(sysImportTemplate.getTemplateId()); sysImportTemplate.setOriginalTemplate(sysImportTemplate1.getOriginalTemplate()); return R.ok(sysImportTemplateService.updateById(sysImportTemplate)); } /** * 通过id删除导入模板定义表 * * @param templateId id * @return R */ @Operation(summary = "通过id删除导入模板定义表", description = "通过id删除导入模板定义表") @SysLog("通过id删除导入模板定义表") @DeleteMapping("/{templateId}") //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_del')" ) public R removeById(@PathVariable String templateId) { return R.ok(sysImportTemplateService.removeById(templateId)); } /** * excel、pdf等类型模板下载 * * @param templateIds 模板id集合 * @return R */ @Operation(summary = "excel、pdf等类型模板下载", description = "excel、pdf等类型模板下载") @SysLog("excel、pdf等类型模板下载") @GetMapping("/downloadExcel") //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_downloadExcel')" ) public void downloadTemplateExcel(@RequestParam("templateIds") String templateIds, HttpServletRequest request, HttpServletResponse response) { SysImportTemplate template = sysImportTemplateService.getById(templateIds); if (template == null) return; ReportEntity var6 = JSON.parseObject(template.getOriginalTemplate(), ReportEntity.class); Map var11 = null; try { var11 = (new JRUtilNew()).rpMap(request, var6, null, null); (new JRUtilNew()).exportFile(var6, null, null, null, request, response, false, var11, "excel"); } catch (Exception e) { log.error("导出模板异常:{}",e.getMessage()); response.setHeader(DEFINE_SET_COOKIE, DEFINE_SET_COOKIE_VALUE); response.setHeader(DEFINE_CACHE_CONTROL, DEFINE_CACHE_CONTROL_VALUE); } } @Operation(summary = "模板下载", description = "模板下载") @GetMapping("/exportTemplate") public void exportTemplate(@RequestParam("templateIds") String templateIds, HttpServletRequest request, HttpServletResponse response) { if(!StringUtils.hasText(templateIds)){ response.setStatus(HttpStatus.NOT_FOUND.value()); return; } sysImportTemplateService.exportTemplate(templateIds, request, response); } /** * xml模板导出 * * @param templateIds 模板id集合 * @return R */ @Operation(summary = "xml模板导出", description = "xml模板导出") @SysLog("xml模板导出") @PostMapping("/downloadXml") //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_downloadXml')" ) public void downloadTemplateXml(@RequestParam("templateIds") String templateIds, HttpServletResponse response) { if (!StringUtils.hasText(templateIds)) { response.setHeader(DEFINE_SET_COOKIE, DEFINE_SET_COOKIE_VALUE); response.setHeader(DEFINE_CACHE_CONTROL, DEFINE_CACHE_CONTROL_VALUE); } List<String> uuids = JSON.parseArray(templateIds, String.class); List<SysImportTemplate> templates = sysImportTemplateService.listByIds(uuids); if (CollectionUtils.isEmpty(templates)) { response.setHeader(DEFINE_SET_COOKIE, DEFINE_SET_COOKIE_VALUE); response.setHeader(DEFINE_CACHE_CONTROL, DEFINE_CACHE_CONTROL_VALUE); } String zipFile = "templates.zip"; try { response.reset(); zipFile = URLEncoder.encode(zipFile, "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + zipFile); response.setContentType("multipart/form-data"); response.setHeader(DEFINE_SET_COOKIE, "fileDownload=true; path=/"); response.setHeader(DEFINE_CACHE_CONTROL, DEFINE_CACHE_CONTROL_VALUE); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); BufferedOutputStream bos = new BufferedOutputStream(zos); for (int i = 0; i < templates.size(); i++) { String fname = templates.get(i).getTemplateName() + "_" + templates.get(i).getTemplateId() + ".xml"; //byte[] f = DesignXmlUtil.reportToXML(JSON.parseObject(templates.get(i).getOriginalTemplate(), ReportEntity.class)).getBytes(); BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(Base64Util.encode(templates.get(i).getOriginalTemplate(), "Unicode").getBytes())); zos.putNextEntry(new ZipEntry(fname)); int len = 0; byte[] buf = new byte[10 * 1024]; while ((len = bis.read(buf, 0, buf.length)) != -1) { bos.write(buf, 0, len); } bis.close(); bos.flush(); } bos.close(); } catch (Exception ex) { response.setHeader(DEFINE_SET_COOKIE, DEFINE_SET_COOKIE_VALUE); response.setHeader(DEFINE_CACHE_CONTROL, DEFINE_CACHE_CONTROL_VALUE); log.error(ex.getMessage()); } } /** * xml模板导入 * * @param projectId 项目组标识 * @return R */// @Operation(summary = "xml模板导入", description = "xml模板导入")// @SysLog("xml模板导入")// @PostMapping("/uploadXml")// //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_downloadExcel')" )// public R uploadTemplateXml(@NotNull @RequestParam("projectId") String projectId, MultipartFile multipartFile){// R result = R.failed();// if (multipartFile == null || multipartFile.getOriginalFilename() == null) {// return R.failed("file不能为空");// }//// String fileName = multipartFile.getOriginalFilename();// if(StrUtil.isEmpty(fileName) || fileName == null){// return R.failed("文件名称为空");// }//// File file = new File(fileName);// try {// multipartFile.transferTo(file);// } catch (IOException e) {// log.error("读取文件失败={}",e.getMessage());// return result.setMsg("文件模板内容错误");// }//// Map<String, String> files = new HashMap();// if (fileName.toLowerCase().endsWith(".zip")) {// files = parseFiles(multipartFile);// }else if(fileName.toLowerCase().endsWith(".xml")){// files.put(file.getName(), DesignXmlUtil.readToString(file));// }else{// return result.setMsg("文件模板内容错误");// }//// if(files.size()==-1){// return result.setMsg("文件模板内容错误");// }//// Iterator it = files.keySet().iterator();// String key = null;// String xml = null;// String fileStr = null;// List<ReportEntity> reportEntitys = null;// while (it.hasNext()){// key = (String)it.next();// xml = files.get(key);// //ReportEntity model = DesignXmlUtil.openXMLNew(xml);// try {// fileStr = Base64Util.decode(xml, "Unicode");// } catch (Exception e) {// log.error("模板解析失败={}",e.getMessage());// return R.failed("模板解析失败!");// }// if(fileStr != null) {// reportEntitys = JSON.parseArray(fileStr, ReportEntity.class);// sysImportTemplateService.saveReport(null, reportEntitys);// reportEntitys.clear();// } else {// return R.failed("模板解析失败!");// }// }// return result.setMsg("保存成功");// }//// private Map<String, String> parseFiles(MultipartFile multipartFile){// Map<String, String> files = new HashMap<>();// String fileName = multipartFile.getOriginalFilename();// File zipFile = new File(fileName);// BufferedReader br = null;// try (// ZipFile zf = new ZipFile(zipFile);// FileInputStream fis = new FileInputStream(zipFile);// ZipInputStream zis = new ZipInputStream(fis);// ) {// multipartFile.transferTo(zipFile);// ZipEntry ze;// StringBuilder builder = new StringBuilder();// while ((ze = zis.getNextEntry()) != null) {// if (ze.toString().endsWith("xml")) {// br = new BufferedReader(// new InputStreamReader(zf.getInputStream(ze)));// String line;// while ((line = br.readLine()) != null) {// builder.append(line);// }// files.put(ze.getName(),builder.toString());// }// }// }catch (Exception e){// log.error("模板文件解析失败={}", e.getMessage());// return null;// }finally{// try{// if(br!=null){// br.close();// }// }catch (Exception ex){// log.error("模板文件解析失败={}", ex.getMessage());// }// }// return files;// } /** * excel模板导入 * @return R */ @Operation(summary = "xml模板导入", description = "xml模板导入") @SysLog("xml模板导入" ) @PostMapping("/uploadExcel" ) //@PreAuthorize("@pms.hasPermission('backend_sysimporttemplate_downloadExcel')" ) public R uploadTemplateExcel(HttpServletRequest request, HttpServletResponse response) { return R.ok(); } /** * 根据导入id获取模板 文件 校验规则 等信息 * @param importVo 文件相关信息 * @return R */ @NoAuth(value = false) @Operation(summary = "模板相关信息读取", description = "模板相关信息读取") @SysLog("模板相关信息读取" ) @PostMapping("/getTemplateDetail" ) public ImportDetailDto getTemplateDetail(@RequestBody ImportVo importVo) { return sysImportTemplateService.getTemplateDetail(importVo); } /** * 根据导入id获取文件列表 * @param importVo 文件相关信息 * @return R */ @Operation(summary = "模板相关信息读取", description = "模板相关信息读取") @SysLog("模板相关信息读取" ) @PostMapping("/getFileByImportId" ) public R<List<FileDto>> getFileByImportId(@Valid @RequestBody ImportVo importVo) { return R.ok(sysImportTemplateService.getFileByImportId(importVo)); } /** * 测试模板配置回调接口 */ @Operation(summary = "测试模板配置回调接口", description = "测试模板配置回调接口") @SysLog("测试模板配置回调接口") @RequestMapping("/testTemplateCallback") public R testTemplateCallback(@RequestParam("importId") String importId) { log.debug("测试模板配置回调接口,{}", importId); return R.ok(); }}
package cn.chinatowercom.dataflow.backend.service.impl;import cn.chinatowercom.dataflow.backend.annotation.CustomizeRedisCache;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLogTask;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportServer;import cn.chinatowercom.dataflow.backend.entity.vo.SysImportInfoLogTaskVO;import cn.chinatowercom.dataflow.backend.service.ScdfResourcesService;import cn.chinatowercom.dataflow.backend.service.SysImportInfoLogTaskService;import cn.chinatowercom.dataflow.backend.service.SysImportServerService;import cn.hutool.core.bean.BeanUtil;import cn.hutool.core.text.CharSequenceUtil;import cn.hutool.http.HttpRequest;import cn.hutool.http.HttpUtil;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.strongdata.dataflow.core.base.exception.CheckedException;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import org.springframework.util.CollectionUtils;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;/** * 资源管理 * * @author liangbing * @date 2022/04/04 */@Service@Slf4jpublic class ScdfResourcesServiceImpl implements ScdfResourcesService { private static final String HTTP = "http://"; //private static final String HTTPS = "https://"; private static final String LEFT_SLASH = "/"; private static final String COLON = ":"; private static final String DEL_FLAG_0 = "0"; private static final String DEFINE_NOT_FOUND_RESOURCE_ADDRESS = "未找到资源服务地址"; private static final String DEFINE_JOBS_EXECUTIONS = "jobs/executions/";// private enum del_flag {// DEL_FLAG_0("0"),// DEL_FLAG_1("1");// private String value;// del_flag(String value) {// this.value = value;// }// public String getValue() {// return value;// }// } private static final int TIMEOUT = 3000; @Autowired private RedisTemplate redisTemplate; @Autowired private SysImportServerService sysImportServerService; @Autowired private SysImportInfoLogTaskService sysImportInfoLogTaskService; @CustomizeRedisCache(key = "#projectId", expireTimes = 60) private String getScdfHttpDomainByProjectId(String projectId) { // 查询项目服务列表 SysImportServer sysImportServer = new SysImportServer(); sysImportServer.setDelFlag(DEL_FLAG_0); sysImportServer.setProjectId(projectId); List<SysImportServer> sysImportServerList = sysImportServerService.list(Wrappers.query(sysImportServer)); // 默认去首个元素并拼接服务域名地址 StringBuilder sb = new StringBuilder(); if (!CollectionUtils.isEmpty(sysImportServerList)) { sysImportServer = sysImportServerList.get(0); sb.append(HTTP) .append(sysImportServer.getHostIp()) .append(COLON) .append(sysImportServer.getHostPort()) .append(LEFT_SLASH); } return sb.toString(); } @Override public JSONObject getTasksExecutions(String projectId, int page, int size){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } Map paramMap = new HashMap(); paramMap.put("page", page); paramMap.put("size", size); String response = HttpUtil.get(domain + "tasks/executions/", paramMap, TIMEOUT); return JSON.parseObject(response); } /** * 根据导入ID查询任务执行列表 * * @param projectId * @param importId * @param page * @param size * * @return java.util.List */ @Override public IPage<SysImportInfoLogTaskVO> getTasksExecutionsByImportId(String projectId, Long importId, int page, int size){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException("未找到项目资源服务地址"); } if(importId == null || importId == 0l) { throw new CheckedException("导入ID不能为空"); } // 分页查询任务执行日志列表 SysImportInfoLogTask sysImportInfoLogTask = new SysImportInfoLogTask(); sysImportInfoLogTask.setDelFlag(DEL_FLAG_0); sysImportInfoLogTask.setImportId(importId); Page pageInfo = new Page(page, size); IPage<SysImportInfoLogTask> sysImportInfoLogTaskIPage = sysImportInfoLogTaskService.page(pageInfo, Wrappers.query(sysImportInfoLogTask)); List<SysImportInfoLogTaskVO> sysImportInfoLogTaskVOList = new ArrayList<>(); for (SysImportInfoLogTask logTask : sysImportInfoLogTaskIPage.getRecords()) { // 获取任务执行详情 JSONObject taskExecution = getTasksExecutionById(projectId, logTask.getTaskId()); if (taskExecution != null) { SysImportInfoLogTaskVO logTaskVO = new SysImportInfoLogTaskVO(); BeanUtil.copyProperties(logTask, logTaskVO); logTaskVO.setTaskInfo(taskExecution); sysImportInfoLogTaskVOList.add(logTaskVO); } } IPage<SysImportInfoLogTaskVO> sysImportInfoLogTaskVOIPage = new Page<>(); sysImportInfoLogTaskVOIPage.setRecords(sysImportInfoLogTaskVOList); sysImportInfoLogTaskVOIPage.setPages(page); sysImportInfoLogTaskVOIPage.setSize(size); sysImportInfoLogTaskVOIPage.setTotal(sysImportInfoLogTaskIPage.getTotal()); return sysImportInfoLogTaskVOIPage; } /** * 获取任务执行详情 * * @param projectId * @param executionId * @return JSONObject * @throws Exception */ @CustomizeRedisCache(key = "#projectId + '^' + #executionId", expireTimes = 60) @Override public JSONObject getTasksExecutionById(String projectId, Long executionId){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } if(executionId == null || executionId == 0l) { throw new CheckedException("任务执行ID不能为空"); } String response = HttpUtil.get(domain + "tasks/executions/" + executionId, TIMEOUT); return JSON.parseObject(response); } /** * 查询job日志信息 * * @param projectId * @param externalTaskExecutionId * @return * @throws Exception */ @Override public String getTasksLogsById(String projectId, String externalTaskExecutionId){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } if(CharSequenceUtil.isEmpty(externalTaskExecutionId)) { throw new CheckedException("任务ID不能为空"); } String response = HttpRequest.get(domain + "tasks/logs/" + externalTaskExecutionId) .header("Content-Type", "text/html; charset=utf-8") .header("Accept", "text/html; charset=utf-8") .execute() .body(); log.info(response); return response; } /** * 根据任务ID查询job列表信息 * * @param projectId * @param taskExecutionId * @param page * @param size * @return * @throws Exception */ @CustomizeRedisCache(key = "#projectId + '^' + #taskExecutionId", expireTimes = 60) @Override public JSONObject getJobsThinExecutionsByTaskId(String projectId, Long taskExecutionId, int page, int size){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } Map paramMap = new HashMap(); paramMap.put("taskExecutionId", taskExecutionId); paramMap.put("page", page); paramMap.put("size", size); String response = HttpUtil.get(domain + "jobs/thinexecutions", paramMap, TIMEOUT); return JSON.parseObject(response);// JSONObject _embedded = (JSONObject) jsonObject.get("_embedded");// JSONArray jobExecutionThinResourceList = (JSONArray) _embedded.get("jobExecutionThinResourceList"); } /** * 根据job执行id查询job详细信息 * @param executionId job执行id * @param projectId 项目id * @return * @throws Exception */ @Override @SneakyThrows public JSONObject getJobDetailById(String projectId, Long executionId){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } if(executionId == null || executionId == 0L) { throw new CheckedException("job执行ID不能为空"); } String response = HttpUtil.get(domain + DEFINE_JOBS_EXECUTIONS + executionId, TIMEOUT); return JSON.parseObject(response); } /** * 根据job执行id和步骤id查询步骤详细信息 * @param executionId job执行id * @param stepId 步骤id * @param projectId 项目id * @return * @throws Exception */ @Override @SneakyThrows public JSONObject getStepDetail(String projectId, Long executionId, Long stepId){ JSONObject jo = new JSONObject(); String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } if(executionId == null || executionId == 0L) { throw new CheckedException("job执行ID不能为空"); } String response = HttpUtil.get(domain + DEFINE_JOBS_EXECUTIONS + executionId + "/steps/" + stepId, TIMEOUT); JSONObject jsonObject = JSON.parseObject(response); String progressResponse = HttpUtil.get(domain + DEFINE_JOBS_EXECUTIONS + executionId + "/steps/" + stepId + "/progress", TIMEOUT); JSONObject progressJsonObject = JSON.parseObject(progressResponse); jo.put("stepsDetail",jsonObject); jo.put("progress",progressJsonObject); return jo; } @Override @SneakyThrows public JSONObject getJobsExecutionStepsByJobExecutionId(String projectId, Long jobId, int page, int size){ String domain = getScdfHttpDomainByProjectId(projectId); if(CharSequenceUtil.isEmpty(domain)) { throw new CheckedException(DEFINE_NOT_FOUND_RESOURCE_ADDRESS); } Map paramMap = new HashMap(); paramMap.put("page", page); paramMap.put("size", size); String response = HttpUtil.get(domain + DEFINE_JOBS_EXECUTIONS + jobId + "/steps", paramMap, TIMEOUT); return JSON.parseObject(response); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysDatasourceConf;import cn.chinatowercom.dataflow.backend.mapper.SysDatasourceConfMapper;import cn.chinatowercom.dataflow.backend.service.SysDatasourceConfService;import org.springframework.stereotype.Service;/** * 数据源表 * * @author catfishing * @date 2023-02-01 14:12:13 */@Servicepublic class SysDatasourceConfServiceImpl extends ServiceImpl<SysDatasourceConfMapper, SysDatasourceConf> implements SysDatasourceConfService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.SysDict;import cn.chinatowercom.dataflow.backend.entity.SysDictItem;import cn.chinatowercom.dataflow.backend.mapper.SysDictItemMapper;import cn.chinatowercom.dataflow.backend.service.SysDictItemService;import cn.chinatowercom.dataflow.backend.service.SysDictService;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.enums.DictTypeEnum;import lombok.RequiredArgsConstructor;import org.springframework.cache.annotation.CacheEvict;import org.springframework.stereotype.Service;import org.springframework.util.Assert;/** * 字典项 * * @author wildwind * @date 2022/03/19 */@Service@RequiredArgsConstructorpublic class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper, SysDictItem> implements SysDictItemService { private final SysDictService dictService; /** * 删除字典项 * @param id 字典项ID * @return */ @Override @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) public void removeDictItem(Long id) { // 根据ID查询字典ID SysDictItem dictItem = this.getById(id); SysDict dict = dictService.getById(dictItem.getDictId()); // 系统内置 Assert.state(!DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag()), "系统内置字典项目不能删除"); this.removeById(id); } /** * 更新字典项 * @param item 字典项 * @return */ @Override @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#item.type") public void updateDictItem(SysDictItem item) { // 查询字典 SysDict dict = dictService.getById(item.getDictId()); // 系统内置 Assert.state(!DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag()), "系统内置字典项目不能修改"); this.updateById(item); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.SysDict;import cn.chinatowercom.dataflow.backend.entity.SysDictItem;import cn.chinatowercom.dataflow.backend.mapper.SysDictItemMapper;import cn.chinatowercom.dataflow.backend.mapper.SysDictMapper;import cn.chinatowercom.dataflow.backend.service.SysDictService;import com.strongdata.dataflow.core.base.constant.CacheConstants;import com.strongdata.dataflow.core.base.constant.enums.DictTypeEnum;import lombok.RequiredArgsConstructor;import org.springframework.cache.annotation.CacheEvict;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.util.Assert;/** * <p> * 数据库字段字典值映射 * </p> * * @author catfishing * @since 2023-03-20 */@Service@RequiredArgsConstructorpublic class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements SysDictService { private final SysDictItemMapper dictItemMapper; /** * 根据ID 删除字典 * @param id 字典ID * @return */ @Override @Transactional(rollbackFor = Exception.class) @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) public void removeDict(Long id) { SysDict dict = this.getById(id); // 系统内置 log.debug("根据ID删除字典的字典类型:" + dict.getSystemFlag()); Assert.state(!DictTypeEnum.SYSTEM.getType().equals(dict.getSystemFlag()), "系统内置字典项目不能删除"); baseMapper.deleteById(id); dictItemMapper.delete(Wrappers.<SysDictItem>lambdaQuery().eq(SysDictItem::getDictId, id)); } /** * 更新字典 * @param dict 字典 * @return */ @Override @CacheEvict(value = CacheConstants.DICT_DETAILS, key = "#dict.type") public void updateDict(SysDict dict) { SysDict sysDict = this.getById(dict.getId()); // 系统内置 log.debug("更新字典的字典类型:" + dict.getSystemFlag()); Assert.state(!DictTypeEnum.SYSTEM.getType().equals(sysDict.getSystemFlag()), "系统内置字典项目不能修改"); this.updateById(dict); } /* 清理字典缓存接口 */ @Override @CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true) public void clearDictCache() { // do nothing }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportColumnRule;import cn.chinatowercom.dataflow.backend.mapper.SysImportColumnRuleMapper;import cn.chinatowercom.dataflow.backend.service.SysImportColumnRuleService;import org.springframework.stereotype.Service;import java.util.List;/** * 指标规则配置表 * * @author catfishing * @date 2023-03-13 15:20:16 */@Servicepublic class SysImportColumnRuleServiceImpl extends ServiceImpl<SysImportColumnRuleMapper, SysImportColumnRule> implements SysImportColumnRuleService { @Override public List<SysImportColumnRule> getColumnRules(List<Long> columnIds) { return baseMapper.getColumnRules(columnIds); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportColumn;import cn.chinatowercom.dataflow.backend.entity.vo.SysImportColumnVO;import cn.chinatowercom.dataflow.backend.mapper.SysImportColumnMapper;import cn.chinatowercom.dataflow.backend.service.SysImportColumnService;import org.springframework.stereotype.Service;import java.util.List;/** * 模板指标配置表 * * @author catfishing * @date 2023-03-13 15:20:16 */@Servicepublic class SysImportColumnServiceImpl extends ServiceImpl<SysImportColumnMapper, SysImportColumn> implements SysImportColumnService { /** * 根据sheet id查询属性配置 * * @param sheetIds * @return */ public List<SysImportColumn> getTemplateSheets(List<String> sheetIds) { return baseMapper.getTemplateSheets(sheetIds); } public List<SysImportColumnVO> getColumnRules(List<String> sheetIds) { return baseMapper.getColumnRules(sheetIds); } @Override public int removeByIds(List<Long> ids) { return baseMapper.removeByIds(ids); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import cn.chinatowercom.dataflow.backend.config.FilePathConfig;import cn.chinatowercom.dataflow.backend.config.MinioConfig;import cn.chinatowercom.dataflow.backend.constant.ImportFileType;import cn.chinatowercom.dataflow.backend.entity.SysImportFile;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoAttach;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLog;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportColumn;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportInfoDTO;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportSheet;import cn.chinatowercom.dataflow.backend.exception.DataFlowBackendRuntimeException;import cn.chinatowercom.dataflow.backend.mapper.SysImportFileMapper;import cn.chinatowercom.dataflow.backend.service.SysImportFileCheckService;import cn.chinatowercom.dataflow.backend.service.SysImportInfoAttachService;import cn.chinatowercom.dataflow.backend.service.SysImportInfoLogService;import cn.chinatowercom.dataflow.backend.service.SysImportInfoService;import cn.hutool.core.text.csv.CsvData;import cn.hutool.core.text.csv.CsvReadConfig;import cn.hutool.core.text.csv.CsvReader;import cn.hutool.core.text.csv.CsvRow;import cn.hutool.json.JSONUtil;import com.alibaba.fastjson.JSON;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.github.pjfanning.xlsx.StreamingReader;import com.strongdata.dataflow.code.file.util.FileUtil;import com.strongdata.dataflow.code.file.util.MinioCommonResp;import com.strongdata.dataflow.code.file.util.MinioUploadResp;import com.strongdata.dataflow.code.file.util.MinioUtil;import com.strongdata.dataflow.core.base.constant.enums.FileType;import com.strongdata.dataflow.core.base.exception.CheckedException;import com.strongdata.dataflow.core.base.util.DateUtil;import com.strongdata.dataflow.core.base.util.DecompressUtils;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.*;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.nio.file.Files;import java.nio.file.Paths;import java.text.SimpleDateFormat;import java.util.*;import java.util.stream.Collectors;/** * 文件管理表 * * @author hj * @date 2023-03-13 10:36:41 */@Service@Slf4jpublic class SysImportFileCheckServiceImpl extends ServiceImpl<SysImportFileMapper, SysImportFile> implements SysImportFileCheckService { private final static String DEFINE_FILE_NAME = "fileName"; private final static String DEFINE_FILE_SUFFIX = "fileSuffix"; private final static String DEFINE_FILE_PATH = "filePath"; private final static String DEFINE_DIFF_WITH_TEMPLATE_PARAM = "与模板配置不一致"; private final static String DEFINE_ERROR_LIST = "errorList"; private final static String DEFINE_SHEET_HEAD = "sheet:"; @Autowired private FilePathConfig filePathConfig; @Resource private MinioConfig minioConfig; @Autowired private SysImportInfoAttachService sysImportInfoAttachService; @Autowired private SysImportInfoService sysImportInfoService; @Autowired private SysImportInfoLogService sysImportInfoLogService; /** * 导入文件异步校验 * * @param sysImportInfoDTO * @param fileMap * @param sheetList * @param columnList */ @SneakyThrows @Async("templateCheck") @Transactional(transactionManager = "transactionManager") public void asynCheckFile(SysImportInfoDTO sysImportInfoDTO, Map<String, String> fileMap, List<SysImportSheet> sheetList, List<SysImportColumn> columnList) { //配置的文件根路径 String fileRootDir = filePathConfig.getFileRootDir(); String fileTempDir = filePathConfig.getFileTempDir(); String fileImportDir = filePathConfig.getFileImportDir(); String day = DateUtil.getDays(); String fileTempPath = fileRootDir + File.separator + fileTempDir + File.separator + day; String fileInportPath = fileRootDir + File.separator + fileImportDir + File.separator + day + File.separator + getMsTime(); //解压缩后文件的目标路径 String uncompressPath = fileTempPath + File.separator + DateUtil.getAllMSTime(); String fileTempAllPath = null; List<Map> fileError = new ArrayList<>(); Long importId = sysImportInfoDTO.getImportId(); try { //将属性根据sheet分组 Map<String, List<SysImportColumn>> columnMap = columnList.stream().collect(Collectors.groupingBy(SysImportColumn::getSheetId)); String fileName = fileMap.get(DEFINE_FILE_NAME); String fileSuffix = fileMap.get(DEFINE_FILE_SUFFIX); fileTempAllPath = fileMap.get(DEFINE_FILE_PATH); String originalFilename = fileMap.get("originalFilename"); Long fileSize = Long.parseLong(fileMap.get("fileSize")); // 校验模板和文件是否匹配,注意压缩文件以整体验证,必须全部通过才算通过 Boolean checkResult; //如果文件时压缩文件 if (!ImportFileType.FILE_XLS.equalsIgnoreCase(fileSuffix) && !ImportFileType.FILE_XLSX.equalsIgnoreCase(fileSuffix) && !ImportFileType.FILE_CSV.equalsIgnoreCase(fileSuffix)) { //将文件解压缩 this.uncompress(fileTempAllPath, uncompressPath); // 遍历一遍解压缩文件后的文件夹,最多2级 checkResult = this.traversalFileCheck(uncompressPath, fileError, sheetList, columnMap); } else { File excelFile = new File(fileTempAllPath); checkResult = this.checkFile(excelFile, originalFilename, fileError, fileSuffix, sheetList, columnMap); } //如果模板验证通过,保存文件信息,提交导入请求 if (checkResult) { //验证通过将文件从临时目录拷贝到正式目录 String importAllpath = null; importAllpath = FileUtil.copy(fileName, fileTempPath, fileInportPath, true); if("minio".equalsIgnoreCase(minioConfig.getStorageType())){ fileMap = fileUpLoadToMinio(importAllpath, originalFilename); fileName = fileMap.get(DEFINE_FILE_NAME); fileSuffix = fileMap.get(DEFINE_FILE_SUFFIX); importAllpath = fileMap.get(DEFINE_FILE_PATH); FileUtil.delFile(importAllpath); }else if("local".equalsIgnoreCase(minioConfig.getStorageType())){ //do nothing }else{ throw new DataFlowBackendRuntimeException("暂不支持的存储类型"); } //保存文件信息 Long fileId = this.saveImportFile(fileName, importAllpath, originalFilename, fileSize, fileSuffix, "minio".equalsIgnoreCase(minioConfig.getStorageType())?fileMap.get("bucketName"):null); sysImportInfoDTO.setFileId(fileId); //提交导入请求 this.submitImport(sysImportInfoDTO); } else { //校验未通过 更新info_log信息 UpdateWrapper<SysImportInfoLog> wrapper = new UpdateWrapper(); wrapper.eq("import_id", importId); wrapper.set("exception", JSON.toJSONString(fileError)); sysImportInfoLogService.update(wrapper); } } catch (Exception e) { log.error("读取文件错误", e); //校验文件抛出错误 Map check = new HashMap(); check.put(DEFINE_FILE_NAME, fileMap.get("originalFilename")); List<String> errorList = new ArrayList<>(); errorList.add("文件读取失败"); check.put(DEFINE_ERROR_LIST, errorList); fileError.add(check); UpdateWrapper<SysImportInfoLog> wrapper = new UpdateWrapper(); wrapper.eq("import_id", importId); wrapper.set("exception", JSON.toJSONString(fileError)); sysImportInfoLogService.update(wrapper); } finally { //将临时文件删除 FileUtil.delFile(fileTempAllPath); //将解压的临时文件夹删除 FileUtil.delFile(uncompressPath); } } public Map<String, String> fileUpLoadToMinio(String uploadFilePath, String originalFilename){ File uploadFile = new File(uploadFilePath); if(StringUtils.isBlank(originalFilename)){ originalFilename = uploadFile.getName(); } String fileName = null; String fileSuffix = null; if (!StringUtils.isBlank(originalFilename)) { fileName = originalFilename.substring(0, originalFilename.lastIndexOf('.')); fileSuffix = originalFilename.substring(originalFilename.lastIndexOf('.')); } String destFileName = fileName + "_" + getMsTime() + fileSuffix; String destFilePath = uploadFilePath.substring(0, uploadFilePath.lastIndexOf(File.separator)) + destFileName; File destFile = new File(destFilePath); boolean isReName = uploadFile.renameTo(destFile); if(!isReName){ log.info("修改文件名称失败!!"); } MinioCommonResp commonResp = MinioUtil.uploadFile(minioConfig.getStorageModuleCode(), destFile, destFileName, minioConfig.getStorageDomain()); if(commonResp == null || !"SUCCESS".equals(commonResp.getStatus()) || commonResp.getData() == null){ throw new DataFlowBackendRuntimeException("文件上传minio失败"); } if(uploadFile.exists()){ try { Files.delete(Paths.get(uploadFilePath)); } catch (IOException e) { log.info("删除uploadFile文件失败!!" + e.getMessage()); } } if(destFile.exists()){ try { Files.delete(Paths.get(destFilePath)); } catch (IOException e) { log.info("删除destFile文件失败!!" + e.getMessage()); } } MinioUploadResp uploadResp = JSONUtil.toBean(String.valueOf(commonResp.getData()), MinioUploadResp.class); Map<String, String> reMap = new HashMap(); reMap.put(DEFINE_FILE_PATH, uploadResp.getFileId()); reMap.put(DEFINE_FILE_NAME, destFileName); reMap.put(DEFINE_FILE_SUFFIX, fileSuffix); reMap.put("bucketName", uploadResp.getBucketName()); return reMap; } private String getMsTime() { return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); } /** * 压缩文件解压缩 * * @param fileAllPath * @param uncompressPath */ @SneakyThrows private void uncompress(String fileAllPath, String uncompressPath) { File file = new File(fileAllPath); FileType docType = DecompressUtils.getFileType(file); if (!docType.equals(FileType.UNKNOWN)) { if (docType.equals(FileType.ZIP)) { DecompressUtils.unZip(file, uncompressPath, false); } else if (docType.equals(FileType.RAR)) { DecompressUtils.uncompressAllFile(file, uncompressPath, false); } else if (docType.equals(FileType._7Z)) { DecompressUtils.decompress7Z(file, uncompressPath, false); } else if (docType.equals(FileType.TAR)) { DecompressUtils.decompressTar(file, uncompressPath, false); } else if (docType.equals(FileType.GZ)) { DecompressUtils.decompressGz(file, uncompressPath, false); } else if (docType.equals(FileType.TAR_GZ)) { DecompressUtils.decompressTarGz(file, uncompressPath, false); } else if (docType.equals(FileType.BZ2)) { DecompressUtils.decompressBZ2(file, uncompressPath, false); } else if (docType.equals(FileType.TAR_BZ2)) { DecompressUtils.decompressTarBz2(file, uncompressPath, false); } } else { throw new CheckedException("上传文件解析失败"); } } /** * 遍历文件夹及子文件夹中文件 * * @param uncompressPath */ @SneakyThrows private Boolean traversalFileCheck(String uncompressPath, List<Map> fileError, List<SysImportSheet> sheetList, Map<String, List<SysImportColumn>> columnMap) { //压缩文件内的所有文件是否验证通过,只有全部验证通过才算通过 Boolean checkResult = true; //验证压缩文件内部压缩的文件是否有excel文件(xls/xlsx/csv),如果压缩文件内部没有一个excel文件要抛出错误 Boolean isExcelFile = false; File dirFile = new File(uncompressPath); //先进入解压缩后的文件夹 if (dirFile != null) { //此时需要获得当前文件夹下所有文件,包括目录 File[] firstFloorFiles = dirFile.listFiles(); //files下的所有内容,可能是文件夹,也可能是文件,那么需要一个个去判断是文件还是文件夹,这个判断过程就是这里封装的方法 for (File firstFloorFile : firstFloorFiles) { if (firstFloorFile.isDirectory()) { //如果是文件夹需要在找一级,导入最多2级 File[] secondFloorFiles = firstFloorFile.listFiles(); for (File secondFloorFile : secondFloorFiles) { if (secondFloorFile.isFile()) { String fileName = secondFloorFile.getName(); //文件后缀 String fileSuffix = fileName.substring(fileName.lastIndexOf('.')); if (ImportFileType.FILE_XLS.equalsIgnoreCase(fileSuffix) || ImportFileType.FILE_XLSX.equalsIgnoreCase(fileSuffix) || ImportFileType.FILE_CSV.equalsIgnoreCase(fileSuffix)) { Boolean check = this.checkFile(secondFloorFile, fileName, fileError, fileSuffix, sheetList, columnMap); if (!check) {//如果有一个验证未通过,则改压缩文件整体验证为未通过 checkResult = check; } isExcelFile = true; } } } } else { String fileName = firstFloorFile.getName(); //文件后缀 String fileSuffix = fileName.substring(fileName.lastIndexOf('.')); if (ImportFileType.FILE_XLS.equalsIgnoreCase(fileSuffix) || ImportFileType.FILE_XLSX.equalsIgnoreCase(fileSuffix) || ImportFileType.FILE_CSV.equalsIgnoreCase(fileSuffix)) { Boolean check = this.checkFile(firstFloorFile, fileName, fileError, fileSuffix, sheetList, columnMap); if (!check) {//如果有一个验证未通过,则改压缩文件整体验证为未通过 checkResult = check; } isExcelFile = true; } } } if (!isExcelFile) { throw new CheckedException("压缩文件内最少应包括一个excel文件,且压缩包最多为2级"); } return checkResult; } else { throw new CheckedException("上传文件解析失败"); } } /** * 验证文件是否符合模板配置 * * @param file * @param originalFilename * @param fileError * @param fileSuffix * @param sheetList * @param columnMap * @return */ private Boolean checkFile(File file, String originalFilename, List<Map> fileError, String fileSuffix, List<SysImportSheet> sheetList, Map<String, List<SysImportColumn>> columnMap) { if (ImportFileType.FILE_XLS.equalsIgnoreCase(fileSuffix)) { return this.checkXlsFile(file, originalFilename, fileError, sheetList, columnMap); } else if (ImportFileType.FILE_XLSX.equalsIgnoreCase(fileSuffix)) { return this.checkXlsxFile(file, originalFilename, fileError, sheetList, columnMap); } else if (ImportFileType.FILE_CSV.equalsIgnoreCase(fileSuffix)) { return this.checkCsvFile(file, originalFilename, fileError, sheetList, columnMap); } return false; } /** * 验证xls文件是否符合模板配置 * * @param file */ private Boolean checkXlsFile(File file, String originalFilename, List<Map> fileError, List<SysImportSheet> sheetList, Map<String, List<SysImportColumn>> columnMap) { Map check = new HashMap(); check.put(DEFINE_FILE_NAME, originalFilename); List<String> errorList = new ArrayList<>(); check.put(DEFINE_ERROR_LIST, errorList); try (InputStream inputStream = new FileInputStream(file); // 读取Excel HSSFWorkbook workbook = new HSSFWorkbook(inputStream) ) { boolean checkResult = true; //文件中sheet数量 int fileSheetNums = workbook.getNumberOfSheets(); //模板中配置的sheet数量 int templateSheetNum = sheetList.size(); if (fileSheetNums < templateSheetNum) { //首先验证sheet数量是否一致,如果不一致之间返回验证不通过 errorList.add("包含的sheet数量与模板配置不一致,缺少sheet"); } //逐个对比sheet和sheet中的属性信息,上传文件有可能sheet顺序和模板配置的顺序不一致,故根据模板去寻找文件的sheet, // 只要模板中的sheet在文件中都能找到就行 for (int i = 0; i < templateSheetNum; i++) { //获取模板的sheet SysImportSheet sysImportSheet = sheetList.get(i); String sysImportSheetName = sysImportSheet.getSheetName(); Boolean sheetExist = false;//默认在文件中没有找到模板配置的sheet //循环文件中的sheet,去找模板中的sheet与文件sheet名称一致的 for (int j = 0; j < fileSheetNums; j++) { // 获取文件Sheet HSSFSheet fileSheet = workbook.getSheetAt(j); String fileSheetName = fileSheet.getSheetName(); if (fileSheetName.equals(sysImportSheetName)) { sheetExist = true; //获取文件标题行 HSSFRow headerRow = fileSheet.getRow(sysImportSheet.getTitleRow()); //文件中标题行的总列数 int fileHeaderCallNum = headerRow.getPhysicalNumberOfCells(); // 获取模板sheet中的属性配置 List<SysImportColumn> columnList = columnMap.get(sysImportSheet.getSheetId()); //模板配置的读取开始的列 //Integer startCol = sysImportSheet.getStartCol() != null ? sysImportSheet.getStartCol() : 0; //比对属性数量是否一致 if (null == columnList || columnList.isEmpty()) { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的表头与模板配置不一致,模板中未配置表头"); continue; } if (fileHeaderCallNum < columnList.size()) { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的表头与模板配置不一致,文件中缺少表头"); continue; } //逐一比对字段名称 for (SysImportColumn column : columnList) { //获取单元格中的内容 HSSFCell headerCell = headerRow.getCell(column.getCellOrder()); if (null != headerCell) { headerCell.setCellType(CellType.STRING); String cellValue = headerCell.getStringCellValue(); if (!cellValue.equals(column.getImFrom())) { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的第" + (column.getCellOrder() + 1) + "列表头:" + cellValue + DEFINE_DIFF_WITH_TEMPLATE_PARAM); } } else { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的第" + (column.getCellOrder() + 1) + "列没有读取到表头,与模板配置不一致"); } } break; } } if (!sheetExist) { checkResult = false; errorList.add("文件中缺少名称为:" + sysImportSheetName + "的sheet"); } } if (!checkResult) { fileError.add(check); } return checkResult; } catch (Exception e) { log.error("读取xls文件错误", e); errorList.add("读取失败"); } fileError.add(check); return false; } /** * 验证xlsx文件是否符合模板配置 * * @param file */ private Boolean checkXlsxFile(File file, String originalFilename, List<Map> fileError, List<SysImportSheet> sheetList, Map<String, List<SysImportColumn>> columnMap) { Map check = new HashMap(); check.put(DEFINE_FILE_NAME, originalFilename); List<String> errorList = new ArrayList<>(); check.put(DEFINE_ERROR_LIST, errorList); try (InputStream inputStream = new FileInputStream(file); Workbook workbook = StreamingReader.builder() .rowCacheSize(10) //缓存到内存中的行数,默认是10 .bufferSize(1024) //读取资源时,缓存到内存的字节大小,默认是1024 .open(inputStream) //打开资源,必须,可以是InputStream或者是File,注意:只能打开XLSX格式的文件 ) { boolean checkResult = true; //获取文件中sheet数量 int fileSheetNums = workbook.getNumberOfSheets(); //模板中配置的sheet数量 int templateSheetNum = sheetList.size(); if (fileSheetNums < templateSheetNum) { //首先验证sheet数量是否大于等于模板配置的数量 errorList.add("包含的sheet数量与模板配置不一致,缺少sheet"); } //逐一比对sheet信息 for (int i = 0; i < templateSheetNum; i++) { SysImportSheet sysImportSheet = sheetList.get(i); String sysImportSheetName = sysImportSheet.getSheetName(); Boolean sheetExist = false;//默认在文件中没有找到模板配置的sheet //循环文件中的sheet,去找模板中的sheet与文件sheet名称一致的 for (int j = 0; j < fileSheetNums; j++) { //获取文件中sheet信息 Sheet fileSheet = workbook.getSheetAt(j); String fileSheetName = fileSheet.getSheetName(); //比对sheetName if (fileSheetName.equals(sysImportSheetName)) { sheetExist = true; //遍历所有的行,找到表头行 for (Row headerRow : fileSheet) { //因为流读取xlsx文件不能指定行,需要行一行读取直到指定的标题行 int rowNum = headerRow.getRowNum(); //模板配置的标题行位置 Integer titleRow = sysImportSheet.getTitleRow(); if (rowNum == titleRow) { //找到标题行 //标题行的总列数 int fileHeaderCallNum = headerRow.getPhysicalNumberOfCells(); //获取模板sheet中的属性配置 List<SysImportColumn> columnList = columnMap.get(sysImportSheet.getSheetId()); //模板配置的读取开始的列 // Integer startCol = sysImportSheet.getStartCol() != null ? sysImportSheet.getStartCol() : 0; //比对属性数量是否一致 if (null == columnList || columnList.isEmpty()) { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的表头与模板配置不一致,模板中未配置表头"); continue; } if (fileHeaderCallNum < columnList.size()) { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的表头与模板配置不一致,文件中缺少表头"); continue; } //逐一比对字段名称 for (SysImportColumn column : columnList) { //获取单元格中的内容 Cell headerCell = headerRow.getCell(column.getCellOrder()); if (null != headerCell) { String cellValue = headerCell.getStringCellValue(); if (!cellValue.equals(column.getImFrom())) { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的第" + (column.getCellOrder() + 1) + "列表头:" + cellValue + DEFINE_DIFF_WITH_TEMPLATE_PARAM); } } else { checkResult = false; errorList.add(DEFINE_SHEET_HEAD + fileSheetName + "的第" + (column.getCellOrder() + 1) + "列没有读取到表头,与模板配置不一致"); } } break; } } break; } } if (!sheetExist) { checkResult = false; errorList.add("文件中缺少名称为:" + sysImportSheetName + "的sheet"); } } if (!checkResult) { fileError.add(check); } return checkResult; } catch (Exception e) { log.error("读取xlsx文件错误", e); errorList.add("读取失败"); } fileError.add(check); return false; } /** * 验证csv文件是否符合模板配置 * * @param file */ private Boolean checkCsvFile(File file, String originalFilename, List<Map> fileError, List<SysImportSheet> sheetList, Map<String, List<SysImportColumn>> columnMap) { Map check = new HashMap(); check.put(DEFINE_FILE_NAME, originalFilename); List<String> errorList = new ArrayList<>(); check.put(DEFINE_ERROR_LIST, errorList); CsvReader reader = null; try { boolean checkResult = true; //首先验证sheet数量,CSV只能由一个sheet,csv文件不验证sheet名称只验证数量 //模板中配置的sheet数量 int templateSheetNum = sheetList.size(); if (templateSheetNum != 1) { //首先验证模板的sheet数量是否是1个 errorList.add("包含的sheet数量与模板配置不一致,缺少sheet"); fileError.add(check); return false; } //配置CSV文件的读取位置,CSV只有一个sheet,使用模板的第一个sheet即可 SysImportSheet sysImportSheet = sheetList.get(0); CsvReadConfig csvReadConfig = new CsvReadConfig(); csvReadConfig.setBeginLineNo(sysImportSheet.getTitleRow()); csvReadConfig.setEndLineNo(sysImportSheet.getTitleRow()); reader = new CsvReader(file, csvReadConfig); //从文件中读取CSV数据 CsvData data = reader.read(); List<CsvRow> rows = data.getRows(); if (rows.isEmpty()) { errorList.add("表头与模板配置不一致,文件中未读取到表头"); fileError.add(check); return false; } //获取标题行,因为只获取了一行数据,就默认第一个是标题行 CsvRow row = rows.get(0); //获取标题行的内容是否与模板配置的字段数量一致 List<String> rawList = row.getRawList(); //获取模板sheet中的属性配置 List<SysImportColumn> columnList = columnMap.get(sysImportSheet.getSheetId()); //模板配置的读取开始的列,CSV文件前面不能有空列 //Integer startCol = sysImportSheet.getStartCol() != null ? sysImportSheet.getStartCol() : 0; //标题行的总列数 int fileHeaderCallNum = rawList.size(); //比对属性数量是否一致 if (null == columnList || columnList.isEmpty()) { errorList.add("表头与模板配置不一致,模板中未配置表头"); fileError.add(check); return false; } if (fileHeaderCallNum < columnList.size()) { errorList.add("表头与模板配置不一致,文件中缺少表头"); fileError.add(check); return false; } //遍历所有的列 for (SysImportColumn column : columnList) { Integer cellOrder = column.getCellOrder(); if (cellOrder < fileHeaderCallNum) { String header = rawList.get(cellOrder); if (header.startsWith("\uFEFF")){ header = header.replace("\uFEFF", ""); } //获取模板中的属性配置 if (!header.equals(column.getImFrom())) { checkResult = false; errorList.add("第" + (column.getCellOrder() + 1) + "列表头:" + header + DEFINE_DIFF_WITH_TEMPLATE_PARAM); } } else { checkResult = false; errorList.add("第" + (column.getCellOrder() + 1) + "列没有读取到表头,与模板配置不一致"); } } if (!checkResult) { fileError.add(check); } return checkResult; } catch (Exception e) { log.error("读取CSV文件错误", e); errorList.add("读取失败;"); } finally { if (null != reader) { try { reader.close(); } catch (IOException e) { log.error(e.getMessage()); } } } fileError.add(check); return false; } /** * 保存导入文件信息 * * @param * @return */ private Long saveImportFile(String fileName, String fileAllPath, String originalFilename, Long fileSize, String fileType, String bucketName) { SysImportFile sysImportFile = new SysImportFile(); sysImportFile.setFileName(fileName); sysImportFile.setFilePath(fileAllPath); sysImportFile.setFileSize(fileSize); sysImportFile.setOriginal(originalFilename); sysImportFile.setType(fileType.replaceFirst("\\.", "")); sysImportFile.setFileGroup(1); sysImportFile.setBucketName(bucketName); save(sysImportFile); return sysImportFile.getId(); } /** * 保存附件信息,提交导入请求 * * @param * @return */ private void submitImport(SysImportInfoDTO sysImportInfoDTO) { //保存附件信息 SysImportInfoAttach sysImportInfoAttach = new SysImportInfoAttach(); sysImportInfoAttach.setFileId(sysImportInfoDTO.getFileId()); sysImportInfoAttach.setImportId(sysImportInfoDTO.getImportId()); sysImportInfoAttachService.save(sysImportInfoAttach); //提交导入请求 sysImportInfoService.submitImport(sysImportInfoDTO); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import cn.chinatowercom.dataflow.backend.config.FilePathConfig;import cn.chinatowercom.dataflow.backend.config.MinioConfig;import cn.chinatowercom.dataflow.backend.entity.SysImportFile;import cn.chinatowercom.dataflow.backend.entity.SysImportInfo;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLog;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportColumn;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportInfoDTO;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportSheet;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportTemplate;import cn.chinatowercom.dataflow.backend.exception.DataFlowBackendRuntimeException;import cn.chinatowercom.dataflow.backend.mapper.SysImportFileMapper;import cn.chinatowercom.dataflow.backend.service.*;import cn.hutool.json.JSONUtil;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.code.file.util.FileUtil;import com.strongdata.dataflow.code.file.util.MinioCommonResp;import com.strongdata.dataflow.code.file.util.MinioUploadResp;import com.strongdata.dataflow.code.file.util.MinioUtil;import com.strongdata.dataflow.core.base.util.DateUtil;import com.strongdata.dataflow.core.base.util.R;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.nio.file.Files;import java.nio.file.Paths;import java.text.SimpleDateFormat;import java.time.LocalDateTime;import java.util.*;import java.util.stream.Collectors;/** * 文件管理表 * * @author hj * @date 2023-03-13 10:36:41 */@Slf4j@Servicepublic class SysImportFileServiceImpl extends ServiceImpl<SysImportFileMapper, SysImportFile> implements SysImportFileService { private final static String DEFINE_FILEPATH = "filePath"; private final static String DEFINE_MINIO = "minio"; private final static String DEFINE_DEL_FLAG = "del_flag"; @Resource private FilePathConfig filePathConfig; @Resource private MinioConfig minioConfig; @Resource private SysImportTemplateService sysImportTemplateService; @Resource private SysImportSheetService sysImportSheetService; @Resource private SysImportColumnService sysImportColumnService; @Resource private SysImportInfoService sysImportInfoService; @Resource private SysImportInfoLogService sysImportInfoLogService; @Resource private SysImportFileCheckService sysImportFileCheckService; /** * 导入文件上传 * * @param sysImportInfoDTO * @param multipartFile * @return */ @SneakyThrows public R uploadImportFile(SysImportInfoDTO sysImportInfoDTO, MultipartFile multipartFile) { //配置的文件根路径 String fileRootDir = filePathConfig.getFileRootDir(); String fileTemptDir = filePathConfig.getFileTempDir(); String day = DateUtil.getDays(); String fileTemptPath = fileRootDir + File.separator + fileTemptDir + File.separator + day; String templateId = sysImportInfoDTO.getTemplateId(); //获取模板信息,校验模板状态 SysImportTemplate sysImportTemplate = sysImportTemplateService.getById(templateId); if (null == sysImportTemplate || sysImportTemplate.getStatus() == 0 || !sysImportTemplate.getDelFlag().equals("0")) { return R.failed("模板信息已删除或停用,请确认后再导入"); } List<SysImportSheet> sheetList = sysImportSheetService.getTemplateSheets(templateId); if (sheetList.isEmpty()) { return R.failed("模板没有配置sheet信息,请确认后再导入"); } List<String> sheetIds = sheetList.stream().map(SysImportSheet::getSheetId).collect(Collectors.toList()); //获取sheet下的属性配置 List<SysImportColumn> columnList = sysImportColumnService.getTemplateSheets(sheetIds); if (columnList.isEmpty()) { return R.failed("模板sheet没有配置属性信息,请确认后再导入"); } //先将文件存储 String originalFilename = multipartFile.getOriginalFilename(); Long fileSize = multipartFile.getSize(); log.debug("导入文件上传文件,执行前 - 文件名:{}", originalFilename); Map<String, String> fileMap = FileUtil.uploadFile(multipartFile.getInputStream(), originalFilename, fileTemptPath); log.debug("导入文件上传文件,执行后 - 文件信息[filePath]:{}", fileMap.get(DEFINE_FILEPATH)); fileMap.put("originalFilename", originalFilename); fileMap.put("fileSize", fileSize.toString()); //保存info和infl_log表数据 Long importId = this.saveImportInfo(sysImportInfoDTO); sysImportInfoDTO.setImportId(importId); //异步校验文件是否符合模板 sysImportFileCheckService.asynCheckFile(sysImportInfoDTO, fileMap, sheetList, columnList); return R.ok(String.valueOf(importId)); } /** * 保存导入文件信息 * * @param * @return */ private Long saveImportInfo(SysImportInfoDTO sysImportInfoDTO) { //保存importInfo信息 SysImportInfo sysImportInfo = new SysImportInfo(); sysImportInfo.setTemplateId(sysImportInfoDTO.getTemplateId()); sysImportInfo.setImportType(sysImportInfoDTO.getImportType()); sysImportInfo.setCreateBy(sysImportInfoDTO.getUserId()); sysImportInfo.setCreateName(sysImportInfoDTO.getUserName()); sysImportInfoService.save(sysImportInfo); Long importId = sysImportInfo.getId(); //保存importInfoLog信息 SysImportInfoLog sysImportInfoLog = new SysImportInfoLog(); sysImportInfoLog.setImportId(importId); sysImportInfoLog.setTemplateId(sysImportInfoDTO.getTemplateId()); sysImportInfoLog.setStartDate(LocalDateTime.now()); sysImportInfoLog.setProjectId(sysImportInfoDTO.getProjectId()); sysImportInfoLog.setCreateBy(sysImportInfoDTO.getUserId()); sysImportInfoLog.setCreateName(sysImportInfoDTO.getUserName()); sysImportInfoLogService.save(sysImportInfoLog); return importId; } /** * 文件上传 * * @param multipartFile * @return */ @SneakyThrows public Long uploadFile(Integer fileGrpup, MultipartFile multipartFile) { //配置的文件根路径 String fileRootDir = filePathConfig.getFileRootDir(); String fileOthertDir = filePathConfig.getFileOthertDir(); String day = DateUtil.getDays(); String fileTemptPath = fileRootDir + File.separator + fileOthertDir + File.separator + day; //文件原名称 String originalFilename = multipartFile.getOriginalFilename(); Long fileSize = multipartFile.getSize(); Map<String, String> fileMap = null; if("local".equalsIgnoreCase(minioConfig.getStorageType())){ fileMap = FileUtil.uploadFile(multipartFile.getInputStream(), originalFilename, fileTemptPath); }else if(DEFINE_MINIO.equalsIgnoreCase(minioConfig.getStorageType())){ fileMap = fileUpLoadToMinio(multipartFile, originalFilename, fileTemptPath); }else{ throw new DataFlowBackendRuntimeException("暂不支持的存储类型"); } if (null != fileMap) { String fileName = fileMap.get("fileName"); String fileSuffix = fileMap.get("fileSuffix"); String filePath = fileMap.get(DEFINE_FILEPATH); //保存文件信息 return this.saveImportFile(fileName, filePath, originalFilename, fileSize, fileSuffix, fileGrpup, DEFINE_MINIO.equalsIgnoreCase(minioConfig.getStorageType())?fileMap.get("bucketName"):null); } else { throw new DataFlowBackendRuntimeException("上传文件失败"); } } @SneakyThrows public Map<String, String> fileUpLoadToMinio(MultipartFile multipartFile, String originalFilename, String tempPath){ tempPath = tempPath+File.separator+getMsTime(); if (!FileUtil.checkFileDirExits(tempPath)) { FileUtil.makeDir(tempPath); } File uploadFile = new File(tempPath+File.separator+originalFilename); multipartFile.transferTo(uploadFile); if(StringUtils.isBlank(originalFilename)){ originalFilename = uploadFile.getName(); } String fileName = null; String fileSuffix = null; if (!StringUtils.isBlank(originalFilename)) { fileName = originalFilename.substring(0, originalFilename.lastIndexOf('.')); fileSuffix = originalFilename.substring(originalFilename.lastIndexOf('.')); } String destFileName = fileName + "_" + getMsTime() + fileSuffix; File destFile = new File(tempPath+File.separator+destFileName); if(!uploadFile.renameTo(destFile)){ log.info("修改文件名称失败!!"); } MinioCommonResp commonResp = MinioUtil.uploadFile(minioConfig.getStorageModuleCode(), destFile, destFileName, minioConfig.getStorageDomain()); if(commonResp == null || !"SUCCESS".equals(commonResp.getStatus()) || commonResp.getData() == null){ throw new DataFlowBackendRuntimeException("文件上传minio失败"); } if(uploadFile.exists()){ Files.delete(Paths.get(uploadFile.getPath())); } if(destFile.exists()){ Files.delete(Paths.get(destFile.getPath())); } MinioUploadResp uploadResp = JSONUtil.toBean(String.valueOf(commonResp.getData()), MinioUploadResp.class); Map<String, String> reMap = new HashMap(); reMap.put(DEFINE_FILEPATH, uploadResp.getFileId()); reMap.put("fileName", destFileName); reMap.put("fileSuffix", fileSuffix); reMap.put("bucketName", uploadResp.getBucketName()); return reMap; } private String getMsTime() { return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); } /** * 保存导入文件信息 * * @param * @return */ private Long saveImportFile(String fileName, String fileAllPath, String originalFilename, Long fileSize, String fileType, Integer fileGrpup, String bucketName) { SysImportFile sysImportFile = new SysImportFile(); sysImportFile.setFileName(fileName); sysImportFile.setFilePath(fileAllPath); sysImportFile.setFileSize(fileSize); sysImportFile.setOriginal(originalFilename); sysImportFile.setType(fileType.replaceFirst("\\.", "")); sysImportFile.setFileGroup(fileGrpup); sysImportFile.setBucketName(bucketName); save(sysImportFile); return sysImportFile.getId(); } /** * 下载文件 * * @param fileId * @param request * @param response * @return */ @SneakyThrows public void downFile(String fileId, String contentType, HttpServletRequest request, HttpServletResponse response) { //查询导入导出文件信息 SysImportFile sysImportFile = getById(fileId); if (sysImportFile == null || sysImportFile.getDelFlag().equals("1")) { log.error("文件因超出保存时限已删除"); throw new DataFlowBackendRuntimeException("文件因超出保存时限已删除,不能下载"); } String filePath = sysImportFile.getFilePath(); String originalName = sysImportFile.getOriginal(); if("local".equalsIgnoreCase(minioConfig.getStorageType())){ FileUtil.downFile(filePath, contentType, originalName, request, response); }else if(DEFINE_MINIO.equalsIgnoreCase(minioConfig.getStorageType())){ String fileRootDir = filePathConfig.getFileRootDir(); String fileTemptDir = filePathConfig.getFileTempDir(); String day = DateUtil.getDays(); String fileTemptPath = fileRootDir + File.separator + fileTemptDir + File.separator + day; String downFileAbsPath = fileDownloadFromMinio(fileTemptPath, sysImportFile.getBucketName(), sysImportFile.getFileName()); if(StringUtils.isBlank(downFileAbsPath)) throw new DataFlowBackendRuntimeException("文件下载失败"); FileUtil.downFile(downFileAbsPath, contentType, sysImportFile.getFileName(), request, response); FileUtil.delFile(downFileAbsPath); }else{ throw new DataFlowBackendRuntimeException("暂不支持的存储类型"); } } public String fileDownloadFromMinio(String tempDir, String bucketName, String objectName) { return MinioUtil.downFile(tempDir, bucketName, objectName, minioConfig.getStorageDomain()); } /** * 定时扫描临时目录删除1天前的临时文件 */ @Scheduled(cron = "0 0 1 * * ?") public void delTempileTask() { //配置的文件根路径 String fileRootDir = filePathConfig.getFileRootDir(); String fileTempDir = filePathConfig.getFileTempDir(); String fileTemptPath = fileRootDir + File.separator + fileTempDir; Date date = new Date(); if (FileUtil.checkFileDirExits(fileTemptPath)) { File tempFolder = new File(fileTemptPath); File[] files = tempFolder.listFiles();//注意:这里只能用listFiles(),不能使用list() //获取临时目录下的文件夹,文件夹以日期命名,获取文件夹名称后即得知那天的文件夹 for (File flie : files) { String fileFolderName = flie.getName(); Date fileDate = DateUtil.parse(fileFolderName, "yyyyMMdd"); if (null != fileDate) { int days = (int) ((date.getTime() - fileDate.getTime()) / (1000 * 3600 * 24)); if (days > 1) { FileUtil.delFile(flie.getAbsolutePath()); } } } } } /** * 定时扫描文件表,删除保存期超过60天的文件 */// @Scheduled(cron = "0 0 2 * * ?") @Scheduled(cron = "${backend.scheduled.cron:0 0 2 * * ?}") public void delDataFile() { //获取60天前的日期 Date date = DateUtil.getDateBeforeDay(new Date(), 60); //查询60天前的文件 QueryWrapper<SysImportFile> queryWrapper = new QueryWrapper(); queryWrapper.eq(DEFINE_DEL_FLAG, 0); queryWrapper.lt("create_time", date); queryWrapper.in("file_group", 1, 3); List<SysImportFile> fileList = getBaseMapper().selectList(queryWrapper); delFile(fileList); } /** * 定时扫描文件表,删除保存期超过20天的拆分文件 */ @Scheduled(cron = "0 0 3 * * ?") public void delCSVFile() { //获取60天前的日期 Date date = DateUtil.getDateBeforeDay(new Date(), 20); //查询60天前的文件 QueryWrapper<SysImportFile> queryWrapper = new QueryWrapper(); queryWrapper.eq(DEFINE_DEL_FLAG, 0); queryWrapper.lt("create_time", date); queryWrapper.in("file_group", 2); List<SysImportFile> fileList = getBaseMapper().selectList(queryWrapper); delFile(fileList); } /** * 删除文件 * * @param fileList */ private void delFile(List<SysImportFile> fileList) { //删除文件 List<Long> fileId = new ArrayList<>(); for (SysImportFile file : fileList) { Boolean re = FileUtil.delFile(file.getFilePath()); if (re) { fileId.add(file.getId()); } } if (!fileId.isEmpty()) { //更新文件表状态 UpdateWrapper<SysImportFile> updateWrapper = new UpdateWrapper(); updateWrapper.in("id", fileId); updateWrapper.set(DEFINE_DEL_FLAG, 1); getBaseMapper().update(null, updateWrapper); } }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoAttach;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoAttachMapper;import cn.chinatowercom.dataflow.backend.service.SysImportInfoAttachService;import org.springframework.stereotype.Service;/** * 导入导出文件信息附件表 * * @author hj * @date 2023-03-13 10:41:31 */@Servicepublic class SysImportInfoAttachServiceImpl extends ServiceImpl<SysImportInfoAttachMapper, SysImportInfoAttach> implements SysImportInfoAttachService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLog;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLogTask;import cn.chinatowercom.dataflow.backend.entity.vo.SysImportInfoLogVO;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoLogMapper;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoLogTaskMapper;import cn.chinatowercom.dataflow.backend.service.SysImportInfoLogService;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.time.LocalDateTime;import java.util.List;import java.util.Objects;/** * 导入日志表 * * @author hj * @date 2023-03-15 15:32:33 */@Service@Slf4jpublic class SysImportInfoLogServiceImpl extends ServiceImpl<SysImportInfoLogMapper, SysImportInfoLog> implements SysImportInfoLogService { @Autowired SysImportInfoLogTaskMapper sysImportInfoLogTaskMapper; @Override public IPage<SysImportInfoLogVO> getSysImportInfoLogPage(Page page, SysImportInfoLog sysImportInfoLog) { String username = sysImportInfoLog.getCreateName(); log.info("username:{}", username); if(!Objects.isNull(username)) { if("admin".equals(username)) { sysImportInfoLog.setCreateName(null); } else { sysImportInfoLog.setCreateName(username); } } else { sysImportInfoLog.setCreateName("null"); } return baseMapper.getSysImportInfoLogPage(page, sysImportInfoLog); } @Override public int updateByImportId(SysImportInfoLog sysImportInfoLog) { SysImportInfoLogTask sysImportInfoLogTask = new SysImportInfoLogTask(); sysImportInfoLogTask.setImportId(sysImportInfoLog.getImportId()); List<SysImportInfoLogTask> sysImportInfoLogTaskList = sysImportInfoLogTaskMapper.selectList(Wrappers.query(sysImportInfoLogTask)); if(CollectionUtils.isEmpty(sysImportInfoLogTaskList)) return -1; QueryWrapper<SysImportInfoLog> wrapper = new QueryWrapper<>(); wrapper.eq("import_id", sysImportInfoLog.getImportId()); SysImportInfoLog oldLog = baseMapper.selectOne(wrapper); if (oldLog == null) { return -1; } else {// LocalDateTime maxBirthday = sysImportInfoLogTaskList.stream()// .map(SysImportInfoLogTask::getEndDate)// .max(LocalDateTime::compareTo)// .orElse(LocalDateTime.now()); sysImportInfoLog.setLogId(oldLog.getLogId()); return baseMapper.updateById(sysImportInfoLog); } }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoLogTask;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoSplit;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoLogTaskMapper;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoSplitMapper;import cn.chinatowercom.dataflow.backend.service.SysImportInfoLogTaskService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/** * * * @author liangbing * @date 2023-04-06 16:58:23 */@Servicepublic class SysImportInfoLogTaskServiceImpl extends ServiceImpl<SysImportInfoLogTaskMapper, SysImportInfoLogTask> implements SysImportInfoLogTaskService { @Autowired private SysImportInfoSplitMapper sysImportInfoSplitMapper; @Override public int insertOrUpdate(SysImportInfoLogTask sysImportInfoLogTask) { QueryWrapper<SysImportInfoLogTask> wrapper = new QueryWrapper<>(); wrapper.eq("task_id", sysImportInfoLogTask.getTaskId()); SysImportInfoLogTask oldLogTask = baseMapper.selectOne(wrapper); if (oldLogTask == null) { return baseMapper.insert(sysImportInfoLogTask); } else { if(sysImportInfoLogTask.getErrFileId() != null){ SysImportInfoSplit sysImportInfoSplit = new SysImportInfoSplit(); sysImportInfoSplit.setSplitId(sysImportInfoLogTask.getSplitId()); sysImportInfoSplit.setErrorFileId(sysImportInfoLogTask.getErrFileId()); sysImportInfoSplitMapper.updateById(sysImportInfoSplit); } sysImportInfoLogTask.setLogTaskId(oldLogTask.getLogTaskId()); return baseMapper.updateById(sysImportInfoLogTask); } } public List<SysImportInfoLogTask> getByImportId(Long importId){ SysImportInfoLogTask sysImportInfoLogTask = new SysImportInfoLogTask(); sysImportInfoLogTask.setImportId(importId); return baseMapper.selectList(Wrappers.query(sysImportInfoLogTask)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import cn.chinatowercom.dataflow.backend.component.DataflowServerClient;import cn.chinatowercom.dataflow.backend.config.MinioConfig;import cn.chinatowercom.dataflow.backend.constant.CacheConst;import cn.chinatowercom.dataflow.backend.entity.SysImportFile;import cn.chinatowercom.dataflow.backend.entity.SysImportInfo;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoSplit;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportInfoDTO;import cn.chinatowercom.dataflow.backend.entity.vo.SysImportInfoVO;import cn.chinatowercom.dataflow.backend.mapper.SysImportFileMapper;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoMapper;import cn.chinatowercom.dataflow.backend.service.SysImportInfoService;import cn.chinatowercom.dataflow.backend.service.SysImportInfoSplitService;import cn.chinatowercom.dataflow.backend.service.TaskSeqService;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.util.R;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.Cursor;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ScanOptions;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;import org.springframework.util.CollectionUtils;import org.springframework.util.StringUtils;import javax.annotation.Resource;import java.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.List;import java.util.Map;/** * 导入导出结果表 * * @author hj * @date 2023-03-15 15:32:33 */@Service@Slf4jpublic class SysImportInfoServiceImpl extends ServiceImpl<SysImportInfoMapper, SysImportInfo> implements SysImportInfoService { private final static String DEFINE_PROJECTID = "projectId"; @Autowired private TaskSeqService taskSeqService; @Autowired private DataflowServerClient dataflowServerClient; @Autowired SysImportInfoSplitService sysImportInfoSplitService; @Autowired private RedisTemplate redisTemplate; @Autowired private SysImportFileMapper sysImportFileMapper; @Resource private MinioConfig minioConfig; /** * 提交导入 * * @param sysImportInfoDTO * @return */ public R submitImport(SysImportInfoDTO sysImportInfoDTO) { // : 2023/3/16 调起文件转csv文件服务 Map<String, Object> batchSplitArgs = new HashMap<>(); batchSplitArgs.put("importId", sysImportInfoDTO.getImportId()); batchSplitArgs.put(DEFINE_PROJECTID, sysImportInfoDTO.getProjectId()); batchSplitArgs.put("spring.cloud.task.executionid", taskSeqService.selectTaskSeq()); batchSplitArgs.put("taskName", "file-split-csv"); batchSplitArgs.put("storageType", minioConfig.getStorageType()); batchSplitArgs.put("storageDomain", minioConfig.getStorageDomain()); batchSplitArgs.put("storageModuleCode", minioConfig.getStorageModuleCode()); pushBatch(batchSplitArgs, CacheConst.BATCH_FILE_SPLIT+":"+String.valueOf(batchSplitArgs.get(DEFINE_PROJECTID))); return R.ok(); } @Override public R importData(SysImportInfoDTO sysImportInfoDTO) { SysImportInfoSplit querySplit = new SysImportInfoSplit(); querySplit.setImportId(sysImportInfoDTO.getImportId()); querySplit.setDelFlag("0"); List<SysImportInfoSplit> splitList = sysImportInfoSplitService.getBaseMapper().selectList(Wrappers.query(querySplit)); if(CollectionUtils.isEmpty(splitList)){ log.info("没有可执行批处理数据={}", sysImportInfoDTO.getImportId()); return R.failed("不存在待上传数据"); } SysImportFile sysImportFile = sysImportFileMapper.selectById(sysImportInfoDTO.getFileId()); if(sysImportFile==null) return R.failed("上传数据源文件不存在"); splitList.forEach(o-> { Map<String, Object> batchFileArgs = new HashMap<>(); batchFileArgs.put("fileTpe", "csv"); batchFileArgs.put("fileId", o.getFileId()); batchFileArgs.put("splitId", o.getSplitId()); batchFileArgs.put("templateId", sysImportInfoDTO.getTemplateId()); batchFileArgs.put("importId", sysImportInfoDTO.getImportId()); batchFileArgs.put("sheetName", o.getSheetName()); batchFileArgs.put(DEFINE_PROJECTID, sysImportInfoDTO.getProjectId()); batchFileArgs.put("spring.cloud.task.executionid", taskSeqService.selectTaskSeq()); batchFileArgs.put("taskName", "excel-import"); batchFileArgs.put("userId", sysImportInfoDTO.getUserId()); batchFileArgs.put("userName", sysImportInfoDTO.getUserName()); batchFileArgs.put("orignFileName", sysImportFile.getFileName().substring(0, sysImportFile.getFileName().lastIndexOf('.'))); batchFileArgs.put("storageType", minioConfig.getStorageType()); batchFileArgs.put("storageDomain", minioConfig.getStorageDomain()); batchFileArgs.put("storageModuleCode", minioConfig.getStorageModuleCode()); pushBatch(batchFileArgs, CacheConst.BATCH_FILE_EXTRACT+":"+String.valueOf(batchFileArgs.get(DEFINE_PROJECTID))); }); return R.ok(); } private void pushBatch(Map<String, Object> params, String key){ if(CollectionUtils.isEmpty(params) || !StringUtils.hasText(key)){ return; } ListOperations<String, Map<String, Object>> ops = redisTemplate.opsForList(); ops.leftPush(key,params); } private Long launchBatch(Map<String, Object> params, String key){ ListOperations<String, Map<String, Object>> ops = redisTemplate.opsForList(); long batchResult = -1l; try{ if((batchResult = dataflowServerClient.launchBatchService(String.valueOf(params.get(DEFINE_PROJECTID)), params))<0){ ops.rightPush(key,params); } }catch (Exception e){ log.error("拉起task异常:{}", e); ops.rightPush(key,params); } return batchResult; } @Scheduled(cron = "0/1 * * * * ?") public void handleUnlaunchBatchFileSplit(){ handleBatch(CacheConst.BATCH_FILE_SPLIT + "*"); } @Scheduled(cron = "0/1 * * * * ?") public void handleUnlaunchBatchFileExtract(){ handleBatch(CacheConst.BATCH_FILE_EXTRACT + "*"); } public void handleBatch(String keys){ RedisConnectionFactory redisConnectionFactory = redisTemplate.getConnectionFactory(); if(null == redisConnectionFactory){ log.error("获取redis链接失败"); return; } ScanOptions options = ScanOptions.scanOptions().match(keys).build(); Cursor<byte[]> cursor = redisConnectionFactory.getConnection().scan(options); String key = null; while (cursor.hasNext()) { key = new String(cursor.next(), StandardCharsets.UTF_8); ListOperations<String, Map<String, Object>> ops = redisTemplate.opsForList(); Map<String, Object> split = null; while(!CollectionUtils.isEmpty(split = ops.rightPop(key))){ if(launchBatch(split, key)<0) break; } } } /** * 查询导入导出结果列表 * * @param page * @param sysImportInfo * @return */ public IPage<SysImportInfoVO> getSysImportInfoPage(Page page, SysImportInfo sysImportInfo) { sysImportInfo.setDelFlag("0"); return baseMapper.getSysImportInfoPage(page, sysImportInfo); } /** * 查询导入导出结果详情 * * @param importId * @return */ public SysImportInfoVO getSysImportInfoById(Long importId) { return baseMapper.getSysImportInfoById(importId); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.SysImportInfoSplit;import cn.chinatowercom.dataflow.backend.mapper.SysImportInfoSplitMapper;import cn.chinatowercom.dataflow.backend.service.SysImportInfoSplitService;import org.springframework.stereotype.Service;import java.util.List;/** * 导入导出文件拆分表 * * @author hj * @date 2023-03-13 10:41:31 */@Servicepublic class SysImportInfoSplitServiceImpl extends ServiceImpl<SysImportInfoSplitMapper, SysImportInfoSplit> implements SysImportInfoSplitService { @Override public List<SysImportInfoSplit> getByImportId(Long importId) { SysImportInfoSplit sysImportInfoSplit = new SysImportInfoSplit(); sysImportInfoSplit.setImportId(importId); return baseMapper.selectList(Wrappers.query(sysImportInfoSplit)); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportRuleType;import cn.chinatowercom.dataflow.backend.mapper.SysImportRuleTypeMapper;import cn.chinatowercom.dataflow.backend.service.SysImportRuleTypeService;import org.springframework.stereotype.Service;/** * 指标规则类型表 * * @author catfishing * @date 2023-03-13 15:20:16 */@Servicepublic class SysImportRuleTypeServiceImpl extends ServiceImpl<SysImportRuleTypeMapper, SysImportRuleType> implements SysImportRuleTypeService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportServer;import cn.chinatowercom.dataflow.backend.mapper.SysImportServerMapper;import cn.chinatowercom.dataflow.backend.service.SysImportServerService;import org.springframework.stereotype.Service;/** * * * @author catfishing * @date 2023-03-27 16:33:38 */@Servicepublic class SysImportServerServiceImpl extends ServiceImpl<SysImportServerMapper, SysImportServer> implements SysImportServerService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysImportSheet;import cn.chinatowercom.dataflow.backend.mapper.SysImportSheetMapper;import cn.chinatowercom.dataflow.backend.service.SysImportSheetService;import org.springframework.stereotype.Service;import java.util.List;/** * 模板属性配置表 * * @author catfishing * @date 2023-03-13 15:20:16 */@Servicepublic class SysImportSheetServiceImpl extends ServiceImpl<SysImportSheetMapper, SysImportSheet> implements SysImportSheetService { /** * 根据模板id查询模板下的sheet * * @param templateId * @return */ public List<SysImportSheet> getTemplateSheets(String templateId) { return baseMapper.getTemplateSheets(templateId); } @Override public SysImportSheet getSheetInfoBySheetName(String templateId, String sheetName) { return baseMapper.getSheetInfoBySheetName(templateId, sheetName); }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import cn.chinatowercom.dataflow.backend.component.DataSourceFeignClient;import cn.chinatowercom.dataflow.backend.constant.RowType;import cn.chinatowercom.dataflow.backend.constant.TemplateStatusEnum;import cn.chinatowercom.dataflow.backend.entity.datasource.DatasourceConnDTO;import cn.chinatowercom.dataflow.backend.entity.datasource.DatasourceJdbcConnDTO;import cn.chinatowercom.dataflow.backend.entity.dto.*;import cn.chinatowercom.dataflow.backend.entity.vo.ImportVo;import cn.chinatowercom.dataflow.backend.entity.vo.SysImportColumnVO;import cn.chinatowercom.dataflow.backend.mapper.SysImportTemplateMapper;import cn.chinatowercom.dataflow.backend.service.*;import cn.chinatowercom.dataflow.backend.utils.CellRangeAddressUtils;import cn.chinatowercom.dataflow.backend.utils.ExcelGenerator;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.baomidou.mybatisplus.core.metadata.IPage;import com.baomidou.mybatisplus.core.toolkit.IdWorker;import com.baomidou.mybatisplus.core.toolkit.Wrappers;import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.strongdata.dataflow.core.base.constant.SecurityConstants;import com.strongdata.dataflow.core.base.util.R;import com.strongdata.dataflow.core.base.xml.ColEntity;import com.strongdata.dataflow.core.base.xml.DataflowDataSetEntity;import com.strongdata.dataflow.core.base.xml.ReportEntity;import com.strongdata.dataflow.core.base.xml.RowEntity;import com.strongdata.dataflow.core.datasource.entity.ResultHolder;import lombok.SneakyThrows;import lombok.extern.slf4j.Slf4j;import org.apache.poi.ss.util.CellRangeAddress;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.util.CollectionUtils;import org.springframework.util.StringUtils;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.util.*;import java.util.regex.Pattern;import java.util.stream.Collectors;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;/** * 导入模板定义表 * * @author catfishing * @date 2023-02-01 14:11:22 */@Service@Slf4jpublic class SysImportTemplateServiceImpl extends ServiceImpl<SysImportTemplateMapper, SysImportTemplate> implements SysImportTemplateService { private final static String DEFINE_TEMPLATEID = "templateId"; private final static String DEFINE_SHEETIDS = "sheetIds"; @Autowired private SysProjectTemplateService sysProjectTemplateService; @Autowired private SysImportSheetService sysImportSheetService; @Autowired private SysImportColumnService sysImportColumnService; @Autowired private SysImportColumnRuleService sysImportColumnRuleService; @Autowired private DataSourceFeignClient dataSourceFeignClient; @SneakyThrows @Override public void exportTemplate(String templateIds, HttpServletRequest request, HttpServletResponse response) { try{ String zipFile = "templates.zip"; if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > -1) { zipFile = new String(zipFile.getBytes("GB2312"), StandardCharsets.ISO_8859_1); } else { zipFile = URLEncoder.encode(zipFile, "UTF-8"); zipFile = new String(zipFile.getBytes(StandardCharsets.UTF_8), "GBK"); } response.setContentType("application/zip"); response.setHeader("Content-disposition", "attachment;filename=" + zipFile); SysImportTemplate sysImportTemplate = baseMapper.selectById(templateIds); if (sysImportTemplate==null){ response.setStatus(HttpStatus.NOT_FOUND.value()); return; } List<SysImportSheet> sheetList = sysImportSheetService.getTemplateSheets(templateIds); if (sheetList.isEmpty()) { log.error("不存在模板配置信息:{}", templateIds); response.setStatus(HttpStatus.NOT_FOUND.value()); return; } ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); addZipFile(zos, exportExcel(sysImportTemplate, sheetList)); zos.close(); }catch(Exception e){ log.info("导出异常", e); response.setStatus(HttpStatus.NOT_FOUND.value()); } } @SneakyThrows File exportExcel(SysImportTemplate sysImportTemplate, List<SysImportSheet> sheetList){ String fileName = sysImportTemplate.getTemplateName()+".xlsx"; File file = new File(fileName); Map<String, List<List<Object>>> sheets = new HashMap<>(); List<ReportEntity> reportEntitys = JSON.parseArray(sysImportTemplate.getOriginalTemplate(), ReportEntity.class); Map<String,List<CellRangeAddress>> mergedRegionMap = new HashMap<>(); List<Object> data = null; int rowIndex = 0; for(ReportEntity re : reportEntitys){ List<List<Object>> datas = new LinkedList<>(); List<CellRangeAddress> mergedRegions = new ArrayList<>(); for(int i=0;i<=re.getRows().size()-1;i++){ RowEntity row = re.getRows().get(i); int colIndex = 0; if(!RowType.DATA_AREA.equals(row.getCategory())){ data = new LinkedList<>(); for(int j=0;j<=row.getCols().size()-1;j++){ boolean flag = false; ColEntity col = row.getCols().get(j); data.add(col.getValue()); if(col.getRowspan()>1 || col.getColspan()>1){ if(!CollectionUtils.isEmpty(mergedRegions)) { for (CellRangeAddress mergedRegion : mergedRegions) { if (!mergedRegion.containsColumn(colIndex) || !mergedRegion.containsRow(rowIndex)) { flag = true; break; } } }else{ mergedRegions.add(CellRangeAddressUtils.merge(rowIndex, rowIndex + col.getRowspan()-1, colIndex, colIndex + col.getColspan()-1)); } if(flag){ mergedRegions.add(CellRangeAddressUtils.merge(rowIndex, rowIndex + col.getRowspan()-1, colIndex, colIndex + col.getColspan()-1)); } } colIndex++; } datas.add(data); } rowIndex++; } sheets.put(re.getSheetId(), datas); mergedRegionMap.put(re.getSheetId(),mergedRegions); } new ExcelGenerator().generateExcel(file, sheetList, sheets, new ArrayList<>(), mergedRegionMap); return file; } @SneakyThrows void addZipFile(ZipOutputStream zos, File file){ ZipEntry entry = new ZipEntry(file.getName()); zos.putNextEntry(entry); Files.copy(file.toPath(), zos); zos.closeEntry(); } @Override public IPage<SysImportTemplate> findTemplateByProjectId(Page page, ImportTemplateDTO sysImportTemplate) { IPage<SysImportTemplate> templates = baseMapper.findTemplateByProjectId(page,sysImportTemplate); if(templates!=null && !CollectionUtils.isEmpty(templates.getRecords())){ templates.getRecords().forEach(o->o.setStatusDesc(TemplateStatusEnum.getValue(o.getStatus()))); } return templates; } @Override public List<SysImportTemplate> getSysImportTemplateAll(ImportTemplateDTO sysImportTemplate) { return baseMapper.getSysImportTemplateAll(sysImportTemplate); } @Override public ImportDetailDto getTemplateDetail(ImportVo importVo) { ImportDetailDto importDetail = new ImportDetailDto(); DatasourceConnDTO datasourceConnDTO = null; //获取模板列信息 SysImportSheet sheetInfo = sysImportSheetService.getSheetInfoBySheetName(importVo.getTemplateId(), importVo.getSheetName()); if(sheetInfo == null) return null; List<SysImportColumnVO> columnList = sysImportColumnService.getColumnRules(Arrays.asList(sheetInfo.getSheetId())); if(CollectionUtils.isEmpty(columnList)) return null; if((datasourceConnDTO = getConnectionInfo(sheetInfo.getDbId())) == null || (datasourceConnDTO.getDatasourceJdbcConnDTO() ==null && datasourceConnDTO.getDatasourceApiConnDTO() == null)){ log.error("数据源不存在,请先绑定数据源"); return null; } SysImportTemplate template = baseMapper.selectById(importVo.getTemplateId()); if (template==null){ log.error("模板信息不存在"); return null; } if(template.getIsCallback()>0 && template.getCallbackHttpUrl()!=null){ importDetail.setCallbackHttpUrl(template.getCallbackHttpUrl()); } importDetail.setSheet(sheetInfo); importDetail.setColumnList(columnList); importDetail.setDatasourceConnDTO(datasourceConnDTO); return importDetail; } @Override public List<FileDto> getFileByImportId(ImportVo importVo) { return new ArrayList<>(); } /** * JsonReportEntity json = JSON.parseObject(report, JsonReportEntity.class); * ReportEntity reportEntity = JsonToXMLUtil.JsonToXml(json); * * */ @Override @Transactional(transactionManager = "transactionManager") public R<Map<String, Object>> saveReport(String uuid, List<ReportEntity> reportEntitys) { Map<String, Object> result = new HashMap<>(); Map<String, Object> returnResult = null; List<Map<String, Object>> sheetIds = new ArrayList<>(); SysImportTemplate sysImportTemplate = new SysImportTemplate(); sysImportTemplate.setOriginalTemplate(eliminateDeleteSheet(reportEntitys)); for (ReportEntity reportEntity : reportEntitys) { sysImportTemplate.setTemplateName(reportEntity.getReportDescription()); if (!StringUtils.hasText(uuid)) { //模板不存在,创建模板、sheet、column、column_rule returnResult = addTemplate(sysImportTemplate, reportEntity); //第一次新增模板并创建多个sheet,保证只能创建一个模板 uuid = sysImportTemplate.getTemplateId(); } else if(StringUtils.hasText(uuid) && !StringUtils.hasText(reportEntity.getSheetId())){ //模板存在,sheet不存在,创建sheet、column、column_rule sysImportTemplate.setTemplateId(uuid); returnResult = addSheet(sysImportTemplate, reportEntity); }else if(StringUtils.hasText(uuid) && StringUtils.hasText(reportEntity.getSheetId())){ //模板存在,sheet存在,更新模板、sheet、column、column_rule if(-1==reportEntity.getDelFlag()){ deleteSheet(reportEntity); }else { sysImportTemplate.setTemplateId(uuid); returnResult = updateTemplate(sysImportTemplate, reportEntity); } } if(!CollectionUtils.isEmpty(returnResult)){ result.put(DEFINE_TEMPLATEID, returnResult.get(DEFINE_TEMPLATEID)); sheetIds.addAll((List)returnResult.get(DEFINE_SHEETIDS)); result.put(DEFINE_SHEETIDS, sheetIds); } } sysImportTemplate.setOriginalTemplate(eliminateDeleteSheet(reportEntitys)); this.updateById(sysImportTemplate); return R.ok(result).setMsg("保存成功"); } private String eliminateDeleteSheet(List<ReportEntity> reportEntitys){ List<ReportEntity> lastReportEntitys = new ArrayList<>(); if(CollectionUtils.isEmpty(reportEntitys)) return null; for (ReportEntity reportEntity : reportEntitys){ if(-1 != reportEntity.getDelFlag()){ lastReportEntitys.add(reportEntity); } } return JSON.toJSONString(lastReportEntitys); } Map<String, Object> updateTemplate(SysImportTemplate sysImportTemplate, ReportEntity reportEntity){ this.updateById(sysImportTemplate); deleteSheet(reportEntity); return addSheet(sysImportTemplate, reportEntity); } public void deleteSheet(ReportEntity reportEntity){ //简化逻辑,删除column、column_rule表数据重新插入 SysImportColumn column = new SysImportColumn(); column.setSheetId(reportEntity.getSheetId()); List<SysImportColumn> columnList = sysImportColumnService.list(Wrappers.query(column)); if(!CollectionUtils.isEmpty(columnList)){ List<Long> columnIds = columnList.stream().map(SysImportColumn::getColumnId).collect(Collectors.toList()); columnIds.forEach(o->{ SysImportColumnRule columnRule = new SysImportColumnRule(); columnRule.setColumnId(o); sysImportColumnRuleService.remove(Wrappers.query(columnRule)); }); sysImportColumnService.removeByIds(columnIds); sysImportSheetService.removeById(reportEntity.getSheetId()); } } Map<String, Object> addTemplate(SysImportTemplate sysImportTemplate, ReportEntity reportEntity){ this.save(sysImportTemplate); SysProjectTemplate pt = new SysProjectTemplate(); pt.setProjectId(reportEntity.getProjectId()); pt.setTemplateId(sysImportTemplate.getTemplateId()); sysProjectTemplateService.save(pt); return addSheet(sysImportTemplate, reportEntity); } Map<String, Object> addSheet(SysImportTemplate sysImportTemplate, ReportEntity reportEntity){ SysImportSheet sheet = new SysImportSheet(); LinkedList<SysImportColumn> columns = new LinkedList(); List<SysImportColumnRule> columnRules = new ArrayList(); sheet.setSheetId(IdWorker.getIdStr()); sheet.setTemplateId(sysImportTemplate.getTemplateId()); sheet.setSheetNum(reportEntity.getSheetNum()); sheet.setSheetName(reportEntity.getSheetName()==null?String.valueOf(reportEntity.getSheetId()):reportEntity.getSheetName()); reportEntity.setSheetId(sheet.getSheetId()); setSheetDbInfo(reportEntity, sheet); Map<String, Object> sheetId = new HashMap(); sheetId.put("sheetId", sheet.getSheetId()); sheetId.put("sheetNum", sheet.getSheetNum()); List<RowEntity> rows = reportEntity.getRows(); if(!CollectionUtils.isEmpty(rows)){ SysImportColumn ctemp = null; SysImportColumnRule crtmp = null; List<ColEntity> cols = null; ColEntity col = null; //循环行 for(int i=0; i<=rows.size()-1; i++){ setSheetRowCategory(rows.get(i), i, sheet); cols=rows.get(i).getCols(); if(!CollectionUtils.isEmpty(cols)){ //循环列 for(int j=0; j<=cols.size()-1; j++){ col = cols.get(j); //数据行存在非"=测试.province_name"格式值跳出本行循环 if(rows.get(i).getCategory().equals(RowType.DATA_AREA) && !judgeCellValue(col.getValue())) break; if(sheet.getStartCol() == null|| sheet.getStartCol().compareTo(0)<0) sheet.setStartCol(j); ctemp = new SysImportColumn(); //设置column表字段 ctemp = columns.size()-1 >= j ? columns.get(j) : ctemp; setColInfoByRowCategory(ctemp, sysImportTemplate.getTemplateId(), reportEntity, j, rows.get(i), col); if(columns.size()<=j && ctemp.getColumnId()!=null) columns.add(ctemp); //设置column_rule表字段 Map columnRuleMap = JSON.parseObject(col.getFill(), Map.class); if(rows.get(i).getCategory().equals(RowType.DATA_AREA) && StringUtils.hasText(col.getFill()) && StringUtils.hasText((String)(columnRuleMap.get("dataReg")))){ //此处扩展字段多规则校验 crtmp = new SysImportColumnRule(); crtmp.setColumnId(ctemp.getColumnId()); crtmp.setRuleTypeId((String)columnRuleMap.get("dataReg")); columnRules.add(crtmp); } } } } if(!CollectionUtils.isEmpty(columns)) sysImportColumnService.saveBatch(columns); sheet.setCommandText(joinCommandText(sheet, columns)); if(!CollectionUtils.isEmpty(columnRules)) sysImportColumnRuleService.saveBatch(columnRules); sysImportSheetService.save(sheet); }else{ sysImportSheetService.save(sheet); } Map<String, Object> addrResult = new HashMap<>(); List<Map<String, Object>> sheetIds = new ArrayList(); sheetIds.add(sheetId); addrResult.put(DEFINE_TEMPLATEID, sysImportTemplate.getTemplateId()); addrResult.put(DEFINE_SHEETIDS, sheetIds); return addrResult; } private DatasourceConnDTO getConnectionInfo(String datasetCode){ if(!StringUtils.hasText(datasetCode)) return null; ResultHolder datasource = dataSourceFeignClient.getDatasourceByDataSetCode(datasetCode, SecurityConstants.FROM_IN); Object respData = null; DatasourceConnDTO datasourceConnDTO = null; if(datasource==null || (respData = datasource.getData()) == null) { return null; } datasourceConnDTO = JSON.parseObject(JSON.toJSONString(respData), DatasourceConnDTO.class); return datasourceConnDTO; } private String joinCommandText(SysImportSheet sheet, LinkedList<SysImportColumn> columns){ DatasourceConnDTO datasourceConnDTO = null; DatasourceJdbcConnDTO datasourceJdbcConnDTO = null; if(CollectionUtils.isEmpty(columns) || !StringUtils.hasText(sheet.getDbId())) return null; if((datasourceConnDTO = getConnectionInfo(sheet.getDbId())) == null) return null; if(datasourceConnDTO.getDatasourceJdbcConnDTO() == null) { return null; } datasourceJdbcConnDTO = datasourceConnDTO.getDatasourceJdbcConnDTO(); return joinSQL(datasourceJdbcConnDTO.getDataSourceType(), datasourceConnDTO.getDatasetTableName(), columns); } private String joinSQL(String datasourceType, String tableName, LinkedList<SysImportColumn> columns){ StringBuilder sql = new StringBuilder(); StringBuilder values = new StringBuilder(); values.append("VALUES ("); if("mysql".equalsIgnoreCase(datasourceType)){ sql.append("INSERT INTO ").append(tableName).append(" ("); columns.forEach(o-> { sql.append(o.getImTo()).append(","); values.append("?,"); }); sql.deleteCharAt(sql.length()-1); sql.append(") "); values.deleteCharAt(values.length()-1); values.append(")"); sql.append(values); return sql.toString(); }else if("oracle".equalsIgnoreCase(datasourceType)){ sql.append("INSERT INTO ").append("\"").append(tableName).append("\"").append(" ("); columns.forEach(o-> { sql.append("\"").append(o.getImTo()).append("\"").append(","); values.append("?,"); }); sql.deleteCharAt(sql.length()-1); sql.append(") "); values.deleteCharAt(values.length()-1); values.append(")"); sql.append(values); return sql.toString(); } return null; } private void setColInfoByRowCategory(SysImportColumn ctemp, String templateId, ReportEntity reportEntity, int index, RowEntity re, ColEntity colEntity){ String transform = null; if(RowType.REPORT_HEAD.equals(re.getCategory()) && StringUtils.hasText(colEntity.getValue())){ if(ctemp.getColumnId()==null) ctemp.setColumnId(IdWorker.getId()); if(!StringUtils.hasText(ctemp.getTemplateId())) ctemp.setTemplateId(templateId); if(!StringUtils.hasText(ctemp.getSheetId())) ctemp.setSheetId(reportEntity.getSheetId()); ctemp.setImFrom(colEntity.getValue()); ctemp.setCellOrder(index); }else if(RowType.DATA_AREA.equals(re.getCategory()) && StringUtils.hasText(colEntity.getValue())){ if(ctemp.getColumnId()==null) ctemp.setColumnId(IdWorker.getId()); if(!StringUtils.hasText(ctemp.getTemplateId())) ctemp.setTemplateId(templateId); if(!StringUtils.hasText(ctemp.getSheetId())) ctemp.setSheetId(reportEntity.getSheetId()); ctemp.setImTo(colEntity.getColumnName()); transform = colEntity.getColumnType(); if(StringUtils.hasText(transform)) ctemp.setDataType(transform); if(StringUtils.hasText(colEntity.getDic())) ctemp.setDataTypeCustomize(colEntity.getDic()); }else if(RowType.DATA_DESC.equals(re.getCategory()) && StringUtils.hasText(colEntity.getValue())){ if(ctemp.getColumnId()==null) ctemp.setColumnId(IdWorker.getId()); if(!StringUtils.hasText(ctemp.getTemplateId())) ctemp.setTemplateId(templateId); if(!StringUtils.hasText(ctemp.getSheetId())) ctemp.setSheetId(reportEntity.getSheetId()); ctemp.setImportDesc(colEntity.getValue()); } } private boolean judgeCellValue(String colValue) { if(null == colValue) return false; Pattern pt = Pattern.compile("^=.*$"); return pt.matcher(colValue).matches(); } private void setSheetDbInfo(ReportEntity reportEntity, SysImportSheet sheet){ List<DataflowDataSetEntity> dataSets = reportEntity.getDataSets(); if(!CollectionUtils.isEmpty(dataSets)){ sheet.setDbId(dataSets.get(0).getName()); sheet.setCommandText(dataSets.get(0).getCommandtext()); } } private void setSheetRowCategory(RowEntity re, int index, SysImportSheet sheet){ if(RowType.REPORT_HEAD.equals(re.getCategory())){ sheet.setTitleRow(index); }else if(RowType.DATA_AREA.equals(re.getCategory())){ sheet.setStartRow(index); } }}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysProjectInfo;import cn.chinatowercom.dataflow.backend.mapper.SysProjectInfoMapper;import cn.chinatowercom.dataflow.backend.service.SysProjectInfoService;import org.springframework.stereotype.Service;/** * 项目信息表 * * @author catfishing * @date 2023-02-01 14:10:15 */@Servicepublic class SysProjectInfoServiceImpl extends ServiceImpl<SysProjectInfoMapper, SysProjectInfo> implements SysProjectInfoService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysProjectTemplate;import cn.chinatowercom.dataflow.backend.mapper.SysProjectTemplateMapper;import cn.chinatowercom.dataflow.backend.service.SysProjectTemplateService;import org.springframework.stereotype.Service;/** * 项目和模板关联表 * * @author catfishing * @date 2023-02-08 10:42:41 */@Servicepublic class SysProjectTemplateServiceImpl extends ServiceImpl<SysProjectTemplateMapper, SysProjectTemplate> implements SysProjectTemplateService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysProjectUserRelation;import cn.chinatowercom.dataflow.backend.mapper.SysProjectUserRelationMapper;import cn.chinatowercom.dataflow.backend.service.SysProjectUserRelationService;import org.springframework.stereotype.Service;/** * 项目人员关联表 * * @author catfishing * @date 2023-02-03 09:45:27 */@Servicepublic class SysProjectUserRelationServiceImpl extends ServiceImpl<SysProjectUserRelationMapper, SysProjectUserRelation> implements SysProjectUserRelationService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.dto.SysTemplateExportCriteria;import cn.chinatowercom.dataflow.backend.mapper.SysTemplateExportCriteriaMapper;import cn.chinatowercom.dataflow.backend.service.SysTemplateExportCriteriaService;import org.springframework.stereotype.Service;/** * 导出数据条件表 * * @author catfishing * @date 2023-03-13 15:20:16 */@Servicepublic class SysTemplateExportCriteriaServiceImpl extends ServiceImpl<SysTemplateExportCriteriaMapper, SysTemplateExportCriteria> implements SysTemplateExportCriteriaService {}
/* * * * * * * Copyright (c) 2022 strongdata Authors. All Rights Reserved. * * * * * * http://www.strongdata.com.cn * * * */package cn.chinatowercom.dataflow.backend.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import cn.chinatowercom.dataflow.backend.entity.TaskSeq;import cn.chinatowercom.dataflow.backend.mapper.TaskSeqMapper;import cn.chinatowercom.dataflow.backend.service.TaskSeqService;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/** * * * @author catfishing * @date 2023-04-04 15:30:58 */@Servicepublic class TaskSeqServiceImpl extends ServiceImpl<TaskSeqMapper, TaskSeq> implements TaskSeqService { @Override public int selectTaskSeq() { baseMapper.updateTaskSeq(); return baseMapper.selectTaskSeq(); }}
package cn.chinatowercom.dataflow.datasource.controller;import cn.chinatowercom.dataflow.datasource.service.DatasetFunctionService;import com.strongdata.dataflow.core.datasource.entity.DatasetTableFunction;import com.strongdata.dataflow.core.security.annotation.NoAuth;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;import java.util.List;/** * @Author gin * @Date 2023/2/20 11:58 */@Api(tags = "数据集:数据集方法")@RestController@RequestMapping("dataset/function")@NoAuth(value = false)public class DatasetFunctionController { @Resource private DatasetFunctionService datasetFunctionService; @ApiOperation("查询") @PostMapping("listByTableId/{tableId}") public List<DatasetTableFunction> listByTableId(@PathVariable String tableId) { return datasetFunctionService.listByTableId(tableId); }}
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
33
Edit dataset card